2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
41 package org.onap.portal.service;
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
47 import java.util.Objects;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
50 import java.util.stream.Collectors;
51 import javax.persistence.EntityManager;
52 import javax.persistence.Tuple;
53 import org.onap.portal.domain.db.ep.EpAppFunction;
54 import org.onap.portal.domain.db.fn.FnApp;
55 import org.onap.portal.domain.db.fn.FnFunction;
56 import org.onap.portal.domain.db.fn.FnRole;
57 import org.onap.portal.domain.db.fn.FnRoleFunction;
58 import org.onap.portal.domain.dto.transport.CentralV2Role;
59 import org.onap.portal.domain.dto.transport.GlobalRoleWithApplicationRoleFunction;
60 import org.onap.portal.exception.RoleFunctionException;
61 import org.onap.portal.logging.logic.EPLogUtil;
62 import org.onap.portal.service.appFunction.EpAppFunctionService;
63 import org.onap.portal.service.app.FnAppService;
64 import org.onap.portal.service.role.FnRoleService;
65 import org.onap.portal.utils.EPCommonSystemProperties;
66 import org.onap.portal.utils.EPUserUtils;
67 import org.onap.portal.utils.EcompPortalUtils;
68 import org.onap.portal.utils.PortalConstants;
69 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
70 import org.onap.portalsdk.core.util.SystemProperties;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.http.HttpEntity;
73 import org.springframework.http.HttpMethod;
74 import org.springframework.http.ResponseEntity;
75 import org.springframework.stereotype.Service;
76 import org.springframework.web.client.RestTemplate;
79 public class ExternalAccessRolesService {
81 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
82 private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
83 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
84 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
85 private static final String FUNCTION_CODE_PARAMS = "functionCode";
86 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
87 private static final String OWNER = ".owner";
88 private static final String ADMIN = ".admin";
89 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
90 private static final String FUNCTION_PIPE = "|";
91 private static final String EXTERNAL_AUTH_PERMS = "perms";
92 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
93 private static final String IS_EMPTY_JSON_STRING = "{}";
94 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
95 private static final String APP_ID = "appId";
96 private static final String ROLE_NAME = "name";
97 private static final String APP_ID_EQUALS = " app_id = ";
99 private static final String GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS = "select"
100 + " distinct d.roleId as roleId,"
101 + " d.roleName as roleName,"
102 + " d.activeYn as active,"
103 + " d.priority as priority,"
104 + " c.epAppFunction.functionCd as functionCd,"
105 + " e.functionName as functionName,"
106 + " c.epAppFunction.appId as appId,"
107 + " c.roleAppId as roleAppId"
111 + " EpAppRoleFunction c,"
115 + " b.appId = c.appId.appId"
116 + " and a.appId = c.roleAppId"
117 + " and b.enabled = 'Y'"
118 + " and c.fnRole.roleId = d.roleId"
119 + " and d.activeYn = 'Y'"
120 + " and e.functionCd = c.epAppFunction.functionCd"
121 + " and c.appId.appId = :appId"
122 + " and e.appId.appId = c.appId.appId";
124 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesService.class);
125 private final RestTemplate template = new RestTemplate();
127 private final FnRoleService fnRoleService;
128 private final FnAppService fnAppService;
129 private final EntityManager entityManager;
130 private final EpAppFunctionService epAppFunctionService;
133 public ExternalAccessRolesService(FnRoleService fnRoleService,
134 FnAppService fnAppService, EntityManager entityManager,
135 EpAppFunctionService epAppFunctionService) {
136 this.fnRoleService = fnRoleService;
137 this.fnAppService = fnAppService;
138 this.entityManager = entityManager;
139 this.epAppFunctionService = epAppFunctionService;
142 String getFunctionCodeType(String roleFuncItem) {
144 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
145 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
147 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
148 || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
150 } else if (roleFuncItem.contains(FUNCTION_PIPE)
151 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
152 type = EcompPortalUtils.getFunctionType(roleFuncItem);
157 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
158 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
161 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
162 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
165 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
166 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
169 List<FnRole> getPortalAppRoleInfo(Long roleId) {
170 return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId);
173 ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
174 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
175 ResponseEntity<String> getResponse = template
176 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
177 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
178 if (getResponse.getStatusCode().value() == 200) {
179 logger.debug(EELFLoggerDelegate.debugLogger,
180 "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
181 getResponse.getBody());
183 logger.error(EELFLoggerDelegate.errorLogger,
184 "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
185 getResponse.getBody());
186 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
191 Map<String, FnRole> getAppRoleNamesWithUnderscoreMap(FnApp app) {
192 final Map<String, FnRole> currentRolesInDB = new HashMap<>();
193 List<FnRole> getCurrentRoleList = null;
194 final Map<String, Long> appParams = new HashMap<>();
195 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
196 getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
198 appParams.put("appId", app.getId());
199 getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId());
201 for (FnRole role : getCurrentRoleList) {
202 currentRolesInDB.put(role.getRoleName()
203 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
205 return currentRolesInDB;
208 List<CentralV2Role> createCentralRoleObject(List<FnApp> app, List<FnRole> roleInfo,
209 List<CentralV2Role> roleList) throws RoleFunctionException {
210 for (FnRole role : roleInfo) {
211 List<EpAppFunction> cenRoleFuncList = epAppFunctionService
212 .getAppRoleFunctionList(role.getId(), app.get(0).getId());
213 SortedSet<FnRoleFunction> roleFunctionSet = new TreeSet<>();
214 for (EpAppFunction roleFunc : cenRoleFuncList) {
215 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
216 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
217 String type = getFunctionCodeType(roleFunc.getFunctionCd());
218 String action = getFunctionCodeAction(roleFunc.getFunctionCd());
219 FnRoleFunction cenRoleFunc = new FnRoleFunction(role, FnFunction.builder().code(functionCode).name(roleFunc.getFunctionName()).type(type).action(action).build());
221 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
222 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
223 CentralV2Role cenRole;
224 if (role.getAppRoleId() == null) {
225 cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated())
226 .modified(role.getModified())
227 .rowNum(role.getRowNum()).name(role.getRoleName())
228 .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
229 .childRoles(childRoles).parentRoles(parentRoles).build();
231 cenRole = CentralV2Role.builder().id(role.getAppRoleId())
232 .created(role.getCreated()).modified(role.getModified())
233 .rowNum(role.getRowNum()).name(role.getRoleName())
234 .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
235 .childRoles(childRoles).parentRoles(parentRoles).build();
237 roleList.add(cenRole);
242 String getFunctionCodeAction(String roleFuncItem) {
243 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
246 List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
247 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
248 List<CentralV2Role> roleList = new ArrayList<>();
250 List<FnApp> app = fnAppService.getByUebKey(uebkey);
251 List<FnRole> appRolesList = fnRoleService.getAppRoles(app.get(0).getId());
252 roleList = createCentralRoleObject(app, appRolesList, roleList);
253 if (!Objects.equals(app.get(0).getId(), PortalConstants.PORTAL_APP_ID)) {
254 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
255 List<FnRole> globalRolesList = fnRoleService.getGlobalRolesOfPortal();
256 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
257 if (!globalRolesList.isEmpty()) {
258 for (FnRole eprole : globalRolesList) {
259 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
260 portalsGlobalRolesFinlaList.add(cenRole);
262 roleList.addAll(globalRoleList);
263 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
264 CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
266 if (result == null) {
271 for (FnRole role : globalRolesList) {
272 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
273 roleList.add(cenRole);
277 } catch (Exception e) {
278 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
281 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
282 return roleList.stream().distinct().collect(Collectors.toList());
285 private CentralV2Role convertRoleToCentralV2Role(FnRole role) {
286 return CentralV2Role.builder().id(role.getId()).created(role.getCreated())
287 .modified(role.getModified())
288 .rowNum(role.getRowNum()).name(role.getRoleName()).active(role.getActiveYn())
289 .priority(role.getPriority()).roleFunctions(new TreeSet<>()).childRoles(new TreeSet<>())
290 .parentRoles(new TreeSet<>()).build();
293 private List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
294 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
296 List<Tuple> tuples = entityManager.createQuery(GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS, Tuple.class)
297 .setParameter("appId", appId)
299 globalRoles = tuples.stream().map(this::tupleToGlobalRoleWithApplicationRoleFunction).collect(Collectors.toList());
300 } catch (Exception e) {
301 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
303 List<CentralV2Role> roleList = new ArrayList<>();
304 if (globalRoles.size() > 0) {
305 roleList = finalListOfCentralRoles(globalRoles);
310 private GlobalRoleWithApplicationRoleFunction tupleToGlobalRoleWithApplicationRoleFunction(Tuple tuple) {
311 return GlobalRoleWithApplicationRoleFunction.builder().roleId((Long) tuple.get("roleId"))
312 .roleName((String) tuple.get("roleName"))
313 .functionCd((String) tuple.get("functionCd")).functionName((String) tuple.get("functionName"))
314 .active((Boolean) tuple.get("active")).priority((Integer) tuple.get("priority"))
315 .appId((Long) tuple.get("appId")).roleAppId((Long) tuple.get("roleAppId")).build();
318 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
319 List<CentralV2Role> rolesfinalList = new ArrayList<>();
320 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
321 boolean found = false;
322 for (CentralV2Role cenRole : rolesfinalList) {
323 if (role.getRoleId().equals(cenRole.getId())) {
324 SortedSet<FnRoleFunction> roleFunctions = cenRole.getRoleFunctions();
325 FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
326 roleFunctions.add(cenRoleFun);
327 cenRole.setRoleFunctions(roleFunctions);
333 CentralV2Role cenrole = new CentralV2Role();
334 cenrole.setName(role.getRoleName());
335 cenrole.setId(role.getRoleId());
336 cenrole.setActive(role.getActive());
337 cenrole.setPriority(role.getPriority());
338 SortedSet<FnRoleFunction> roleFunctions = new TreeSet<>();
339 FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
340 roleFunctions.add(cenRoleFun);
341 cenrole.setRoleFunctions(roleFunctions);
342 rolesfinalList.add(cenrole);
345 return rolesfinalList;
348 private FnRoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
352 FnRoleFunction cenRoleFun = null;
353 if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
354 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
355 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
356 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
357 cenRoleFun = FnRoleFunction.builder().build();
358 FnRole fnRole = new FnRole();
359 FnFunction fnFunction = FnFunction.builder().functionCd(instance).name(role.getFunctionName()).type(type).action(action).build();
360 cenRoleFun.setRole(fnRole);
361 cenRoleFun.setFunctionCd(fnFunction);
363 type = getFunctionCodeType(role.getFunctionCd());
364 action = getFunctionCodeAction(role.getFunctionCd());
365 FnFunction fnFunction = FnFunction.builder().functionCd(role.getFunctionCd()).name(role.getFunctionName()).type(type).action(action).build();
366 cenRoleFun.setRole(new FnRole());
367 cenRoleFun.setFunctionCd(fnFunction);