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 com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.DeserializationFeature;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import com.fasterxml.jackson.databind.type.TypeFactory;
47 import java.io.IOException;
48 import java.util.ArrayList;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.List;
54 import java.util.Objects;
55 import java.util.Optional;
57 import java.util.SortedSet;
58 import java.util.TreeSet;
59 import java.util.stream.Collectors;
60 import javax.management.InvalidApplicationException;
61 import javax.persistence.EntityManager;
62 import javax.persistence.Query;
63 import javax.persistence.Tuple;
64 import org.json.JSONArray;
65 import org.json.JSONObject;
66 import org.onap.portal.domain.db.DomainVo;
67 import org.onap.portal.domain.db.ep.EpAppFunction;
68 import org.onap.portal.domain.db.ep.EpAppRoleFunction;
69 import org.onap.portal.domain.db.fn.FnApp;
70 import org.onap.portal.domain.db.fn.FnFunction;
71 import org.onap.portal.domain.db.fn.FnRole;
72 import org.onap.portal.domain.db.fn.FnRoleFunction;
73 import org.onap.portal.domain.db.fn.FnUser;
74 import org.onap.portal.domain.db.fn.FnUserRole;
75 import org.onap.portal.domain.dto.ecomp.EPAppRoleFunction;
76 import org.onap.portal.domain.dto.ecomp.EPUserAppRolesRequest;
77 import org.onap.portal.domain.dto.ecomp.ExternalRoleDetails;
78 import org.onap.portal.domain.dto.ecomp.UploadRoleFunctionExtSystem;
79 import org.onap.portal.domain.dto.model.ExternalSystemUser;
80 import org.onap.portal.domain.dto.transport.BulkUploadRoleFunction;
81 import org.onap.portal.domain.dto.transport.BulkUploadUserRoles;
82 import org.onap.portal.domain.dto.transport.CentralApp;
83 import org.onap.portal.domain.dto.transport.CentralRole;
84 import org.onap.portal.domain.dto.transport.CentralRoleFunction;
85 import org.onap.portal.domain.dto.transport.CentralUser;
86 import org.onap.portal.domain.dto.transport.CentralUserApp;
87 import org.onap.portal.domain.dto.transport.CentralV2Role;
88 import org.onap.portal.domain.dto.transport.CentralV2User;
89 import org.onap.portal.domain.dto.transport.CentralV2UserApp;
90 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
91 import org.onap.portal.domain.dto.transport.EcompUserRoles;
92 import org.onap.portal.domain.dto.transport.ExternalAccessPerms;
93 import org.onap.portal.domain.dto.transport.ExternalAccessPermsDetail;
94 import org.onap.portal.domain.dto.transport.ExternalAccessRole;
95 import org.onap.portal.domain.dto.transport.ExternalAccessRolePerms;
96 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
97 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
98 import org.onap.portal.domain.dto.transport.GlobalRoleWithApplicationRoleFunction;
99 import org.onap.portal.domain.dto.transport.LocalRole;
100 import org.onap.portal.exception.DeleteDomainObjectFailedException;
101 import org.onap.portal.exception.ExternalAuthSystemException;
102 import org.onap.portal.exception.InactiveApplicationException;
103 import org.onap.portal.exception.InvalidUserException;
104 import org.onap.portal.exception.RoleFunctionException;
105 import org.onap.portal.logging.logic.EPLogUtil;
106 import org.onap.portal.service.app.FnAppService;
107 import org.onap.portal.service.appFunction.EpAppFunctionService;
108 import org.onap.portal.service.appRoleFunction.EpAppRoleFunctionService;
109 import org.onap.portal.service.role.FnRoleService;
110 import org.onap.portal.service.roleFunction.FnRoleFunctionService;
111 import org.onap.portal.service.user.FnUserService;
112 import org.onap.portal.utils.EPCommonSystemProperties;
113 import org.onap.portal.utils.EPUserUtils;
114 import org.onap.portal.utils.EcompPortalUtils;
115 import org.onap.portal.utils.PortalConstants;
116 import org.onap.portalsdk.core.domain.Role;
117 import org.onap.portalsdk.core.domain.RoleFunction;
118 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
119 import org.onap.portalsdk.core.restful.domain.EcompRole;
120 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
121 import org.onap.portalsdk.core.restful.domain.EcompUser;
122 import org.onap.portalsdk.core.util.SystemProperties;
123 import org.springframework.beans.factory.annotation.Autowired;
124 import org.springframework.http.HttpEntity;
125 import org.springframework.http.HttpHeaders;
126 import org.springframework.http.HttpMethod;
127 import org.springframework.http.HttpStatus;
128 import org.springframework.http.ResponseEntity;
129 import org.springframework.stereotype.Service;
130 import org.springframework.transaction.annotation.Propagation;
131 import org.springframework.transaction.annotation.Transactional;
132 import org.springframework.web.client.HttpClientErrorException;
133 import org.springframework.web.client.RestTemplate;
135 @SuppressWarnings("unchecked")
137 public class ExternalAccessRolesService {
139 private static final String APP_ROLE_NAME_PARAM = "appRoleName";
140 private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
141 private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
142 private static final String FUNCTION_CODE_PARAMS = "functionCode";
143 private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
144 private static final String OWNER = ".owner";
145 private static final String ADMIN = ".admin";
146 private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
147 private static final String FUNCTION_PIPE = "|";
148 private static final String EXTERNAL_AUTH_PERMS = "perms";
149 private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
150 private static final String IS_EMPTY_JSON_STRING = "{}";
151 private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
152 private static final String APP_ID = "appId";
153 private static final String ROLE_NAME = "name";
154 private static final String APP_ID_EQUALS = " app_id = ";
156 private static final String GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS = "select"
157 + " distinct d.roleId as roleId,"
158 + " d.roleName as roleName,"
159 + " d.activeYn as active,"
160 + " d.priority as priority,"
161 + " c.epAppFunction.functionCd as functionCd,"
162 + " e.functionName as functionName,"
163 + " c.epAppFunction.appId as appId,"
164 + " c.roleAppId as roleAppId"
168 + " EpAppRoleFunction c,"
172 + " b.appId = c.appId.appId"
173 + " and a.appId = c.roleAppId"
174 + " and b.enabled = 'Y'"
175 + " and c.fnRole.roleId = d.roleId"
176 + " and d.activeYn = 'Y'"
177 + " and e.functionCd = c.epAppFunction.functionCd"
178 + " and c.appId.appId = :appId"
179 + " and e.appId.appId = c.appId.appId";
181 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesService.class);
182 private final RestTemplate template = new RestTemplate();
184 private final FnUserService fnUserService;
185 private final FnRoleService fnRoleService;
186 private final FnAppService fnAppService;
187 private final EntityManager entityManager;
188 private final FnRoleFunctionService fnRoleFunctionService;
189 private final EpAppFunctionService epAppFunctionService;
190 private final EpAppRoleFunctionService epAppRoleFunctionService;
191 private final LocalRoleService localRoleService;
192 private final BulkUploadUserRolesService bulkUploadUserRolesService;
195 public ExternalAccessRolesService(
196 final FnUserService fnUserService,
197 final FnRoleService fnRoleService,
198 final FnAppService fnAppService, EntityManager entityManager,
199 FnRoleFunctionService fnRoleFunctionService,
200 final EpAppFunctionService epAppFunctionService,
201 final EpAppRoleFunctionService epAppRoleFunctionService,
202 final LocalRoleService localRoleService,
203 BulkUploadUserRolesService bulkUploadUserRolesService) {
204 this.fnUserService = fnUserService;
205 this.fnRoleService = fnRoleService;
206 this.fnAppService = fnAppService;
207 this.entityManager = entityManager;
208 this.fnRoleFunctionService = fnRoleFunctionService;
209 this.epAppFunctionService = epAppFunctionService;
210 this.epAppRoleFunctionService = epAppRoleFunctionService;
211 this.localRoleService = localRoleService;
212 this.bulkUploadUserRolesService = bulkUploadUserRolesService;
215 public String getFunctionCodeType(String roleFuncItem) {
217 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
218 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
220 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
221 || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
223 } else if (roleFuncItem.contains(FUNCTION_PIPE)
224 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
225 type = EcompPortalUtils.getFunctionType(roleFuncItem);
230 private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
231 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
234 private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
235 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
238 private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
239 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
242 List<FnRole> getPortalAppRoleInfo(Long roleId) {
243 return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId);
246 ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
247 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
248 ResponseEntity<String> getResponse = template
249 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
250 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
251 if (getResponse.getStatusCode().value() == 200) {
252 logger.debug(EELFLoggerDelegate.debugLogger,
253 "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
254 getResponse.getBody());
256 logger.error(EELFLoggerDelegate.errorLogger,
257 "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
258 getResponse.getBody());
259 EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
264 Map<String, FnRole> getAppRoleNamesWithUnderscoreMap(FnApp app) {
265 final Map<String, FnRole> currentRolesInDB = new HashMap<>();
266 List<FnRole> getCurrentRoleList = null;
267 final Map<String, Long> appParams = new HashMap<>();
268 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
269 getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
271 appParams.put("appId", app.getId());
272 getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId());
274 for (FnRole role : getCurrentRoleList) {
275 currentRolesInDB.put(role.getRoleName()
276 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
278 return currentRolesInDB;
281 List<CentralV2Role> createCentralRoleObject(List<FnApp> app, List<FnRole> roleInfo,
282 List<CentralV2Role> roleList) throws RoleFunctionException {
283 for (FnRole role : roleInfo) {
284 List<EpAppFunction> cenRoleFuncList = epAppFunctionService
285 .getAppRoleFunctionList(role.getId(), app.get(0).getId());
286 SortedSet<DomainVo> roleFunctionSet = new TreeSet<>();
287 for (EpAppFunction roleFunc : cenRoleFuncList) {
288 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
289 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
290 String type = getFunctionCodeType(roleFunc.getFunctionCd());
291 String action = getFunctionCodeAction(roleFunc.getFunctionCd());
292 FnRoleFunction cenRoleFunc = new FnRoleFunction(role,
293 FnFunction.builder().code(functionCode).name(roleFunc.getFunctionName()).type(type).action(action)
296 SortedSet<CentralV2Role> childRoles = new TreeSet<>();
297 SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
298 CentralV2Role cenRole;
299 if (role.getAppRoleId() == null) {
300 cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated())
301 .modified(role.getModified())
302 .rowNum(role.getRowNum()).name(role.getRoleName())
303 .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
304 .childRoles(childRoles).parentRoles(parentRoles).build();
306 cenRole = CentralV2Role.builder().id(role.getAppRoleId())
307 .created(role.getCreated()).modified(role.getModified())
308 .rowNum(role.getRowNum()).name(role.getRoleName())
309 .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
310 .childRoles(childRoles).parentRoles(parentRoles).build();
312 roleList.add(cenRole);
317 public String getFunctionCodeAction(String roleFuncItem) {
318 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
321 public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
322 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
323 List<CentralV2Role> roleList = new ArrayList<>();
325 List<FnApp> app = fnAppService.getByUebKey(uebkey);
326 List<FnRole> appRolesList = fnRoleService.getAppRoles(app.get(0).getId());
327 roleList = createCentralRoleObject(app, appRolesList, roleList);
328 if (!Objects.equals(app.get(0).getId(), PortalConstants.PORTAL_APP_ID)) {
329 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
330 List<FnRole> globalRolesList = fnRoleService.getGlobalRolesOfPortal();
331 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
332 if (!globalRolesList.isEmpty()) {
333 for (FnRole eprole : globalRolesList) {
334 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
335 portalsGlobalRolesFinlaList.add(cenRole);
337 roleList.addAll(globalRoleList);
338 for (CentralV2Role role : portalsGlobalRolesFinlaList) {
339 CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
341 if (result == null) {
346 for (FnRole role : globalRolesList) {
347 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
348 roleList.add(cenRole);
352 } catch (Exception e) {
353 logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
356 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
357 return roleList.stream().distinct().collect(Collectors.toList());
360 private List<CentralV2Role> getGlobalRolesOfApplication(final Long appId) {
361 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
363 List<Tuple> tuples = entityManager.createQuery(GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS, Tuple.class)
364 .setParameter("appId", appId)
366 globalRoles = tuples.stream().map(this::tupleToGlobalRoleWithApplicationRoleFunction)
367 .collect(Collectors.toList());
368 } catch (Exception e) {
369 logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
371 List<CentralV2Role> roleList = new ArrayList<>();
372 if (globalRoles.size() > 0) {
373 roleList = finalListOfCentralRoles(globalRoles);
378 private GlobalRoleWithApplicationRoleFunction tupleToGlobalRoleWithApplicationRoleFunction(Tuple tuple) {
379 return GlobalRoleWithApplicationRoleFunction.builder().roleId((Long) tuple.get("roleId"))
380 .roleName((String) tuple.get("roleName"))
381 .functionCd((String) tuple.get("functionCd")).functionName((String) tuple.get("functionName"))
382 .active((Boolean) tuple.get("active")).priority((Integer) tuple.get("priority"))
383 .appId((Long) tuple.get("appId")).roleAppId((Long) tuple.get("roleAppId")).build();
386 private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
387 List<CentralV2Role> rolesfinalList = new ArrayList<>();
388 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
389 boolean found = false;
390 for (CentralV2Role cenRole : rolesfinalList) {
391 if (role.getRoleId().equals(cenRole.getId())) {
392 SortedSet<DomainVo> roleFunctions = new TreeSet<>();
393 for (DomainVo vo : cenRole.getRoleFunctions()) {
394 Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
395 roleFunction.ifPresent(roleFunctions::add);
397 FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
398 roleFunctions.add(cenRoleFun);
399 cenRole.setRoleFunctions(roleFunctions);
405 CentralV2Role cenrole = new CentralV2Role();
406 cenrole.setName(role.getRoleName());
407 cenrole.setId(role.getRoleId());
408 cenrole.setActive(role.getActive());
409 cenrole.setPriority(role.getPriority());
410 SortedSet<DomainVo> roleFunctions = new TreeSet<>();
411 FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
412 roleFunctions.add(cenRoleFun);
413 cenrole.setRoleFunctions(roleFunctions);
414 rolesfinalList.add(cenrole);
417 return rolesfinalList;
420 public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
421 final Map<String, String> params = new HashMap<>();
423 CentralV2User cenV2User = null;
424 String result = null;
426 params.put("orgUserIdValue", loginId);
427 List<FnApp> appList = getApp(uebkey);
428 if (!appList.isEmpty()) {
429 user = fnUserService.loadUserByUsername(loginId);
430 ObjectMapper mapper = new ObjectMapper();
431 cenV2User = getV2UserAppRoles(loginId, uebkey);
432 result = mapper.writeValueAsString(cenV2User);
434 } catch (Exception e) {
435 logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
441 public void syncApplicationRolesWithEcompDB(FnApp app) {
443 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
444 // Sync functions and roles assigned to it which also creates new roles if does
445 // not exits in portal
446 syncRoleFunctionFromExternalAccessSystem(app);
447 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
448 ObjectMapper mapper = new ObjectMapper();
449 logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
450 // Get Permissions from External Auth System
451 JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app.getId(), app.getAuthNamespace());
452 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
454 List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
455 List<FnRole> finalRoleList = new ArrayList<>();
456 for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
457 FnRole ecompRole = convertExternalRoleDetailsToEpRole(externalRole);
458 finalRoleList.add(ecompRole);
460 List<FnRole> applicationRolesList;
461 applicationRolesList = getAppRoles(app.getId());
462 List<String> applicationRoleIdList = new ArrayList<>();
463 for (FnRole applicationRole : applicationRolesList) {
464 applicationRoleIdList.add(applicationRole.getRoleName());
466 List<FnRole> roleListToBeAddInEcompDB = new ArrayList<>();
467 for (FnRole aafRole : finalRoleList) {
468 if (!applicationRoleIdList.contains(aafRole.getRoleName())) {
469 roleListToBeAddInEcompDB.add(aafRole);
472 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
473 // Check if roles exits in external Access system and if not make inactive in DB
474 inactiveRolesNotInExternalAuthSystem(app.getId(), finalRoleList, applicationRolesList);
475 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
476 // Add new roles in DB and updates role description in External Auth System
477 addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
478 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
479 } catch (HttpClientErrorException e) {
480 logger.error(EELFLoggerDelegate.errorLogger,
481 "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
482 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
483 } catch (Exception e) {
484 logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
488 public List<FnRole> getAppRoles(Long appId) {
489 List<FnRole> applicationRoles;
492 applicationRoles = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
494 applicationRoles = fnRoleService.retrieveAppRolesByAppId(appId);
496 } catch (Exception e) {
497 logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
500 return applicationRoles;
503 private FnRole convertExternalRoleDetailsToEpRole(ExternalRoleDetails externalRoleDetails) {
504 FnRole role = new FnRole();
505 role.setActiveYn(true);
506 role.setAppId(externalRoleDetails.getAppId());
507 role.setAppRoleId(externalRoleDetails.getAppRoleId());
508 role.setRoleName(externalRoleDetails.getName());
509 role.setPriority(externalRoleDetails.getPriority());
513 public List<ExternalRoleDetails> getExternalRoleDetailsList(FnApp app, ObjectMapper mapper, JSONArray extRole)
515 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
516 ExternalAccessPerms externalAccessPerms;
517 List<String> functionCodelist = new ArrayList<>();
518 Map<String, FnRole> curRolesMap = getAppRoleNamesMap(app.getId());
519 Map<String, FnRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
520 for (int i = 0; i < extRole.length(); i++) {
521 ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
522 EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
523 JSONObject Role = (JSONObject) extRole.get(i);
524 String name = extRole.getJSONObject(i).getString(ROLE_NAME);
525 String actualRoleName = name.substring(app.getAuthNamespace().length() + 1);
526 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
527 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
529 SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
530 if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
531 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
532 for (int j = 0; j < extPerm.length(); j++) {
533 JSONObject perms = extPerm.getJSONObject(j);
534 boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
535 app.getAuthNamespace());
536 if (isNamespaceMatching) {
537 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
538 perms.getString("instance"), perms.getString("action"));
539 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
540 functionCodelist.add(ePAppRoleFunction.getCode());
541 externalAccessPermsOfRole.add(externalAccessPerms);
545 externalRoleDetail.setActive(true);
546 externalRoleDetail.setName(actualRoleName);
547 if (app.getId() == 1) {
548 externalRoleDetail.setAppId(null);
550 externalRoleDetail.setAppId(app.getId());
552 FnRole currRole = null;
553 currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
554 ? curRolesUnderscoreMap.get(actualRoleName)
555 : curRolesMap.get(actualRoleName);
557 if (currRole != null) {
558 roleId = currRole.getId();
560 final Map<String, EpAppRoleFunction> roleFunctionsMap = new HashMap<>();
561 if (roleId != null) {
562 List<EpAppRoleFunction> appRoleFunctions = epAppRoleFunctionService
563 .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), roleId);
564 if (!appRoleFunctions.isEmpty()) {
565 for (EpAppRoleFunction roleFunc : appRoleFunctions) {
566 roleFunctionsMap.put(roleFunc.getEpAppFunction().getFunctionCd(), roleFunc);
570 if (!externalAccessPermsOfRole.isEmpty()) {
571 // Adding functions to role
572 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
573 EpAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
574 if (checkRoleFunctionExits == null) {
575 String funcCode = externalpermission.getType().substring(app.getAuthNamespace().length() + 1)
576 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
577 + externalpermission.getAction();
578 EpAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
579 if (checkRoleFunctionPipeExits == null) {
581 logger.debug(EELFLoggerDelegate.debugLogger,
582 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
583 externalpermission.getInstance());
584 List<EpAppFunction> roleFunction = epAppFunctionService
585 .getAppFunctionOnCodeAndAppId(app.getId(), externalpermission.getInstance());
586 if (roleFunction.isEmpty()) {
587 roleFunction = epAppFunctionService
588 .getAppFunctionOnCodeAndAppId(app.getId(), funcCode);
590 if (!roleFunction.isEmpty()) {
591 EpAppRoleFunction apRoleFunction = new EpAppRoleFunction();
592 apRoleFunction.setAppId(app);
593 apRoleFunction.setFnRole(currRole);
594 apRoleFunction.setEpAppFunction(roleFunction.get(0));
595 epAppRoleFunctionService.save(apRoleFunction);
597 } catch (Exception e) {
598 logger.error(EELFLoggerDelegate.errorLogger,
599 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
605 externalRoleDetailsList.add(externalRoleDetail);
607 return externalRoleDetailsList;
610 private Map<String, FnRole> getAppRoleNamesMap(final Long appId) {
611 final Map<String, FnRole> currentRolesInDB = new HashMap<>();
612 List<FnRole> getCurrentRoleList = null;
613 final Map<String, Long> appParams = new HashMap<>();
614 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
615 getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
617 getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(appId);
619 for (FnRole role : getCurrentRoleList) {
620 currentRolesInDB.put(role.getRoleName(), role);
622 return currentRolesInDB;
625 public JSONArray getAppRolesJSONFromExtAuthSystem(final long appId, final String authNamespace) throws Exception {
626 ResponseEntity<String> response = null;
627 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
628 HttpEntity<String> entity = new HttpEntity<>(headers);
629 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
630 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
631 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
632 + "roles/ns/" + authNamespace, HttpMethod.GET, entity, String.class);
633 String res = response.getBody();
634 logger.debug(EELFLoggerDelegate.debugLogger,
635 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
637 JSONObject jsonObj = new JSONObject(res);
638 JSONArray extRole = jsonObj.getJSONArray("role");
639 for (int i = 0; i < extRole.length(); i++) {
640 if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + ADMIN)
641 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + OWNER)
642 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + ACCOUNT_ADMINISTRATOR)
643 && !(appId == PortalConstants.PORTAL_APP_ID))) {
651 private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(FnApp app, List<FnRole> roleListToBeAddInEcompDB) {
652 FnRole roleToBeAddedInEcompDB;
653 for (FnRole fnRole : roleListToBeAddInEcompDB) {
655 roleToBeAddedInEcompDB = fnRole;
656 if (app.getId() == 1) {
657 roleToBeAddedInEcompDB.setAppRoleId(null);
659 fnRoleService.saveOne(roleToBeAddedInEcompDB);
660 List<FnRole> getRoleCreatedInSync = null;
661 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
662 getRoleCreatedInSync = fnRoleService
663 .retrieveAppRolesByRoleNameAndByAppId(roleToBeAddedInEcompDB.getRoleName(), app.getId());
664 FnRole epUpdateRole = getRoleCreatedInSync.get(0);
665 epUpdateRole.setAppRoleId(epUpdateRole.getId());
666 fnRoleService.saveOne(epUpdateRole);
668 List<FnRole> roleList;
669 final Map<String, String> params = new HashMap<>();
670 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getRoleName());
671 boolean isPortalRole;
672 if (app.getId() == 1) {
674 roleList = fnRoleService
675 .retrieveAppRolesByRoleNameAndWhereAppIdIsNull(roleToBeAddedInEcompDB.getRoleName());
677 isPortalRole = false;
678 roleList = fnRoleService
679 .retrieveAppRolesByRoleNameAndByAppId(roleToBeAddedInEcompDB.getRoleName(), app.getId());
681 FnRole role = roleList.get(0);
682 Role aaFrole = new Role();
683 aaFrole.setId(role.getId());
684 aaFrole.setActive(role.getActiveYn());
685 aaFrole.setPriority(role.getPriority());
686 aaFrole.setName(role.getRoleName());
687 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
688 } catch (Exception e) {
689 logger.error(EELFLoggerDelegate.errorLogger,
690 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
695 private void updateRoleInExternalSystem(Role updateExtRole, FnApp app, boolean isGlobalRole) throws Exception {
696 ObjectMapper mapper = new ObjectMapper();
697 ResponseEntity<String> deleteResponse = null;
698 List<FnRole> epRoleList = null;
699 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
700 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
701 epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
703 epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app.getId());
705 // Assigning functions to global role
706 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
707 List<FnFunction> functions = new ArrayList<>();
708 for (FnRoleFunction roleFunction : convertSetToListOfRoleFunctions(updateExtRole)) {
709 functions.add(roleFunction.getFunctionCd());
712 FnApp portalAppInfo = fnAppService.getById(PortalConstants.PORTAL_APP_ID);
713 addFunctionsTOGlobalRole(epRoleList, updateExtRole, functions, mapper, app, portalAppInfo);
715 String appRole = getSingleAppRole(epRoleList.get(0).getRoleName(), app);
716 List<FnRoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
717 if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
718 JSONObject jsonObj = new JSONObject(appRole);
719 JSONArray extRole = jsonObj.getJSONArray("role");
720 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
721 String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
722 Map<String, String> delRoleKeyMapper = new HashMap<>();
723 delRoleKeyMapper.put(ROLE_NAME, roleName);
724 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
725 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
726 if (deleteResponse.getStatusCode().value() != 200) {
727 throw new ExternalAuthSystemException(deleteResponse.getBody());
729 addRole(updateExtRole, app.getUebKey());
731 String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
732 String name = extRole.getJSONObject(0).getString(ROLE_NAME);
733 List<ExternalAccessPerms> list = new ArrayList<>();
734 if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
735 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
736 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
737 .constructCollectionType(List.class, ExternalAccessPerms.class));
739 // If role name or role functions are updated then delete
740 // record in External System and add new record to avoid
742 boolean isRoleNameChanged = false;
743 if (!desc.equals(updateExtRole.getName())) {
744 isRoleNameChanged = true;
745 deleteRoleInExtSystem(mapper, name);
746 addRole(updateExtRole, app.getUebKey());
747 // add partner functions to the global role in External
749 if (!list.isEmpty() && isGlobalRole) {
750 addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
753 perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace()));
754 // if role name is changes please ignore the previous
755 // functions in External Auth
756 // and update with user requested functions
757 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
759 // Delete role in External System if role is inactive
760 if (!updateExtRole.getActive()) {
761 deleteRoleInExtSystem(mapper, name);
763 if (!isRoleNameChanged) {
764 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
769 // It seems like role exists in local DB but not in External
771 if (updateExtRole.getActive()) {
772 addRole(updateExtRole, app.getUebKey());
773 ExternalAccessRolePerms extAddRolePerms = null;
774 ExternalAccessPerms extAddPerms = null;
775 List<FnRoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
776 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
777 for (FnRoleFunction roleFunc : roleFunctionListAdd) {
778 extAddPerms = new ExternalAccessPerms(
779 app.getAuthNamespace() + "." + roleFunc.getFunctionCd().getType(),
780 roleFunc.getFunctionCd().getCode(), roleFunc.getFunctionCd().getAction());
781 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
782 app.getAuthNamespace() + "." + updateExtRole.getName().replaceAll(
783 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
784 addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
791 private void addRemoveFunctionsToRole(Role updateExtRole, FnApp app, ObjectMapper mapper,
792 List<FnRoleFunction> fnRoleFunctions, String name, List<ExternalAccessPerms> list) throws Exception {
794 List<FnFunction> roleFunctionListNew = new ArrayList<>();
795 for (FnRoleFunction roleFunction : fnRoleFunctions) {
796 roleFunctionListNew.add(roleFunction.getFunctionCd());
798 Map<String, FnFunction> updateRoleFunc = new HashMap<>();
799 for (FnFunction addPerm : roleFunctionListNew) {
800 updateRoleFunc.put(addPerm.getCode(), addPerm);
802 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
803 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
804 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace()));
805 // Update permissions in the ExternalAccess System
806 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
807 if (!list.isEmpty()) {
808 for (ExternalAccessPerms perm : list) {
809 FnFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getAuthNamespace().length() + 1)
810 + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
811 if (roleFunc == null) {
812 FnFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
813 if (roleFuncPipeFilter == null) {
814 removePermForRole(perm, mapper, name, headers);
817 extRolePermMap.put(perm.getInstance(), perm);
818 extRolePermMapPipes.put(perm.getType().substring(app.getAuthNamespace().length() + 1) + FUNCTION_PIPE
819 + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
823 if (!roleFunctionListNew.isEmpty()) {
824 for (FnFunction roleFunc : roleFunctionListNew) {
825 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
826 ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
828 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
832 if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
833 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
841 private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, FnApp app, ObjectMapper mapper,
842 HttpHeaders headers, FnFunction roleFunc) throws JsonProcessingException {
844 ExternalAccessRolePerms extRolePerms;
845 ExternalAccessPerms extPerms;
849 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
850 code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
851 type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
852 action = getFunctionCodeAction(roleFunc.getCode());
854 code = roleFunc.getCode();
855 type = roleFunc.getCode().contains("menu") ? "menu" : "url";
858 extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, code, action);
859 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getAuthNamespace() + "." + updateExtRole.getName()
860 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
861 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
862 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
863 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
864 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
865 ResponseEntity<String> addResponse = template.exchange(
866 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
867 HttpMethod.POST, entity, String.class);
868 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
870 logger.debug(EELFLoggerDelegate.debugLogger,
871 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
872 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
875 logger.debug(EELFLoggerDelegate.debugLogger,
876 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
877 updateRolePerms, addResponse.getStatusCode().value());
882 private void addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
883 HttpHeaders headers) throws JsonProcessingException {
885 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
886 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
887 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
888 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
889 ResponseEntity<String> addResponse = template.exchange(
890 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
891 HttpMethod.POST, entity, String.class);
892 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
894 logger.debug(EELFLoggerDelegate.debugLogger,
895 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
896 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
899 logger.debug(EELFLoggerDelegate.debugLogger,
900 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
901 updateRolePerms, addResponse.getStatusCode().value());
905 private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
906 FnApp app, Role updateExtRole) throws Exception {
907 for (ExternalAccessPerms perm : permslist) {
908 if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace())) {
909 ExternalAccessRolePerms extAddGlobalRolePerms = null;
910 ExternalAccessPerms extAddPerms = null;
911 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
912 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
913 app.getAuthNamespace() + "." + updateExtRole.getName().replaceAll(
914 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
915 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
916 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
917 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
918 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
919 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
921 ResponseEntity<String> addResponse = template
922 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
923 + "role/perm", HttpMethod.POST, entity, String.class);
924 if (addResponse.getStatusCode().value() != 201) {
925 logger.debug(EELFLoggerDelegate.debugLogger,
926 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
927 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
929 logger.debug(EELFLoggerDelegate.debugLogger,
930 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
931 addResponse.getStatusCode().value());
933 } catch (Exception e) {
934 logger.error(EELFLoggerDelegate.errorLogger,
935 "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
941 private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
942 throws JsonProcessingException, Exception, ExternalAuthSystemException {
943 ResponseEntity<String> deleteResponse;
944 Map<String, String> delRoleKeyMapper = new HashMap<>();
945 delRoleKeyMapper.put(ROLE_NAME, name);
946 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
947 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
948 if (deleteResponse.getStatusCode().value() != 200) {
949 logger.error(EELFLoggerDelegate.errorLogger,
950 "updateRoleInExternalSystem: Failed to delete role in external system due to {} ",
951 deleteResponse.getBody());
952 throw new ExternalAuthSystemException(deleteResponse.getBody());
956 public void addRole(Role addRole, String uebkey) throws Exception {
957 boolean response = false;
958 ResponseEntity<String> addResponse = null;
959 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
960 FnApp app = getApp(uebkey).get(0);
961 String newRole = updateExistingRoleInExternalSystem(addRole.getName(), app.getAuthNamespace());
962 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
963 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
964 addResponse = template.exchange(
965 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
966 HttpMethod.POST, entity, String.class);
967 if (addResponse.getStatusCode().value() == 201) {
969 logger.debug(EELFLoggerDelegate.debugLogger,
970 "addRole: Finished adding role in the External Auth system and response code: {} ",
971 addResponse.getStatusCode().value());
973 if (addResponse.getStatusCode().value() == 406) {
974 logger.error(EELFLoggerDelegate.errorLogger,
975 "addRole: Failed to add in the External Auth system due to {} and status code: {}",
976 addResponse.getBody(), addResponse.getStatusCode().value());
980 private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
981 ResponseEntity<String> delResponse = null;
982 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
983 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
984 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
985 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
986 delResponse = template.exchange(
987 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
988 HttpMethod.DELETE, entity, String.class);
989 logger.debug(EELFLoggerDelegate.debugLogger,
990 "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
991 delRole, delResponse.getStatusCode().value());
995 private String getSingleAppRole(String addRole, FnApp app) throws Exception {
996 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
997 HttpEntity<String> entity = new HttpEntity<>(headers);
998 ResponseEntity<String> response = null;
999 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
1000 response = template.exchange(
1001 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
1002 + app.getAuthNamespace() + "." + addRole
1003 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1004 HttpMethod.GET, entity, String.class);
1005 logger.debug(EELFLoggerDelegate.debugLogger,
1006 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
1007 response.getStatusCode().value());
1008 return response.getBody();
1011 private void addFunctionsTOGlobalRole(List<FnRole> epRoleList, Role updateExtRole,
1012 List<FnFunction> roleFunctionListNew, ObjectMapper mapper, FnApp app, FnApp portalAppInfo)
1015 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
1016 // GET Permissions from External Auth System
1017 JSONArray extPerms = getExtAuthPermissions(app.getAuthNamespace());
1018 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1019 final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
1020 final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
1021 final Map<String, FnFunction> userRquestedFunctionsMap = new HashMap<>();
1022 final Map<String, FnFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
1023 for (ExternalAccessPermsDetail permDetail : permsDetailList) {
1024 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
1025 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
1027 // Add If function does not exists for role in External Auth System
1028 for (FnFunction roleFunc : roleFunctionListNew) {
1029 String roleFuncCode = "";
1030 ExternalAccessPermsDetail permsDetail;
1031 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
1032 roleFuncCode = roleFunc.getCode();
1033 permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
1035 roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1036 permsDetail = existingPermsWithRoles.get(roleFuncCode);
1038 if (null == permsDetail.getRoles()
1039 || !permsDetail.getRoles()
1040 .contains(portalAppInfo.getAuthNamespace() + FUNCTION_PIPE
1041 + epRoleList.get(0).getRoleName().replaceAll(
1042 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
1044 addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
1046 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
1047 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
1049 List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = entityManager
1050 .createNamedQuery("getGlobalRoleForRequestedApp")
1051 .setParameter("requestedAppId", app.getId())
1052 .setParameter("roleId", updateExtRole.getId())
1054 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
1055 String globalRoleFuncWithoutPipes = "";
1056 FnFunction roleFunc = null;
1057 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
1058 globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
1059 roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
1061 globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
1062 roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
1064 if (roleFunc == null) {
1065 ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
1066 ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
1067 : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
1068 ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
1069 EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
1070 permDetailFromMap.getAction());
1071 String roleName = portalAppInfo.getAuthNamespace() + "." + globalRoleFunc.getRoleName()
1072 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
1073 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1074 removePermForRole(perm, mapper, roleName, headers);
1077 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
1078 } catch (Exception e) {
1079 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
1084 private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
1085 throws ExternalAuthSystemException, JsonProcessingException {
1086 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
1087 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
1089 HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
1090 logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
1091 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
1092 ResponseEntity<String> deletePermResponse = template
1093 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1094 + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
1095 if (deletePermResponse.getStatusCode().value() != 200) {
1096 throw new ExternalAuthSystemException(deletePermResponse.getBody());
1098 logger.debug(EELFLoggerDelegate.debugLogger,
1099 "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
1100 permDetails, deletePermResponse.getStatusCode().value());
1101 } catch (Exception e) {
1102 if (e.getMessage().contains("404")) {
1103 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
1104 permDetails, e.getMessage());
1111 private void addRoleFunctionsToGlobalRoleInExternalSystem(FnFunction addFunction, Role globalRole,
1112 ObjectMapper mapper, FnApp app, FnApp portalAppInfo) throws Exception {
1114 logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
1115 ExternalAccessRolePerms extAddRolePerms = null;
1116 ExternalAccessPerms extAddPerms = null;
1117 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1121 if (addFunction.getFunctionCd().contains(FUNCTION_PIPE)) {
1122 code = EcompPortalUtils.getFunctionCode(addFunction.getFunctionCd());
1123 type = getFunctionCodeType(addFunction.getFunctionCd());
1124 action = getFunctionCodeAction(addFunction.getFunctionCd());
1126 code = addFunction.getFunctionCd();
1127 type = addFunction.getFunctionCd().contains("menu") ? "menu" : "url";
1130 extAddPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, code, action);
1131 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
1132 portalAppInfo.getAuthNamespace() + "." + globalRole
1133 .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1134 String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
1135 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1136 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
1137 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1138 ResponseEntity<String> addResponse = template.exchange(
1139 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1140 HttpMethod.POST, entity, String.class);
1141 if (addResponse.getStatusCode().value() != 201) {
1142 logger.debug(EELFLoggerDelegate.debugLogger,
1143 "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}",
1144 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
1146 logger.debug(EELFLoggerDelegate.debugLogger,
1147 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
1148 addResponse.getStatusCode().value());
1150 logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
1151 } catch (Exception e) {
1152 logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
1157 private List<FnRoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
1158 Set<FnRoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
1159 List<FnRoleFunction> roleFunctionList = new ArrayList<>();
1160 ObjectMapper roleFuncMapper = new ObjectMapper();
1161 for (Object nextValue : roleFunctionSetList) {
1162 FnRoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, FnRoleFunction.class);
1163 roleFunctionList.add(roleFunction);
1165 return roleFunctionList.stream().distinct().collect(Collectors.toList());
1168 private List<FnRole> getPartnerAppRoleInfo(Long roleId, Long appId) {
1169 List<FnRole> roleInfo = fnRoleService.retrieveAppRoleByAppRoleIdAndByAppId(roleId, appId);
1170 if (roleInfo.isEmpty()) {
1171 roleInfo = fnRoleService.retrieveAppRoleByAppRoleIdAndByAppId(appId, roleId);
1176 private void inactiveRolesNotInExternalAuthSystem(final Long appId, List<FnRole> finalRoleList,
1177 List<FnRole> applicationRolesList) {
1178 final Map<String, FnRole> checkRolesInactive = new HashMap<>();
1179 for (FnRole extrole : finalRoleList) {
1180 checkRolesInactive.put(extrole.getRoleName(), extrole);
1182 for (FnRole role : applicationRolesList) {
1184 List<FnRole> roleList;
1185 if (!checkRolesInactive.containsKey(role.getRoleName())) {
1187 roleList = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role.getRoleName());
1189 roleList = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role.getRoleName(), appId);
1191 if (!roleList.isEmpty()) {
1192 FnRole updateRoleInactive = roleList.get(0);
1193 updateRoleInactive.setActiveYn(false);
1194 fnRoleService.saveOne(updateRoleInactive);
1197 } catch (Exception e) {
1198 logger.error(EELFLoggerDelegate.errorLogger,
1199 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
1204 private JSONArray getExtAuthPermissions(String authNamespace) throws Exception {
1205 ResponseEntity<String> response = null;
1206 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1207 HttpEntity<String> entity = new HttpEntity<>(headers);
1208 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
1209 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1210 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1211 + "perms/ns/" + authNamespace, HttpMethod.GET, entity, String.class);
1212 String res = response.getBody();
1213 logger.debug(EELFLoggerDelegate.debugLogger,
1214 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
1215 response.getBody());
1216 JSONObject jsonObj = new JSONObject(res);
1217 JSONArray extPerms = jsonObj.getJSONArray("perm");
1218 for (int i = 0; i < extPerms.length(); i++) {
1219 if (extPerms.getJSONObject(i).getString("type").equals(authNamespace + ".access")) {
1227 public void syncRoleFunctionFromExternalAccessSystem(FnApp app) {
1229 // get Permissions from External Auth System
1230 JSONArray extPerms = getExtAuthPermissions(app.getAuthNamespace());
1231 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1232 final Map<String, EpAppFunction> roleFuncMap = new HashMap<>();
1233 List<EpAppFunction> appFunctions = epAppFunctionService.getAllRoleFunctions(app.getId());
1234 if (!appFunctions.isEmpty()) {
1235 for (EpAppFunction roleFunc : appFunctions) {
1236 roleFuncMap.put(roleFunc.getFunctionCd(), roleFunc);
1239 // get Roles for portal in DB
1240 List<FnRole> portalRoleList = getGlobalRolesOfPortal();
1241 final Map<String, FnRole> existingPortalRolesMap = new HashMap<>();
1242 for (FnRole epRole : portalRoleList) {
1243 existingPortalRolesMap.put(epRole.getRoleName().replaceAll(
1244 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1247 final Map<String, FnRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
1248 // store External Permissions with Pipe and without Pipe (just
1250 final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1251 final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1252 for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1253 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1254 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1255 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1257 // Add if new functions and app role functions were added in
1258 // external auth system
1259 for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1260 String code = permsDetail.getInstance();
1261 EpAppFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1262 List<EpAppFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1263 getFunctionCodeKey);
1264 List<String> roles = permsDetail.getRoles();
1265 if (roles != null) {
1266 addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
1267 existingPortalRolesMap);
1270 // Check if function does exits in External Auth System but exits in
1271 // local then delete function and its dependencies
1272 for (EpAppFunction roleFunc : appFunctions) {
1274 ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1275 .get(roleFunc.getFunctionCd());
1276 if (null == getFunctionCodeContainsPipeKey) {
1277 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getFunctionCd());
1278 if (null == getFunctionCodeKey) {
1279 deleteAppRoleFuncDoesNotExitsInExtSystem(app.getId(), roleFunc.getFunctionCd());
1282 } catch (Exception e) {
1283 logger.error(EELFLoggerDelegate.errorLogger,
1284 "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1287 logger.debug(EELFLoggerDelegate.debugLogger,
1288 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1289 } catch (Exception e) {
1290 logger.error(EELFLoggerDelegate.errorLogger,
1291 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1295 private List<EpAppFunction> addGetLocalFunction(FnApp app,
1296 final Map<String, EpAppFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
1297 EpAppFunction getFunctionCodeKey) {
1298 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
1299 getFunctionCodeKey);
1300 List<EpAppFunction> roleFunctionList = epAppFunctionService
1301 .getAppFunctionOnCodeAndAppId(app.getId(), finalFunctionCodeVal);
1302 if (roleFunctionList.isEmpty()) {
1303 roleFunctionList = epAppFunctionService.getAppFunctionOnCodeAndAppId(app.getId(), code);
1305 return roleFunctionList;
1308 private String addToLocalIfFunctionNotExists(FnApp app, final Map<String, EpAppFunction> roleFuncMap,
1309 ExternalAccessPermsDetail permsDetail, String code, EpAppFunction getFunctionCodeKey) {
1310 String finalFunctionCodeVal = "";
1311 if (null == getFunctionCodeKey) {
1312 finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
1313 EpAppFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
1314 // If function does not exist in local then add!
1315 if (null == checkIfCodeStillExits) {
1316 logger.debug(EELFLoggerDelegate.debugLogger,
1317 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
1318 addFunctionInEcompDB(app, permsDetail, code);
1319 logger.debug(EELFLoggerDelegate.debugLogger,
1320 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
1323 return finalFunctionCodeVal;
1326 private void addFunctionInEcompDB(FnApp app, ExternalAccessPermsDetail permsDetail, String code) {
1328 EpAppFunction addFunction = new EpAppFunction();
1329 addFunction.setAppId(app);
1330 addFunction.setFunctionCd(code);
1331 addFunction.setFunctionName(permsDetail.getDescription());
1332 epAppFunctionService.save(addFunction);
1333 } catch (Exception e) {
1334 logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
1338 private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(FnApp app, JSONArray extPerms) throws IOException {
1339 ExternalAccessPermsDetail permDetails = null;
1340 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1341 for (int i = 0; i < extPerms.length(); i++) {
1342 String description = null;
1343 if (extPerms.getJSONObject(i).has("description")) {
1344 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1347 extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1) + "|"
1348 + extPerms.getJSONObject(i).getString("instance") + "|"
1349 + extPerms.getJSONObject(i).getString("action");
1351 if (extPerms.getJSONObject(i).has("roles")) {
1352 ObjectMapper rolesListMapper = new ObjectMapper();
1353 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1354 List<String> list = rolesListMapper.readValue(resRoles.toString(),
1355 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1356 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1357 extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1)
1358 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1359 + extPerms.getJSONObject(i).getString("action"),
1360 extPerms.getJSONObject(i).getString("action"), list, description);
1361 permsDetailList.add(permDetails);
1363 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1364 extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1)
1365 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1366 + extPerms.getJSONObject(i).getString("action"),
1367 extPerms.getJSONObject(i).getString("action"), description);
1368 permsDetailList.add(permDetails);
1371 return permsDetailList;
1374 public List<FnRole> getGlobalRolesOfPortal() {
1375 List<FnRole> globalRoles = new ArrayList<>();
1377 globalRoles = fnRoleService.getGlobalRolesOfPortal();
1378 } catch (Exception e) {
1379 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
1384 private void deleteAppRoleFuncDoesNotExitsInExtSystem(final Long appId, final String roleFunc) {
1385 logger.debug(EELFLoggerDelegate.debugLogger,
1386 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc);
1387 epAppRoleFunctionService.deleteByAppIdAndFunctionCd(appId, roleFunc);
1388 logger.debug(EELFLoggerDelegate.debugLogger,
1389 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc);
1390 logger.debug(EELFLoggerDelegate.debugLogger,
1391 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc);
1392 epAppFunctionService.deleteByAppIdAndFunctionCd(appId, roleFunc);
1393 logger.debug(EELFLoggerDelegate.debugLogger,
1394 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc);
1397 private CentralV2Role convertRoleToCentralV2Role(FnRole role) {
1398 return CentralV2Role.builder().id(role.getId()).created(role.getCreated())
1399 .modified(role.getModified()).createdId(role.getCreatedId().getId())
1400 .modifiedId(role.getModifiedId().getId())
1401 .rowNum(role.getRowNum()).name(role.getRoleName()).active(role.getActiveYn())
1402 .priority(role.getPriority()).roleFunctions(new TreeSet<>()).childRoles(new TreeSet<>())
1403 .parentRoles(new TreeSet<>()).build();
1406 private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(FnApp app, final Map<String, FnRole> currentRolesInDB,
1407 List<EpAppFunction> roleFunctionList, List<String> roles,
1408 Map<String, FnRole> existingPortalRolesMap) throws Exception {
1409 if (!roleFunctionList.isEmpty()) {
1410 final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1411 final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1412 List<LocalRole> localRoleList = localRoleService
1413 .getCurrentAppRoleFunctions(app.getId(), roleFunctionList.get(0).getFunctionCd());
1414 for (LocalRole localRole : localRoleList) {
1415 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1416 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1418 for (String addRole : roles) {
1419 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
1421 for (String extAuthrole : roles) {
1422 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1423 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
1424 app.getAuthNamespace());
1425 if (isNameSpaceMatching) {
1426 if (!currentAppRoleFunctionsMap
1427 .containsKey(extAuthrole.substring(app.getAuthNamespace().length() + 1))) {
1428 FnRole localAddFuntionRole = currentRolesInDB
1429 .get(extAuthrole.substring(app.getAuthNamespace().length() + 1));
1430 if (localAddFuntionRole == null) {
1431 checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1433 EpAppRoleFunction addAppRoleFunc = new EpAppRoleFunction();
1434 addAppRoleFunc.setAppId(app);
1435 addAppRoleFunc.setEpAppFunction(roleFunctionList.get(0));
1436 addAppRoleFunc.setFnRole(localAddFuntionRole);
1437 epAppRoleFunctionService.save(addAppRoleFunc);
1440 // This block is to save global role function if exists
1442 String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1443 boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1444 if (checkIfGlobalRoleExists) {
1445 FnRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1446 EpAppRoleFunction addGlobalRoleFunctions = new EpAppRoleFunction();
1447 List<EpAppRoleFunction> currentGlobalRoleFunctionsList = epAppRoleFunctionService
1448 .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), role.getId());
1449 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
1450 .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getEpAppFunction()
1452 .equals(roleFunctionList.get(0).getFunctionCd()));
1453 if (!checkIfRoleFunctionExists) {
1454 addGlobalRoleFunctions.setAppId(app);
1455 addGlobalRoleFunctions.setFnRole(role);
1456 if (!app.getId().equals(role.getAppRoleId())) {
1457 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1459 addGlobalRoleFunctions.setRoleAppId(null);
1461 addGlobalRoleFunctions.setEpAppFunction(roleFunctionList.get(0));
1462 epAppRoleFunctionService.save(addGlobalRoleFunctions);
1467 for (LocalRole localRoleDelete : localRoleList) {
1468 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
1469 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
1470 epAppRoleFunctionService
1471 .deleteByAppIdAndFunctionCdAndRoleId(app.getId(), roleFunctionList.get(0).getFunctionCd(),
1472 localRoleDelete.getRoleId());
1478 private void checkAndAddRoleInDB(FnApp app, final Map<String, FnRole> currentRolesInDB,
1479 List<EpAppFunction> roleFunctionList, String roleList) throws Exception {
1480 if (!currentRolesInDB.containsKey(roleList.substring(app.getAuthNamespace().length() + 1))) {
1481 FnRole role = addRoleInDBIfDoesNotExists(app.getId(),
1482 roleList.substring(app.getAuthNamespace().length() + 1));
1483 addRoleDescriptionInExtSystem(role.getRoleName(), app.getAuthNamespace());
1484 if (!roleFunctionList.isEmpty()) {
1486 EpAppRoleFunction addAppRoleFunc = new EpAppRoleFunction();
1487 addAppRoleFunc.setAppId(app);
1488 addAppRoleFunc.setEpAppFunction(roleFunctionList.get(0));
1489 addAppRoleFunc.setFnRole(role);
1490 epAppRoleFunctionService.save(addAppRoleFunc);
1491 } catch (Exception e) {
1492 logger.error(EELFLoggerDelegate.errorLogger,
1493 "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
1499 private FnRole addRoleInDBIfDoesNotExists(final Long appId, final String role) {
1500 FnRole setNewRole = new FnRole();
1502 boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, appId);
1503 List<FnRole> getRoleCreated = null;
1504 if (!appId.equals(PortalConstants.PORTAL_APP_ID)) {
1505 List<FnRole> roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
1507 FnRole epUpdateRole = roleCreated.get(0);
1508 epUpdateRole.setAppRoleId(epUpdateRole.getId());
1509 fnRoleService.saveOne(epUpdateRole);
1510 getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
1512 getRoleCreated = roleCreated;
1515 getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role);
1517 if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
1518 FnRole roleObject = getRoleCreated.get(0);
1519 setNewRole.setId(roleObject.getId());
1520 setNewRole.setRoleName(roleObject.getRoleName());
1521 setNewRole.setActiveYn(roleObject.getActiveYn());
1522 setNewRole.setPriority(roleObject.getPriority());
1524 } catch (Exception e) {
1525 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
1530 private boolean checkIfRoleExitsElseCreateInSyncFunctions(final String role, final long appId) {
1532 List<FnRole> roleCreated = null;
1533 if (appId == PortalConstants.PORTAL_APP_ID) {
1534 roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role);
1536 roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
1538 if (roleCreated == null || roleCreated.isEmpty()) {
1539 FnRole epRoleNew = new FnRole();
1540 epRoleNew.setActiveYn(true);
1541 epRoleNew.setRoleName(role);
1542 if (appId == PortalConstants.PORTAL_APP_ID) {
1543 epRoleNew.setAppId(null);
1545 epRoleNew.setAppId(appId);
1547 fnRoleService.saveOne(epRoleNew);
1555 private String updateExistingRoleInExternalSystem(final String roleName, final String authNamespace)
1556 throws JsonProcessingException {
1557 ObjectMapper mapper = new ObjectMapper();
1558 String addNewRole = "";
1559 ExternalAccessRole extRole = new ExternalAccessRole();
1560 extRole.setName(authNamespace + "." + roleName
1561 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1562 extRole.setDescription(String.valueOf(roleName));
1563 addNewRole = mapper.writeValueAsString(extRole);
1567 private boolean addRoleDescriptionInExtSystem(final String roleName, final String authNamespace) throws Exception {
1568 boolean status = false;
1570 String addRoleNew = updateExistingRoleInExternalSystem(roleName, authNamespace);
1571 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1572 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1574 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1575 HttpMethod.PUT, entity, String.class);
1577 } catch (HttpClientErrorException e) {
1578 logger.error(EELFLoggerDelegate.errorLogger,
1579 "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
1580 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1581 } catch (Exception e) {
1582 logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
1587 public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
1588 List<CentralRole> cenRoleList = new ArrayList<>();
1589 for (CentralV2Role v2CenRole : v2CenRoleList) {
1590 SortedSet<EpAppFunction> cenRoleFuncList = new TreeSet<>();
1591 for (DomainVo vo : v2CenRole.getRoleFunctions()) {
1592 Optional<FnRoleFunction> v2CenRoleFunc = fnRoleFunctionService.findById(vo.getId());
1593 if (v2CenRoleFunc.isPresent()) {
1594 EpAppFunction roleFunc = EpAppFunction.builder()
1595 .functionCd(v2CenRoleFunc.get().getFunctionCd().getCode())
1596 .functionName(v2CenRoleFunc.get().getRole().getRoleName())
1598 cenRoleFuncList.add(roleFunc);
1601 CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(),
1602 v2CenRole.getPriority(), cenRoleFuncList);
1603 cenRoleList.add(role);
1608 public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1609 boolean response = false;
1610 String message = "";
1612 FnApp app = getApp(uebkey).get(0);
1613 addRoleInEcompDB(saveRole, app);
1615 } catch (Exception e) {
1616 message = e.getMessage();
1617 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1619 return new ExternalRequestFieldsValidator(response, message);
1622 @Transactional(rollbackFor = Exception.class)
1623 public void addRoleInEcompDB(Role addRoleInDB, FnApp app) throws Exception {
1626 Set<FnFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
1627 List<FnFunction> roleFunctionListNew = new ArrayList<>();
1628 ObjectMapper mapper = new ObjectMapper();
1629 for (Object nextValue : roleFunctionList) {
1630 FnFunction roleFunction = mapper.convertValue(nextValue, FnFunction.class);
1631 roleFunctionListNew.add(roleFunction);
1633 List<FnFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
1635 if (addRoleInDB.getId() == null) { // check if it is new role
1636 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1637 checkIfRoleExitsInExternalSystem(addRoleInDB, app);
1639 FnRole epRoleNew = new FnRole();
1640 epRoleNew.setActiveYn(addRoleInDB.getActive());
1641 epRoleNew.setRoleName(addRoleInDB.getName());
1642 epRoleNew.setPriority(addRoleInDB.getPriority());
1643 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1644 epRoleNew.setAppId(null);
1646 epRoleNew.setAppId(app.getId());
1648 fnRoleService.saveOne(epRoleNew);
1649 List<FnRole> getRoleCreated = null;
1650 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1651 List<FnRole> roleCreated = fnRoleService
1652 .retrieveAppRolesByRoleNameAndByAppId(addRoleInDB.getName(), app.getId());
1653 FnRole epUpdateRole = roleCreated.get(0);
1654 epUpdateRole.setAppRoleId(epUpdateRole.getId());
1655 fnRoleService.saveOne(epUpdateRole);
1656 getRoleCreated = fnRoleService
1657 .retrieveAppRolesByRoleNameAndByAppId(addRoleInDB.getName(), app.getId());
1659 getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(addRoleInDB.getName());
1661 // Add role in External Auth system
1662 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1663 addNewRoleInExternalSystem(getRoleCreated, app);
1666 } else { // if role already exists then update it
1667 FnRole globalRole = null;
1668 List<FnRole> applicationRoles;
1669 List<FnRole> globalRoleList = getGlobalRolesOfPortal();
1670 boolean isGlobalRole = false;
1671 if (!globalRoleList.isEmpty()) {
1672 FnRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
1676 isGlobalRole = true;
1679 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
1680 || (globalRole != null && app.getId() != globalRole.getAppId())) {
1681 applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
1683 applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app.getId());
1685 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1686 updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
1687 // Add all user to the re-named role in external auth system
1688 if (!applicationRoles.isEmpty()
1689 && !addRoleInDB.getName().equals(applicationRoles.get(0).getRoleName())) {
1690 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
1691 addRoleInDB.getName());
1694 deleteRoleFunction(app, applicationRoles);
1695 if (!applicationRoles.isEmpty()) {
1696 epRole = applicationRoles.get(0);
1697 epRole.setRoleName(addRoleInDB.getName());
1698 epRole.setPriority(addRoleInDB.getPriority());
1699 epRole.setActiveYn(addRoleInDB.getActive());
1700 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1701 epRole.setAppId(null);
1702 epRole.setAppRoleId(null);
1703 } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
1704 && applicationRoles.get(0).getAppRoleId() == null) {
1705 epRole.setAppRoleId(epRole.getId());
1707 fnRoleService.saveOne(epRole);
1709 Long roleAppId = null;
1710 if (globalRole != null && !app.getId().equals(globalRole.getAppId())) {
1711 roleAppId = PortalConstants.PORTAL_APP_ID;
1713 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
1716 } catch (Exception e) {
1717 logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
1722 private void saveRoleFunction(List<FnFunction> roleFunctionListNew, FnApp app, List<FnRole> applicationRoles,
1724 for (FnFunction roleFunc : roleFunctionListNew) {
1725 String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1726 EpAppRoleFunction appRoleFunc = new EpAppRoleFunction();
1727 appRoleFunc.setAppId(app);
1728 appRoleFunc.setFnRole(applicationRoles.get(0));
1729 appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
1730 List<EpAppFunction> roleFunction = epAppFunctionService.getRoleFunction(roleFunc.getCode(), app.getId());
1731 if (roleFunction.isEmpty()) {
1732 roleFunction = epAppFunctionService.getRoleFunction(code, app.getId());
1734 if (roleFunction.size() > 1) {
1735 EpAppFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
1736 appRoleFunc.setEpAppFunction(getExactFunctionCode);
1738 appRoleFunc.setEpAppFunction(roleFunction.get(0));
1740 epAppRoleFunctionService.save(appRoleFunc);
1744 @Transactional(propagation = Propagation.REQUIRED)
1745 public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1748 List<FnRole> epRoleList;
1749 FnApp app = getApp(uebkey).get(0);
1750 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1751 epRoleList = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(deleteRole);
1753 epRoleList = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(deleteRole, app.getId());
1755 if (!epRoleList.isEmpty()) {
1756 // Delete app role functions before deleting role
1757 deleteRoleFunction(app, epRoleList);
1758 if (app.getId() == 1) {
1759 // Delete fn_user_ role
1761 "DELETE FROM FN_USER_ROLE WHERE " + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList
1763 entityManager.createQuery(query).executeUpdate();
1764 boolean isPortalRequest = false;
1765 deleteRoleDependencyRecords(epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1767 deleteRoleInExternalAuthSystem(epRoleList, app);
1768 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1769 fnRoleService.delete(epRoleList.get(0));
1772 } catch (Exception e) {
1773 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1779 private void deleteRoleInExternalAuthSystem(List<FnRole> epRoleList, FnApp app) throws Exception {
1780 ResponseEntity<String> deleteResponse;
1781 ResponseEntity<String> res = getNameSpaceIfExists(app);
1782 if (res.getStatusCode() == HttpStatus.OK) {
1783 // Delete Role in External System
1784 String deleteRoleKey = "{\"name\":\"" + app.getAuthNamespace() + "." + epRoleList.get(0).getRoleName()
1785 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1786 deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1787 if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1788 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1789 logger.error(EELFLoggerDelegate.errorLogger,
1790 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1791 deleteResponse.getBody());
1793 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1797 private void deleteRoleFunction(FnApp app, List<FnRole> role) {
1798 List<EpAppRoleFunction> appRoleFunctionList = epAppRoleFunctionService
1799 .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), role.get(0).getId());
1800 epAppRoleFunctionService.deleteInBatch(appRoleFunctionList);
1803 public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1804 List<CentralV2Role> roleList = new ArrayList<>();
1806 List<FnApp> app = getApp(uebkey);
1808 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1809 appId = app.get(0).getId();
1811 List<FnRole> epRole;
1812 if (appId == null) {
1813 epRole = fnRoleService.retrieveActiveRolesWhereAppIdIsNull();
1815 epRole = fnRoleService.retrieveActiveRolesOfApplication(appId);
1817 roleList = createCentralRoleObject(app, epRole, roleList);
1818 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1819 if (globalRoleList.size() > 0) {
1820 roleList.addAll(globalRoleList);
1822 } catch (Exception e) {
1823 logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1829 public Integer bulkUploadRoles(String uebkey) throws Exception {
1830 List<FnApp> app = getApp(uebkey);
1831 List<FnRole> roles = getAppRoles(app.get(0).getId());
1832 List<CentralV2Role> cenRoleList = new ArrayList<>();
1833 final Map<String, Long> params = new HashMap<>();
1834 Integer rolesListAdded = 0;
1836 cenRoleList = createCentralRoleObject(app, roles, cenRoleList);
1837 ObjectMapper mapper = new ObjectMapper();
1838 mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1839 String roleList = mapper.writeValueAsString(cenRoleList);
1840 List<Role> roleObjectList = mapper.readValue(roleList,
1841 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1842 for (Role role : roleObjectList) {
1843 addRoleInExternalSystem(role, app.get(0));
1846 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1847 // Add Account Admin role in External AUTH System
1849 String addAccountAdminRole = "";
1850 ExternalAccessRole extRole = new ExternalAccessRole();
1851 extRole.setName(app.get(0).getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE
1852 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1853 addAccountAdminRole = mapper.writeValueAsString(extRole);
1854 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1855 HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
1857 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1858 HttpMethod.POST, entity, String.class);
1860 } catch (HttpClientErrorException e) {
1861 logger.error(EELFLoggerDelegate.errorLogger,
1862 "HttpClientErrorException - Failed to create Account Admin role", e);
1863 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1864 } catch (Exception e) {
1865 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1866 logger.error(EELFLoggerDelegate.errorLogger,
1867 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
1870 logger.error(EELFLoggerDelegate.errorLogger,
1871 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
1875 } catch (Exception e) {
1876 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
1879 return rolesListAdded;
1882 private void addRoleInExternalSystem(Role role, FnApp app) throws Exception {
1883 String addRoleNew = updateExistingRoleInExternalSystem(role.getName(), app.getAuthNamespace());
1884 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1886 HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1888 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1889 HttpMethod.POST, entity, String.class);
1890 } catch (HttpClientErrorException e) {
1891 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
1893 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1894 } catch (Exception e) {
1895 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1896 logger.error(EELFLoggerDelegate.errorLogger,
1897 "addRoleInExternalSystem: Role already exits but does not break functionality", e);
1899 logger.error(EELFLoggerDelegate.errorLogger,
1900 "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
1905 public Integer bulkUploadFunctions(String uebkey) throws Exception {
1906 FnApp app = getApp(uebkey).get(0);
1907 List<FnRoleFunction> roleFuncList = fnRoleFunctionService.findAll();
1908 EpAppFunction cenRoleFunc;
1909 Integer functionsAdded = 0;
1911 for (FnRoleFunction roleFunc : roleFuncList) {
1912 cenRoleFunc = EpAppFunction.builder()
1913 .functionCd(roleFunc.getFunctionCd().getName())
1914 .roleId(roleFunc.getRole().getId())
1916 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1919 } catch (HttpClientErrorException e) {
1920 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
1921 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1922 } catch (Exception e) {
1923 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
1925 return functionsAdded;
1928 public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1929 FnApp app = getApp(uebkey).get(0);
1930 List<FnRole> roles = getAppRoles(app.getId());
1931 Integer roleFunctions = 0;
1933 for (FnRole role : roles) {
1934 List<BulkUploadRoleFunction> appRoleFunc = bulkUploadUserRolesService
1935 .uploadAllRoleFunctions(role.getId());
1936 if (!appRoleFunc.isEmpty()) {
1937 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
1938 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1943 } catch (HttpClientErrorException e) {
1944 logger.error(EELFLoggerDelegate.errorLogger,
1945 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
1946 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1947 } catch (Exception e) {
1948 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
1950 return roleFunctions;
1953 private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, FnRole role, FnApp app) {
1955 String instance = "";
1957 if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
1958 type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
1959 instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
1960 action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
1962 type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1963 instance = addRoleFunc.getFunctionCd();
1966 ExternalAccessRolePerms extRolePerms = null;
1967 ExternalAccessPerms extPerms = null;
1968 ObjectMapper mapper = new ObjectMapper();
1970 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1971 extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, instance, action,
1972 addRoleFunc.getFunctionName());
1973 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getAuthNamespace() + "." + role.getRoleName()
1974 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1975 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1976 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1978 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1979 HttpMethod.POST, entity, String.class);
1980 } catch (Exception e) {
1981 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1982 logger.error(EELFLoggerDelegate.errorLogger,
1983 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
1986 logger.error(EELFLoggerDelegate.errorLogger,
1987 "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
1993 public Integer bulkUploadUserRoles(String uebkey) throws Exception {
1994 FnApp app = getApp(uebkey).get(0);
1995 List<BulkUploadUserRoles> userRolesList;
1996 Integer userRolesAdded = 0;
1997 if (app.getAuthCentral()) {
1998 userRolesList = bulkUploadUserRolesService.getBulkUserRoles(app.getUebKey());
1999 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2000 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
2001 addUserRoleInExternalSystem(userRolesUpload);
2006 return userRolesAdded;
2009 public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2010 FnApp app = getApp(uebkey).get(0);
2011 List<EpAppFunction> roleFuncList = epAppFunctionService.getAllRoleFunctions(app.getId());
2012 Integer functionsAdded = 0;
2014 for (EpAppFunction roleFunc : roleFuncList) {
2015 addFunctionInExternalSystem(roleFunc, app);
2018 } catch (HttpClientErrorException e) {
2019 logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
2021 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2022 } catch (Exception e) {
2023 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2025 return functionsAdded;
2028 public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2029 FnApp app = getApp(uebkey).get(0);
2030 for (Role role : roleList) {
2031 addRoleInExternalSystem(role, app);
2035 private void addFunctionInExternalSystem(EpAppFunction roleFunc, FnApp app) throws Exception {
2036 ObjectMapper mapper = new ObjectMapper();
2037 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2038 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2040 String instance = "";
2042 if ((roleFunc.getFunctionCd().contains(FUNCTION_PIPE))
2043 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2044 type = EcompPortalUtils.getFunctionType(roleFunc.getFunctionCd());
2045 instance = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
2046 action = EcompPortalUtils.getFunctionAction(roleFunc.getFunctionCd());
2048 type = roleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2049 instance = roleFunc.getFunctionCd();
2053 extPerms.setAction(action);
2054 extPerms.setInstance(instance);
2055 extPerms.setType(app.getAuthNamespace() + "." + type);
2056 extPerms.setDescription(roleFunc.getFunctionName());
2057 String addFunction = mapper.writeValueAsString(extPerms);
2058 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2059 logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2060 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2061 ResponseEntity<String> addPermResponse = template.exchange(
2062 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2063 HttpMethod.POST, entity, String.class);
2064 logger.debug(EELFLoggerDelegate.debugLogger,
2065 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2066 addPermResponse.getStatusCode().value(), addFunction);
2067 } catch (HttpClientErrorException e) {
2068 logger.error(EELFLoggerDelegate.errorLogger,
2069 "HttpClientErrorException - Failed to add function in external central auth system", e);
2070 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2072 } catch (Exception e) {
2073 logger.error(EELFLoggerDelegate.errorLogger,
2074 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2079 public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2080 FnApp app = getApp(uebkey).get(0);
2081 List<FnRole> roles = getAppRoles(app.getId());
2082 Integer roleFunctions = 0;
2084 for (FnRole role : roles) {
2085 List<BulkUploadRoleFunction> appRoleFunc = bulkUploadUserRolesService
2086 .uploadPartnerRoleFunctions(role.getId());
2087 if (!appRoleFunc.isEmpty()) {
2088 for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2089 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2094 // upload global role functions to ext auth system
2095 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2096 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2098 } catch (HttpClientErrorException e) {
2099 logger.error(EELFLoggerDelegate.errorLogger,
2100 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2101 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2102 } catch (Exception e) {
2103 logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2105 return roleFunctions;
2108 private Integer bulkUploadGlobalRoleFunctions(FnApp app, Integer roleFunctions) throws Exception {
2110 //TODO HARDCODED ID!!!!!
2111 FnApp portalApp = fnAppService.getById(1L);
2112 String getBulkUploadPartnerGlobalRoleFunctions =
2113 "select distinct fr.role_id, fr.role_name, fr.active_yn, fr.priority, epr.function_cd, ep.function_name, ep.app_id, epr.role_app_id"
2114 + " from fn_role fr, ep_app_function ep, ep_app_role_function epr"
2115 + " where fr.role_id = epr.role_id and ep.function_cd = epr.function_cd and ep.app_id = epr.app_id and epr.app_id = :appId and epr.role_app_id = 1";
2116 List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = entityManager
2117 .createQuery(getBulkUploadPartnerGlobalRoleFunctions)
2118 .setParameter("appId", app.getId())
2120 ObjectMapper mapper = new ObjectMapper();
2121 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2122 for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2123 ExternalAccessRolePerms extRolePerms;
2124 ExternalAccessPerms extPerms;
2126 String instance = "";
2128 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2129 type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2130 instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2131 action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2133 type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2134 instance = globalRoleFunc.getFunctionCd();
2137 extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, instance, action);
2138 extRolePerms = new ExternalAccessRolePerms(extPerms,
2139 portalApp.getAuthNamespace() + "." + globalRoleFunc.getRoleName().replaceAll(
2140 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2141 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2142 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2143 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2146 } catch (HttpClientErrorException e) {
2147 logger.error(EELFLoggerDelegate.errorLogger,
2148 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2149 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2151 } catch (Exception e) {
2152 logger.error(EELFLoggerDelegate.errorLogger,
2153 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2156 return roleFunctions;
2159 private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
2160 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
2161 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
2162 ResponseEntity<String> addPermResponse = template.exchange(
2163 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2164 HttpMethod.POST, entity, String.class);
2165 logger.debug(EELFLoggerDelegate.debugLogger,
2166 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
2167 addPermResponse.getStatusCode().value(), updateRolePerms);
2170 public List<String> getMenuFunctionsList(String uebkey) throws Exception {
2171 List<String> appMenuFunctionsList = null;
2172 List<String> appMenuFunctionsFinalList = new ArrayList<>();
2174 FnApp app = getApp(uebkey).get(0);
2175 String getMenuFunctions = "select f.function_cd from ep_app_function f"
2176 + " where f.app_id =:appId"
2178 + " select epa.function_cd from fn_role fnr, ep_app_role_function epr, ep_app_function epa where epr.role_id = fnr.role_id"
2179 + " and epa.function_cd = epr.function_cd and fnr.role_name like 'global%' and fnr.app_id is null and epr.app_id = 1";
2180 appMenuFunctionsList = entityManager.createQuery(getMenuFunctions).setParameter(APP_ID, app.getId())
2182 for (String appMenuFunction : appMenuFunctionsList) {
2183 if (appMenuFunction.contains(FUNCTION_PIPE)) {
2184 appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
2186 appMenuFunctionsFinalList.add(appMenuFunction);
2189 } catch (Exception e) {
2190 logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
2191 return appMenuFunctionsFinalList;
2193 return appMenuFunctionsFinalList;
2196 public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
2197 List<String> usersList = new ArrayList<>();
2198 List<EcompUser> usersfinalList = new ArrayList<>();
2200 FnApp app = getApp(uebkey).get(0);
2201 String ApplicationUserRoles =
2202 "select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, fu.login_id, \n"
2203 + " fu.active_yn , fr.app_role_id, fr.role_name, epr.function_cd , epf.function_name\n"
2204 + " from fn_user fu, fn_role fr, fn_user_role fur, ep_app_role_function epr , ep_app_function epf\n"
2205 + " where fu.user_id = fur.user_id and fu.active_yn='Y' and fur.role_id = fr.role_id and fr.app_id =:appId and fr.active_yn='Y' and epr.function_cd= epf.function_cd and epf.app_id=epr.app_id and fur.role_id=epr.role_id\n"
2207 + " select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, \n"
2208 + " fu.login_id, fu.active_yn , fr.role_id, fr.role_name, earf.function_cd , eaf.function_name\n"
2209 + " from fn_user_role a, fn_role fr, fn_user fu , ep_app_role_function earf, ep_app_function eaf\n"
2210 + " where a.role_id in (select b.role_id from ep_app_role_function b where b.role_app_id = 1 and b.app_id =:appId) and a.user_id =fu.user_id and a.role_id = fr.role_id and fr.active_yn='Y' and fu.active_yn='Y'\n"
2211 + " and earf.role_id = a.role_id and earf.function_cd = eaf.function_cd and earf.app_id = eaf.app_id and earf.role_app_id = 1 and fr.active_yn='Y' and fu.active_yn='Y'";
2213 List<EcompUserRoles> userList = entityManager.createQuery(ApplicationUserRoles)
2214 .setParameter("appId", app.getId()).getResultList();
2215 for (EcompUserRoles ecompUserRole : userList) {
2216 boolean found = false;
2217 Set<EcompRole> roles = null;
2218 for (EcompUser user : usersfinalList) {
2219 if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
2220 EcompRole ecompRole = new EcompRole();
2221 ecompRole.setId(ecompUserRole.getRoleId());
2222 ecompRole.setName(ecompUserRole.getRoleName());
2223 roles = user.getRoles();
2224 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
2225 .findAny().orElse(null);
2226 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
2228 roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
2230 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
2231 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
2232 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
2233 epRoleFunction.setName(ecompUserRole.getFunctionName());
2234 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
2235 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
2236 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
2237 roleFunctionSet.add(epRoleFunction);
2238 ecompRole.setRoleFunctions(roleFunctionSet);
2239 roles.add(ecompRole);
2240 user.setRoles(roles);
2246 EcompUser epUser = new EcompUser();
2247 epUser.setOrgId(ecompUserRole.getOrgId());
2248 epUser.setManagerId(ecompUserRole.getManagerId());
2249 epUser.setFirstName(ecompUserRole.getFirstName());
2250 epUser.setLastName(ecompUserRole.getLastName());
2251 epUser.setPhone(ecompUserRole.getPhone());
2252 epUser.setEmail(ecompUserRole.getEmail());
2253 epUser.setOrgUserId(ecompUserRole.getOrgUserId());
2254 epUser.setOrgCode(ecompUserRole.getOrgCode());
2255 epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
2256 epUser.setJobTitle(ecompUserRole.getJobTitle());
2257 epUser.setLoginId(ecompUserRole.getLoginId());
2258 epUser.setActive(true);
2259 roles = new HashSet<>();
2260 EcompRole ecompRole = new EcompRole();
2261 ecompRole.setId(ecompUserRole.getRoleId());
2262 ecompRole.setName(ecompUserRole.getRoleName());
2263 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
2264 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
2265 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
2266 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
2267 epRoleFunction.setName(ecompUserRole.getFunctionName());
2268 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
2269 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
2270 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
2271 roleFunctionSet.add(epRoleFunction);
2272 ecompRole.setRoleFunctions(roleFunctionSet);
2273 roles.add(ecompRole);
2274 epUser.setRoles(roles);
2275 usersfinalList.add(epUser);
2278 ObjectMapper mapper = new ObjectMapper();
2279 for (EcompUser u1 : usersfinalList) {
2280 String str = mapper.writeValueAsString(u1);
2283 } catch (Exception e) {
2284 logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
2287 return usersfinalList;
2290 public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
2292 List<FnApp> appList = getApp(uebkey);
2293 FnApp app = appList.get(0);
2294 List<FnUser> epUserList;
2295 epUserList = getUser(loginId);
2296 List<EcompRole> missingUserAppRoles = new ArrayList<>();
2297 List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
2298 logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
2299 List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
2300 if (userApplicationsRolesfromDB.size() > 0) {
2301 missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
2302 .collect(Collectors.toList());
2304 List<String> missingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
2305 .collect(Collectors.toList());
2306 logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + missingroleNamesList);
2308 List<EcompRole> finalMissingRoleList = new ArrayList<>();
2309 if (missingUserAppRoles.size() > 0) {
2310 final Map<String, Long> params = new HashMap<>();
2311 for (EcompRole role : missingUserAppRoles) {
2312 EcompRole epRole = new EcompRole();
2313 epRole.setId(role.getId());
2314 epRole.setName(role.getName());
2315 String getAppRoleFunctionList =
2316 "SELECT DISTINCT f.app_id , f.function_cd, f.function_name from ep_app_role_function rf, ep_app_function f"
2317 + " where rf.role_id =:roleId and rf.app_id =:appId and rf.app_id = f.app_id and rf.function_cd = f.function_cd";
2318 List<EpAppFunction> appRoleFunctionList = entityManager.createQuery(getAppRoleFunctionList)
2319 .setParameter("roleId", role.getId()).setParameter(APP_ID, app.getId()).getResultList();
2320 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
2321 for (EpAppFunction roleFunc : appRoleFunctionList) {
2322 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
2323 String type = getFunctionCodeType(roleFunc.getFunctionCd());
2324 String action = getFunctionCodeAction(roleFunc.getFunctionCd());
2325 EcompRoleFunction fun = new EcompRoleFunction();
2326 fun.setAction(action);
2327 fun.setCode(functionCode);
2329 fun.setName(roleFunc.getFunctionName());
2330 roleFunctionSet.add(fun);
2333 epRole.setRoleFunctions(roleFunctionSet);
2334 finalMissingRoleList.add(epRole);
2338 return finalMissingRoleList;
2341 private List<EcompRole> getUserAppRoles(FnApp app, FnUser user) {
2342 String getUserAppCurrentRoles = "select distinct fu.role_id, fr.user_id, fu.role_name, fu.priority from fn_role fu left outer join fn_user_role fr ON fu.role_id = fr.role_id and fu.app_id = fr.app_id and fr.role_id != 999 where fu.app_id =:appId and fr.user_id =:userId and fu.active_yn='Y' \n";
2343 List<EPUserAppCurrentRoles> userAppsRolesList = entityManager.createQuery(getUserAppCurrentRoles)
2344 .setParameter("appId", app.getId())
2345 .setParameter("userId", user.getId())
2347 List<EcompRole> setUserRoles = new ArrayList<>();
2348 for (EPUserAppCurrentRoles role : userAppsRolesList) {
2349 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
2350 role.getRoleName());
2351 EcompRole ecompRole = new EcompRole();
2352 ecompRole.setId(role.getRoleId());
2353 ecompRole.setName(role.getRoleName());
2354 setUserRoles.add(ecompRole);
2356 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
2357 setUserRoles.size());
2358 return setUserRoles;
2361 public List<FnUser> getUser(String loginId) throws InvalidUserException {
2362 List<FnUser> userList = fnUserService.getUserWithOrgUserId(loginId);
2363 if (userList.isEmpty()) {
2364 throw new InvalidUserException("User not found");
2369 @Transactional(propagation = Propagation.REQUIRED)
2370 public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
2372 String message = "";
2373 boolean response = false;
2376 List<FnRole> epRoleList = null;
2377 app = getApp(uebkey).get(0);
2378 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2379 epRoleList = getPortalAppRoleInfo(roleId);
2381 epRoleList = getPartnerAppRoleInfo(roleId, app.getId());
2383 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2384 // Delete User Role in External System before deleting role
2385 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
2387 // Delete user app roles
2388 fnRoleService.delete(epRoleList.get(0));
2389 boolean isPortalRequest = false;
2390 deleteRoleDependencyRecords(epRoleList.get(0).getId(), app.getId(), isPortalRequest);
2391 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2392 // Final call to delete role once all dependencies has been
2394 deleteRoleInExternalAuthSystem(epRoleList, app);
2396 fnRoleService.delete(epRoleList.get(0));
2397 logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
2399 } catch (HttpClientErrorException e) {
2400 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
2401 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2402 message = e.getMessage();
2403 } catch (Exception e) {
2404 logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
2405 message = e.getMessage();
2407 return new ExternalRequestFieldsValidator(response, message);
2410 @Transactional(propagation = Propagation.REQUIRED)
2411 public void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
2416 // It should delete only when it portal's roleId
2417 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
2418 // Delete from fn_role_function
2419 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
2420 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2421 query = entityManager.createQuery(sql);
2422 query.executeUpdate();
2423 // Delete from fn_role_composite
2424 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
2425 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2426 query = entityManager.createQuery(sql);
2427 query.executeUpdate();
2429 // Delete from ep_app_role_function
2430 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
2431 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2432 query = entityManager.createQuery(sql);
2433 query.executeUpdate();
2434 // Delete from ep_role_notification
2435 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
2436 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2437 query = entityManager.createQuery(sql);
2438 query.executeUpdate();
2439 // Delete from fn_user_pseudo_role
2440 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
2441 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2442 query = entityManager.createQuery(sql);
2443 query.executeUpdate();
2444 // Delete form EP_WIDGET_CATALOG_ROLE
2445 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
2446 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2447 query = entityManager.createQuery(sql);
2448 query.executeUpdate();
2449 // Delete form EP_WIDGET_CATALOG_ROLE
2450 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
2451 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2452 query = entityManager.createQuery(sql);
2453 query.executeUpdate();
2454 if (!isPortalRequest) {
2455 // Delete form fn_menu_functional_roles
2456 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
2457 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2458 query = entityManager.createQuery(sql);
2459 query.executeUpdate();
2461 } catch (Exception e) {
2462 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
2463 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
2467 private void deleteUserRoleInExternalSystem(FnRole role, FnApp app, String LoginId) throws Exception {
2468 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2469 HttpEntity<String> entity = new HttpEntity<>(headers);
2470 getNameSpaceIfExists(app);
2471 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
2472 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2473 ResponseEntity<String> getResponse = template.exchange(
2474 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
2476 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
2477 + "/" + app.getAuthNamespace() + "."
2478 + role.getRoleName()
2479 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
2480 HttpMethod.GET, entity, String.class);
2481 logger.debug(EELFLoggerDelegate.debugLogger,
2482 "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
2483 getResponse.getBody());
2484 if (getResponse.getStatusCode().value() != 200) {
2485 throw new ExternalAuthSystemException(getResponse.getBody());
2487 String res = getResponse.getBody();
2488 if (!res.equals(IS_EMPTY_JSON_STRING)) {
2489 HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
2490 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
2491 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2492 ResponseEntity<String> deleteResponse = template.exchange(
2493 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
2495 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
2496 + "/" + app.getAuthNamespace() + "."
2497 + role.getRoleName().replaceAll(
2498 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
2499 HttpMethod.DELETE, userRoleentity, String.class);
2500 if (deleteResponse.getStatusCode().value() != 200) {
2501 throw new ExternalAuthSystemException("Failed to delete user role");
2503 logger.debug(EELFLoggerDelegate.debugLogger,
2504 "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
2505 deleteResponse.getStatusCode().value());
2509 public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
2510 FnApp app = getApp(uebkey).get(0);
2511 List<BulkUploadUserRoles> userRolesList;
2512 Integer userRolesAdded = 0;
2513 if (app.getAuthCentral()) {
2514 userRolesList = bulkUploadUserRolesService.getBulkUsersForSingleRole(app.getUebKey(), roleId);
2515 for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2516 userRolesUpload.setRoleName(modifiedRoleName);
2517 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
2518 addUserRoleInExternalSystem(userRolesUpload);
2523 return userRolesAdded;
2526 private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2529 ObjectMapper mapper = new ObjectMapper();
2530 if (EPCommonSystemProperties
2531 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2532 name = userRolesUpload.getOrgUserId()
2533 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2535 ExternalAccessUser extUser = new ExternalAccessUser(name,
2536 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
2537 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2538 String userRole = mapper.writeValueAsString(extUser);
2539 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2540 HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2542 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2543 HttpMethod.POST, entity, String.class);
2544 } catch (HttpClientErrorException e) {
2545 logger.error(EELFLoggerDelegate.errorLogger,
2546 "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
2547 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2548 } catch (Exception e) {
2549 if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2550 logger.error(EELFLoggerDelegate.errorLogger,
2551 "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
2553 logger.error(EELFLoggerDelegate.errorLogger,
2554 "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
2559 private void addNewRoleInExternalSystem(List<FnRole> newRole, FnApp app)
2562 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2563 ObjectMapper mapper = new ObjectMapper();
2565 ExternalAccessRole extRole = new ExternalAccessRole();
2566 extRole.setName(app.getAuthNamespace() + "." + newRole.get(0).getRoleName()
2567 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2568 extRole.setDescription(String.valueOf(newRole.get(0).getRoleName()));
2569 addNewRole = mapper.writeValueAsString(extRole);
2570 HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
2571 logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
2572 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
2573 ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
2574 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2575 HttpMethod.POST, postEntity, String.class);
2576 if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
2577 logger.debug(EELFLoggerDelegate.debugLogger,
2578 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
2579 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
2581 } catch (HttpClientErrorException ht) {
2582 fnRoleService.delete(newRole.get(0));
2583 logger.error(EELFLoggerDelegate.debugLogger,
2584 "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
2585 throw new HttpClientErrorException(ht.getStatusCode());
2589 private void checkIfRoleExitsInExternalSystem(Role checkRole, FnApp app) throws Exception {
2590 getNameSpaceIfExists(app);
2591 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2592 String roleName = app.getAuthNamespace() + "." + checkRole.getName()
2593 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
2594 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
2595 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
2596 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2597 ResponseEntity<String> checkRoleInExternalSystem = template
2598 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
2599 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
2600 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
2602 "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
2603 checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
2604 throw new ExternalAuthSystemException(" Role already exists in external system");
2608 public ResponseEntity<String> getNameSpaceIfExists(FnApp app) throws Exception {
2609 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2610 HttpEntity<String> entity = new HttpEntity<>(headers);
2611 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
2612 ResponseEntity<String> response = null;
2615 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2616 + "nss/" + app.getAuthNamespace(), HttpMethod.GET, entity, String.class);
2617 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
2618 response.getStatusCode().value());
2619 } catch (HttpClientErrorException e) {
2620 logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
2621 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2622 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
2623 throw new InvalidApplicationException("Invalid NameSpace");
2631 private FnRoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
2635 FnRoleFunction cenRoleFun = null;
2636 if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
2637 instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
2638 type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
2639 action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
2640 cenRoleFun = FnRoleFunction.builder().build();
2641 FnRole fnRole = new FnRole();
2642 FnFunction fnFunction = FnFunction.builder().functionCd(instance).name(role.getFunctionName()).type(type)
2643 .action(action).build();
2644 cenRoleFun.setRole(fnRole);
2645 cenRoleFun.setFunctionCd(fnFunction);
2647 type = getFunctionCodeType(role.getFunctionCd());
2648 action = getFunctionCodeAction(role.getFunctionCd());
2649 FnFunction fnFunction = FnFunction.builder().functionCd(role.getFunctionCd()).name(role.getFunctionName())
2650 .type(type).action(action).build();
2651 cenRoleFun.setRole(new FnRole());
2652 cenRoleFun.setFunctionCd(fnFunction);
2657 public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
2658 CentralUser sendUserRoles = null;
2660 CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
2661 sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
2662 } catch (Exception e) {
2663 logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
2666 return sendUserRoles;
2669 private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
2671 List<FnApp> appList = getApp(uebkey);
2672 app = appList.get(0);
2673 FnUser user = fnUserService.loadUserByUsername(loginId);
2674 Set<FnUserRole> userAppSet = user.getUserApps();
2675 return createEPUser(user, userAppSet, app);
2678 public List<FnApp> getApp(String uebkey) throws Exception {
2679 List<FnApp> app = null;
2681 app = fnAppService.getByUebKey(uebkey);
2682 if (!app.isEmpty() && !app.get(0).getEnabled()
2683 && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2684 throw new InactiveApplicationException("Application:" + app.get(0).getAppName() + " is Unavailable");
2686 } catch (Exception e) {
2687 logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
2693 private CentralV2User createEPUser(FnUser userInfo, Set<FnUserRole> userAppSet, FnApp app) {
2694 CentralV2User userAppList = CentralV2User.builder().build();
2695 CentralV2User user1;
2696 List<FnRole> globalRoleList = new ArrayList<>();
2698 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2699 globalRoleList = fnRoleService.userAppGlobalRoles(userInfo.getId(), app.getId());
2701 userAppList.setUserApps(new TreeSet<>());
2702 for (FnUserRole userApp : userAppSet) {
2703 if (userApp.getRoleId().getActiveYn()) {
2704 FnApp epApp = userApp.getFnAppId();
2705 String globalRole = userApp.getRoleId().getRoleName().toLowerCase();
2706 if (((epApp.getId().equals(app.getId()))
2707 && (!userApp.getRoleId().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
2708 || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
2709 && (globalRole.toLowerCase().startsWith("global_")))) {
2710 CentralV2UserApp cua = new CentralV2UserApp();
2711 cua.setUserId(null);
2712 CentralApp cenApp = CentralApp.builder().id(1L).created(epApp.getCreated())
2713 .modified(epApp.getModified()).createdId(epApp.getId())
2714 .modifiedId(epApp.getModifiedId().getId()).rowNum(epApp.getRowNum())
2715 .name(epApp.getAppName()).imageUrl(epApp.getAppImageUrl())
2716 .description(epApp.getAppDescription()).notes(epApp.getAppNotes())
2717 .url(epApp.getAppUrl()).alternateUrl(epApp.getAppAlternateUrl())
2718 .restEndpoint(epApp.getAppRestEndpoint()).mlAppName(epApp.getMlAppName())
2719 .mlAppAdminId(epApp.getMlAppAdminId()).motsId(String.valueOf(epApp.getMotsId()))
2720 .appPassword(epApp.getAppPassword()).open(String.valueOf(epApp.getOpen()))
2721 .enabled(String.valueOf(epApp.getEnabled())).thumbnail(epApp.getThumbnail())
2722 .username(epApp.getAppUsername()).uebKey(epApp.getUebKey())
2723 .uebSecret(epApp.getUebSecret()).uebTopicName(epApp.getUebTopicName())
2725 cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
2728 if (globalRole.toLowerCase().startsWith("global_")
2729 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
2730 && !epApp.getId().equals(app.getId())) {
2731 appId = app.getId();
2732 FnRole result = null;
2733 if (globalRoleList.size() > 0) {
2734 result = globalRoleList.stream()
2735 .filter(x -> userApp.getRoleId().getId().equals(x.getId())).findAny()
2738 if (result == null) {
2742 appId = userApp.getFnAppId().getId();
2744 List<EpAppFunction> appRoleFunctionList = epAppFunctionService
2745 .getAppRoleFunctionList(userApp.getRoleId().getId(), appId);
2746 SortedSet<EpAppFunction> roleFunctionSet = new TreeSet<>();
2747 for (EpAppFunction roleFunc : appRoleFunctionList) {
2748 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
2749 String type = getFunctionCodeType(roleFunc.getFunctionCd());
2750 String action = getFunctionCodeAction(roleFunc.getFunctionCd());
2751 EpAppFunction cenRoleFunc = new EpAppFunction(roleFunc.getId(),
2752 functionCode, roleFunc.getFunctionName(), null, type, action, null);
2753 roleFunctionSet.add(cenRoleFunc);
2756 if (globalRole.toLowerCase().startsWith("global_")
2757 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2758 userRoleId = userApp.getRoleId().getId();
2760 userRoleId = userApp.getRoleId().getAppRoleId();
2762 CentralV2Role cenRole = CentralV2Role.builder().id(userRoleId)
2763 .created(userApp.getRoleId().getCreated()).modified(userApp.getRoleId().getModified())
2764 .createdId(userApp.getRoleId().getCreatedId().getId())
2765 .modifiedId(userApp.getRoleId().getModifiedId().getId())
2766 .rowNum(userApp.getRoleId().getRowNum()).name(userApp.getRoleId().getRoleName())
2767 .active(userApp.getRoleId().getActiveYn()).priority(userApp.getRoleId().getPriority())
2768 //.roleFunctions(roleFunctionSet).setChildRoles(null).setParentRoles(null)
2770 cua.setRole(cenRole);
2771 userAppList.getUserApps().add(cua);
2775 user1 = CentralV2User.builder().id(null).created(userInfo.getCreated())
2776 .modified(userInfo.getModified()).createdId(userInfo.getCreatedId().getId())
2777 .modifiedId(userInfo.getModifiedId().getId()).rowNum(userInfo.getRowNum())
2778 .orgId(userInfo.getOrgId().getOrgId()).managerId(userInfo.getOrgManagerUserId())
2779 .firstName(userInfo.getFirstName()).middleInitial(userInfo.getMiddleName())
2780 .lastName(userInfo.getLastName()).phone(userInfo.getPhone()).fax(userInfo.getFax())
2781 .cellular(userInfo.getCellular()).email(userInfo.getEmail())
2782 .addressId(userInfo.getAddressId()).alertMethodCd(userInfo.getAlertMethodCd().getAlertMethodCd())
2783 .hrid(userInfo.getHrid()).orgUserId(userInfo.getOrgUserId()).orgCode(userInfo.getOrgCode())
2784 .address1(userInfo.getAddressLine1()).address2(userInfo.getAddressLine2()).city(userInfo.getCity())
2785 .state(userInfo.getStateCd()).zipCode(userInfo.getZipCode()).country(userInfo.getCountryCd())
2786 .orgManagerUserId(userInfo.getOrgManagerUserId()).locationClli(userInfo.getLocationClli())
2787 .businessCountryCode(userInfo.getBusinessUnit())
2788 .businessCountryName(userInfo.getBusinessUnitName())
2789 .businessUnit(userInfo.getBusinessUnit()).businessUnitName(userInfo.getBusinessUnitName())
2790 .department(userInfo.getDepartment()).departmentName(userInfo.getDepartmentName())
2791 .companyCode(userInfo.getOrgCode()).company(userInfo.getCompany())
2792 .zipCodeSuffix(userInfo.getZipCode()).jobTitle(userInfo.getJobTitle())
2793 //.commandChain(userInfo.getCommandChain()).siloStatus(userInfo.getSiloStatus())
2794 .costCenter(userInfo.getCostCenter()).financialLocCode(userInfo.getFinLocCode())
2795 .loginId(userInfo.getLoginId()).loginPwd(userInfo.getLoginPwd())
2796 .lastLoginDate(userInfo.getLastLoginDate()).active(userInfo.getActiveYn())
2797 //.internal(userInfo.getIsInternalYn()).selectedProfileId(userInfo.getSelectedProfileId())
2798 //.timeZoneId(userInfo.getTimezone().getTimezoneId()).online(userInfo.isOnline())
2799 //.chatId(userInfo.getChatId()).setUserApps(userAppList.getUserApps()).setPseudoRoles(null)
2801 } catch (Exception e) {
2802 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
2808 private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
2809 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
2810 Set<CentralUserApp> userApps = new TreeSet<>();
2811 for (CentralV2UserApp userApp : userV2Apps) {
2812 CentralApp app = userApp.getApp();
2813 CentralUserApp cua = new CentralUserApp();
2814 cua.setUserId(null);
2816 SortedSet<EpAppFunction> cenRoleFunction = new TreeSet<>();
2817 for (DomainVo vo : userApp.getRole().getRoleFunctions()) {
2818 Optional<EpAppFunction> epApp = epAppFunctionService.getForId(vo.getId());
2819 if (epApp.isPresent()) {
2820 EpAppFunction cenRoleFunc = EpAppFunction.builder().functionCd(epApp.get().getFunctionCd())
2822 epApp.get().getFunctionName()).build();
2823 cenRoleFunction.add(cenRoleFunc);
2826 CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
2827 userApp.getRole().isActive(), userApp.getRole().getPriority(), cenRoleFunction);
2831 return CentralUser.builder().id(cenV2User.getId()).created(cenV2User.getCreated())
2832 .modified(cenV2User.getModified()).createdId(cenV2User.getCreatedId())
2833 .modifiedId(cenV2User.getModifiedId()).rowNum(cenV2User.getRowNum())
2834 .orgId(cenV2User.getOrgId()).managerId(cenV2User.getManagerId())
2835 .firstName(cenV2User.getFirstName()).middleInitial(cenV2User.getMiddleInitial())
2836 .lastName(cenV2User.getLastName()).phone(cenV2User.getPhone()).fax(cenV2User.getFax())
2837 .cellular(cenV2User.getCellular()).email(cenV2User.getEmail())
2838 .addressId(cenV2User.getAddressId()).alertMethodCd(cenV2User.getAlertMethodCd())
2839 .hrid(cenV2User.getHrid()).orgUserId(cenV2User.getOrgUserId()).orgCode(cenV2User.getOrgCode())
2840 .address1(cenV2User.getAddress1()).address2(cenV2User.getAddress2()).city(cenV2User.getCity())
2841 .state(cenV2User.getState()).zipCode(cenV2User.getZipCode()).country(cenV2User.getCountry())
2842 .orgManagerUserId(cenV2User.getOrgManagerUserId()).locationClli(cenV2User.getLocationClli())
2843 .businessCountryCode(cenV2User.getBusinessCountryCode())
2844 .businessCountryName(cenV2User.getBusinessCountryName()).businessUnit(cenV2User.getBusinessUnit())
2845 .businessUnitName(cenV2User.getBusinessUnitName()).department(cenV2User.getDepartment())
2846 .departmentName(cenV2User.getDepartmentName()).companyCode(cenV2User.getCompanyCode())
2847 .company(cenV2User.getCompany()).zipCodeSuffix(cenV2User.getZipCodeSuffix())
2848 .jobTitle(cenV2User.getJobTitle()).commandChain(cenV2User.getCommandChain())
2849 .siloStatus(cenV2User.getSiloStatus()).costCenter(cenV2User.getCostCenter())
2850 .financialLocCode(cenV2User.getFinancialLocCode()).loginId(cenV2User.getLoginId())
2851 .loginPwd(cenV2User.getLoginPwd()).lastLoginDate(cenV2User.getLastLoginDate())
2852 .active(cenV2User.isActive()).internal(cenV2User.isInternal())
2853 .selectedProfileId(cenV2User.getSelectedProfileId()).timeZoneId(cenV2User.getTimeZoneId())
2854 .online(cenV2User.isOnline()).chatId(cenV2User.getChatId()).userApps(userApps).build();
2857 public CentralV2Role getRoleInfo(final Long roleId, final String uebkey) throws Exception {
2858 List<CentralV2Role> roleList = new ArrayList<>();
2859 CentralV2Role cenRole = CentralV2Role.builder().build();
2860 List<FnRole> roleInfo;
2863 app = getApp(uebkey);
2864 if (app.isEmpty()) {
2865 throw new InactiveApplicationException("Application not found");
2867 if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2868 List<FnRole> globalRoleList = getGlobalRolesOfPortal();
2869 if (globalRoleList.size() > 0) {
2870 FnRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
2872 if (result != null) {
2873 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
2877 if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2878 roleInfo = getPortalAppRoleInfo(roleId);
2880 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0).getId());
2882 roleList = createCentralRoleObject(app, roleInfo, roleList);
2883 if (roleList.isEmpty()) {
2886 } catch (Exception e) {
2887 logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
2890 return roleList.get(0);
2893 private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
2894 CentralV2Role finalGlobalrole;
2895 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
2897 roleWithApplicationRoleFucntions = entityManager
2898 .createNamedQuery("getGlobalRoleForRequestedApp")
2899 .setParameter("roleId", roleId)
2900 .setParameter("requestedAppId", requestedAppId)
2902 } catch (Exception e) {
2903 logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
2905 if (roleWithApplicationRoleFucntions.size() > 0) {
2906 List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
2907 finalGlobalrole = rolesfinalList.get(0);
2909 List<FnRole> roleList = getPortalAppRoleInfo(roleId);
2910 finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
2912 return finalGlobalrole;
2915 public EpAppFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
2916 String code = EcompPortalUtils.getFunctionCode(functionCode);
2917 String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
2918 EpAppFunction roleFunc = null;
2919 FnApp app = getApp(uebkey).get(0);
2920 List<EpAppFunction> getRoleFuncList = null;
2922 getRoleFuncList = epAppFunctionService.getRoleFunction(functionCode, app.getId());
2923 if (getRoleFuncList.isEmpty()) {
2924 getRoleFuncList = epAppFunctionService.getRoleFunction(encodedCode, app.getId());
2925 if (getRoleFuncList.isEmpty()) {
2929 if (getRoleFuncList.size() > 1) {
2930 EpAppFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
2931 if (cenV2RoleFunction == null) {
2934 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
2936 // Check even if single record have pipes
2937 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getFunctionCd().contains(FUNCTION_PIPE)) {
2938 roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
2940 roleFunc = getRoleFuncList.get(0);
2943 } catch (Exception e) {
2944 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
2950 private EpAppFunction appFunctionListFilter(String roleFuncCode, List<EpAppFunction> roleFunction) {
2951 final Map<String, EpAppFunction> appFunctionsFilter = new HashMap<>();
2952 final Map<String, EpAppFunction> appFunctionsFilterPipes = new HashMap<>();
2953 EpAppFunction getExactFunctionCode;
2954 for (EpAppFunction cenRoleFunction : roleFunction) {
2955 appFunctionsFilter.put(cenRoleFunction.getFunctionCd(), cenRoleFunction);
2956 appFunctionsFilterPipes
2957 .put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getFunctionCd()), cenRoleFunction);
2959 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
2960 if (getExactFunctionCode == null) {
2961 getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
2963 return getExactFunctionCode;
2966 private EpAppFunction checkIfPipesExitsInFunctionCode(EpAppFunction getRoleFuncList) {
2967 EpAppFunction roleFunc;
2968 String functionCodeFormat = getRoleFuncList.getFunctionCd();
2969 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
2970 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
2971 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
2972 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
2973 roleFunc = new EpAppFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
2974 getRoleFuncList.getFunctionName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
2975 newfunctionActionFormat, getRoleFuncList.getEditUrl());
2977 roleFunc = EpAppFunction.builder()
2978 .id(getRoleFuncList.getId())
2979 .functionCd(functionCodeFormat)
2980 .functionName(getRoleFuncList.getFunctionName())
2981 .appId(getRoleFuncList.getAppId())
2982 .editUrl(getRoleFuncList.getEditUrl())
2988 public boolean saveCentralRoleFunction(EpAppFunction domainCentralRoleFunction, FnApp app)
2990 boolean saveOrUpdateFunction = false;
2992 if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getFunctionCd())) {
2993 domainCentralRoleFunction
2994 .setFunctionCd(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getFunctionCd()));
2996 final Map<String, String> functionParams = new HashMap<>();
2997 functionParams.put("appId", String.valueOf(app.getId()));
2998 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2999 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
3001 if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
3002 domainCentralRoleFunction.setFunctionCd(domainCentralRoleFunction.getType() + FUNCTION_PIPE
3003 + domainCentralRoleFunction.getFunctionCd() + FUNCTION_PIPE + domainCentralRoleFunction
3006 domainCentralRoleFunction.setAppId(app);
3007 epAppFunctionService.save(domainCentralRoleFunction);
3008 saveOrUpdateFunction = true;
3009 } catch (Exception e) {
3010 logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
3013 return saveOrUpdateFunction;
3016 private void addRoleFunctionInExternalSystem(EpAppFunction domainCentralRoleFunction, FnApp app)
3018 ObjectMapper mapper = new ObjectMapper();
3019 ExternalAccessPerms extPerms = new ExternalAccessPerms();
3020 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3022 String instance = "";
3024 if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
3025 || domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)) {
3026 type = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
3027 ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getFunctionCd())
3028 : domainCentralRoleFunction.getType();
3029 instance = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
3030 ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getFunctionCd())
3031 : domainCentralRoleFunction.getFunctionCd();
3032 action = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
3033 ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getFunctionCd())
3034 : domainCentralRoleFunction.getAction();
3036 type = domainCentralRoleFunction.getFunctionCd().contains("menu") ? "menu" : "url";
3037 instance = domainCentralRoleFunction.getFunctionCd();
3040 // get Permissions from External Auth System
3041 JSONArray extPermsList = getExtAuthPermissions(app.getAuthNamespace());
3042 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
3043 String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
3044 boolean checkIfFunctionsExits = permsDetailList.stream()
3045 .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
3046 if (!checkIfFunctionsExits) {
3048 extPerms.setAction(action);
3049 extPerms.setInstance(instance);
3050 extPerms.setType(app.getAuthNamespace() + "." + type);
3051 extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
3052 String addFunction = mapper.writeValueAsString(extPerms);
3053 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
3054 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
3055 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
3056 ResponseEntity<String> addPermResponse = template.exchange(
3057 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
3058 HttpMethod.POST, entity, String.class);
3059 logger.debug(EELFLoggerDelegate.debugLogger,
3060 "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
3061 addPermResponse.getStatusCode().value(), addFunction);
3062 } catch (HttpClientErrorException e) {
3063 logger.error(EELFLoggerDelegate.errorLogger,
3064 "HttpClientErrorException - Failed to add function in external central auth system", e);
3065 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3067 } catch (Exception e) {
3068 logger.error(EELFLoggerDelegate.errorLogger,
3069 "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
3074 extPerms.setAction(action);
3075 extPerms.setInstance(instance);
3076 extPerms.setType(app.getAuthNamespace() + "." + type);
3077 extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
3078 String updateRoleFunction = mapper.writeValueAsString(extPerms);
3079 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
3080 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
3081 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
3082 ResponseEntity<String> updatePermResponse = template.exchange(
3083 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
3084 HttpMethod.PUT, entity, String.class);
3085 logger.debug(EELFLoggerDelegate.debugLogger,
3086 "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
3087 updateRoleFunction, updatePermResponse.getStatusCode().value());
3088 } catch (HttpClientErrorException e) {
3089 logger.error(EELFLoggerDelegate.errorLogger,
3090 "HttpClientErrorException - Failed to add function in external central auth system", e);
3091 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3093 } catch (Exception e) {
3094 logger.error(EELFLoggerDelegate.errorLogger,
3095 "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
3102 public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3103 SortedSet<EpAppFunction> cenRoleFuncList = new TreeSet<>();
3104 for (DomainVo vo : v2CenRole.getRoleFunctions()) {
3105 Optional<EpAppFunction> v2CenRoleFunc = epAppFunctionService.getForId(vo.getId());
3106 if (v2CenRoleFunc.isPresent()) {
3107 EpAppFunction roleFunc = EpAppFunction.builder()
3108 .functionCd(v2CenRoleFunc.get().getFunctionCd())
3109 .functionName(v2CenRoleFunc.get().getFunctionName())
3111 cenRoleFuncList.add(roleFunc);
3115 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
3119 public List<EpAppFunction> getRoleFuncList(String uebkey) throws Exception {
3120 FnApp app = getApp(uebkey).get(0);
3121 List<EpAppFunction> finalRoleList = new ArrayList<>();
3122 List<EpAppFunction> getRoleFuncList = epAppFunctionService.getAllRoleFunctions(app.getId());
3123 for (EpAppFunction roleFuncItem : getRoleFuncList) {
3124 String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getFunctionCd());
3126 if (roleFuncItem.getFunctionCd().contains("|")) {
3127 type = EcompPortalUtils.getFunctionType(roleFuncItem.getFunctionCd());
3129 type = getFunctionCodeType(roleFuncItem.getFunctionCd());
3131 String action = getFunctionCodeAction(roleFuncItem.getFunctionCd());
3132 roleFuncItem.setFunctionCd(EPUserUtils.decodeFunctionCode(code));
3133 roleFuncItem.setType(type);
3134 roleFuncItem.setAction(action);
3135 finalRoleList.add(roleFuncItem);
3137 return finalRoleList;
3140 public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
3141 List<EpAppFunction> answer) {
3142 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3143 for (EpAppFunction cenRoleFunc : answer) {
3144 CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3145 setRoleFunc.setCode(cenRoleFunc.getFunctionCd());
3146 setRoleFunc.setName(cenRoleFunc.getFunctionName());
3147 addRoleFuncList.add(setRoleFunc);
3149 return addRoleFuncList;
3152 @Transactional(rollbackFor = Exception.class)
3153 public boolean deleteCentralRoleFunction(String code, FnApp app) {
3154 boolean deleteFunctionResponse = false;
3156 List<EpAppFunction> domainCentralRoleFunction = epAppFunctionService.getRoleFunction(code, app.getId());
3157 EpAppFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
3158 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
3159 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
3160 // Delete role function dependency records
3161 deleteAppRoleFunctions(appFunctionCode.getFunctionCd(), app.getId());
3163 epAppFunctionService.deleteOne(appFunctionCode);
3164 deleteFunctionResponse = true;
3165 } catch (Exception e) {
3166 logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
3168 return deleteFunctionResponse;
3171 private void deleteRoleFunctionInExternalSystem(EpAppFunction domainCentralRoleFunction, FnApp app) {
3173 ObjectMapper mapper = new ObjectMapper();
3174 ExternalAccessPerms extPerms = new ExternalAccessPerms();
3175 String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getFunctionCd());
3176 String checkType = getFunctionCodeType(domainCentralRoleFunction.getFunctionCd());
3177 String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getFunctionCd());
3178 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3179 extPerms.setAction(actionValue);
3180 extPerms.setInstance(instanceValue);
3181 extPerms.setType(app.getAuthNamespace() + "." + checkType);
3182 extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
3183 String deleteRoleFunction = mapper.writeValueAsString(extPerms);
3184 HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
3185 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
3186 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
3187 ResponseEntity<String> delPermResponse = template
3188 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3189 + "perm?force=true", HttpMethod.DELETE, entity, String.class);
3190 logger.debug(EELFLoggerDelegate.debugLogger,
3191 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
3192 deleteRoleFunction, delPermResponse.getStatusCode().value());
3193 } catch (HttpClientErrorException e) {
3194 logger.error(EELFLoggerDelegate.errorLogger,
3195 "HttpClientErrorException - Failed to delete functions in External System", e);
3196 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3197 } catch (Exception e) {
3198 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
3199 logger.debug(EELFLoggerDelegate.debugLogger,
3200 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB",
3203 logger.error(EELFLoggerDelegate.errorLogger,
3204 "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
3209 private void deleteAppRoleFunctions(final String code, final Long appId) {
3210 epAppFunctionService.deleteByAppIdAndFunctionCd(appId, code);
3213 public Integer updateAppRoleDescription(String uebkey) {
3214 Integer roleDescUpdated = 0;
3217 app = getApp(uebkey).get(0);
3218 List<FnRole> roles = getAppRoles(app.getId());
3219 for (FnRole epRole : roles) {
3220 Role role = new Role();
3221 role.setName(epRole.getRoleName());
3222 boolean status = addRoleDescriptionInExtSystem(role.getName(), app.getAuthNamespace());
3227 } catch (Exception e) {
3228 logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
3230 return roleDescUpdated;
3233 public Role convertCentralRoleToRole(String result) {
3234 ObjectMapper mapper = new ObjectMapper();
3235 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3236 Role newRole = new Role();
3238 newRole = mapper.readValue(result, Role.class);
3239 } catch (IOException e) {
3240 logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3242 if (newRole.getRoleFunctions() != null) {
3243 Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3244 Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3245 for (Object nextValue : roleFunctionList) {
3246 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3247 roleFunctionListNew.add(roleFun);
3249 newRole.setRoleFunctions(roleFunctionListNew);
3254 public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, FnApp app) throws Exception {
3255 ObjectMapper mapper = new ObjectMapper();
3256 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3258 ExternalAccessRolePerms extRolePerms;
3259 ExternalAccessPerms extPerms;
3260 extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + data.getType(),
3261 EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction());
3262 String appNameSpace = "";
3263 if (data.isGlobalRolePartnerFunc()) {
3265 appNameSpace = fnAppService.getById(1L).getAuthNamespace();
3267 appNameSpace = app.getAuthNamespace();
3269 extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
3270 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3271 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3272 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3273 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3274 } catch (HttpClientErrorException e) {
3275 logger.error(EELFLoggerDelegate.errorLogger,
3276 "HttpClientErrorException - Failed to add role function in external central auth system", e);
3277 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3279 } catch (Exception e) {
3280 logger.error(EELFLoggerDelegate.errorLogger,
3281 "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);