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 java.time.LocalDateTime;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.List;
55 import java.util.Optional;
57 import java.util.SortedSet;
58 import java.util.TreeSet;
59 import java.util.stream.Collectors;
60 import javax.persistence.EntityManager;
61 import javax.persistence.Query;
62 import javax.persistence.Tuple;
63 import org.apache.commons.lang.StringUtils;
64 import org.apache.cxf.transport.http.HTTPException;
65 import org.hibernate.Session;
66 import org.hibernate.Transaction;
67 import org.json.JSONArray;
68 import org.json.JSONObject;
69 import org.onap.portal.domain.db.ep.EpAppFunction;
70 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
71 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
72 import org.onap.portal.domain.db.fn.FnApp;
73 import org.onap.portal.domain.db.fn.FnFunction;
74 import org.onap.portal.domain.db.fn.FnMenuFunctional;
75 import org.onap.portal.domain.db.fn.FnMenuFunctionalRoles;
76 import org.onap.portal.domain.db.fn.FnRole;
77 import org.onap.portal.domain.db.fn.FnRoleFunction;
78 import org.onap.portal.domain.db.fn.FnUser;
79 import org.onap.portal.domain.db.fn.FnUserRole;
80 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
81 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
82 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
83 import org.onap.portal.domain.dto.transport.CentralV2Role;
84 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
85 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
86 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
87 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
89 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
90 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
91 import org.onap.portal.domain.dto.transport.Role;
92 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
93 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
94 import org.onap.portal.exception.DeleteDomainObjectFailedException;
95 import org.onap.portal.exception.SyncUserRolesException;
96 import org.onap.portal.logging.format.EPAppMessagesEnum;
97 import org.onap.portal.logging.logic.EPLogUtil;
98 import org.onap.portal.service.appFunction.EpAppFunctionService;
99 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
100 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
101 import org.onap.portal.service.app.FnAppService;
102 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
103 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
104 import org.onap.portal.service.role.FnRoleService;
105 import org.onap.portal.service.userRole.FnUserRoleService;
106 import org.onap.portal.service.user.FnUserService;
107 import org.onap.portal.utils.EPCommonSystemProperties;
108 import org.onap.portal.utils.EPUserUtils;
109 import org.onap.portal.utils.EcompPortalUtils;
110 import org.onap.portal.utils.PortalConstants;
111 import org.onap.portalsdk.core.domain.RoleFunction;
112 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
113 import org.onap.portalsdk.core.restful.domain.EcompRole;
114 import org.onap.portalsdk.core.util.SystemProperties;
115 import org.springframework.beans.factory.annotation.Autowired;
116 import org.springframework.http.HttpEntity;
117 import org.springframework.http.HttpHeaders;
118 import org.springframework.http.HttpMethod;
119 import org.springframework.http.HttpStatus;
120 import org.springframework.http.ResponseEntity;
121 import org.springframework.stereotype.Service;
122 import org.springframework.transaction.annotation.Transactional;
123 import org.springframework.web.client.HttpClientErrorException;
124 import org.springframework.web.client.RestTemplate;
128 public class AdminRolesService {
130 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
131 private static final Object syncRests = new Object();
132 private final RestTemplate template = new RestTemplate();
134 private Long SYS_ADMIN_ROLE_ID = 38L;
135 private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
136 private final Long ECOMP_APP_ID = 1L;
137 private final String ADMIN_ACCOUNT = "Is account admin for user {}";
139 private final AppsCacheService appsCacheService;
140 private final EntityManager entityManager;
141 private final FnUserService fnUserService;
142 private final FnRoleService fnRoleService;
143 private final FnAppService fnAppService;
144 private final FnMenuFunctionalService fnMenuFunctionalService;
145 private final FnUserRoleService fnUserRoleService;
146 private final EpAppFunctionService epAppFunctionService;
147 private final EcompUserAppRolesService ecompUserAppRolesService;
148 private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
149 private final ApplicationsRestClientService applicationsRestClientService;
150 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
151 private final ExternalAccessRolesService externalAccessRolesService;
152 private final EpUserRolesRequestService epUserRolesRequestService;
155 public AdminRolesService(AppsCacheService appsCacheService,
156 final EntityManager entityManager,
157 final FnUserService fnUserService, FnRoleService fnRoleService,
158 FnAppService fnAppService,
159 FnMenuFunctionalService fnMenuFunctionalService,
160 final FnUserRoleService fnUserRoleService,
161 EpAppFunctionService epAppFunctionService,
162 EcompUserAppRolesService ecompUserAppRolesService,
163 FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
164 ApplicationsRestClientService applicationsRestClientService,
165 EpUserRolesRequestDetService epUserRolesRequestDetService,
166 ExternalAccessRolesService externalAccessRolesService,
167 EpUserRolesRequestService epUserRolesRequestService) {
168 this.appsCacheService = appsCacheService;
169 this.entityManager = entityManager;
170 this.fnUserService = fnUserService;
171 this.fnRoleService = fnRoleService;
172 this.fnAppService = fnAppService;
173 this.fnMenuFunctionalService = fnMenuFunctionalService;
174 this.fnUserRoleService = fnUserRoleService;
175 this.epAppFunctionService = epAppFunctionService;
176 this.ecompUserAppRolesService = ecompUserAppRolesService;
177 this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
178 this.applicationsRestClientService = applicationsRestClientService;
179 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
180 this.externalAccessRolesService = externalAccessRolesService;
181 this.epUserRolesRequestService = epUserRolesRequestService;
184 public boolean isSuperAdmin(final String loginId) {
185 boolean isSuperAdmin;
187 isSuperAdmin = fnUserRoleService
188 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
189 } catch (Exception e) {
190 logger.error("isSuperAdmin exception: " + e.toString());
193 logger.info("isSuperAdmin " + isSuperAdmin);
197 public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
199 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
200 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
201 logger.debug(EELFLoggerDelegate.debugLogger,
202 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
203 orgUserId, userAdminApps.size());
205 for (FnUserRole userApp : userApps) {
206 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
207 userAdminApps.size() > 1)) {
208 logger.debug(EELFLoggerDelegate.debugLogger,
209 "Is account admin for userAdminApps() - for user {}, found Id {}",
210 orgUserId, userApp.getRoleId().getId());
214 } catch (Exception e) {
215 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
216 logger.error(EELFLoggerDelegate.errorLogger,
217 "Exception occurred while executing isAccountAdmin operation",
223 public boolean isUser(final long userId) {
225 FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
226 if (currentUser != null && currentUser.getId() != null) {
227 for (FnUserRole userApp : currentUser.getUserApps()) {
228 if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
229 FnRole role = userApp.getRoleId();
230 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
231 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
232 if (role.getActiveYn()) {
239 } catch (Exception e) {
240 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
241 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
247 public boolean isRoleAdmin(Long userId) {
249 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
250 List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
251 logger.debug(EELFLoggerDelegate.debugLogger,
252 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
253 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
254 Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
255 Set<String> roleFunSet;
256 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
257 .collect(Collectors.toSet());
258 if (!roleFunSet.isEmpty()) {
259 for (String roleFunction : roleFunSet) {
260 String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
261 getRoleFuncListOfPortalSet1.add(type);
265 boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
266 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
267 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
268 checkIfFunctionsExits);
270 return checkIfFunctionsExits;
272 } catch (Exception e) {
273 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
274 logger.error(EELFLoggerDelegate.errorLogger,
275 "Exception occurred while executing isRoleAdmin operation",
281 private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
282 boolean isApplicationAccountAdmin = false;
284 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
285 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
286 if (!userAdminApps.isEmpty()) {
287 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
288 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
291 } catch (Exception e) {
292 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
293 logger.error(EELFLoggerDelegate.errorLogger,
294 "Exception occurred while executing isAccountAdminOfApplication operation", e);
296 logger.debug(EELFLoggerDelegate.debugLogger,
297 "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
299 return isApplicationAccountAdmin;
303 private List<Integer> getAdminAppsForTheUser(final Long userId) {
304 String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)";
305 return entityManager.createQuery(query, Integer.class)
306 .setParameter("userId", userId).getResultList();
309 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
310 AppWithRolesForUser newAppRolesForUser) {
311 boolean result = false;
312 boolean epRequestValue = false;
314 String reqMessage = "";
315 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
316 userId = newAppRolesForUser.getOrgUserId().trim();
318 Long appId = newAppRolesForUser.getAppId();
319 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
321 if (userId.length() > 0) {
322 ObjectMapper mapper = new ObjectMapper();
323 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
326 FnApp app = fnAppService.getById(appId);
328 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
330 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
332 boolean checkIfUserIsOnlyRoleAdmin =
333 isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
334 if (checkIfUserIsOnlyRoleAdmin) {
335 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
336 if (!roleInAppForUser.getIsApplied()) {
337 EcompRole ecompRole = new EcompRole();
338 ecompRole.setId(roleInAppForUser.getRoleId());
339 ecompRole.setName(roleInAppForUser.getRoleName());
340 rolesGotDeletedFromApprover.add(ecompRole);
345 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
347 boolean systemUser = newAppRolesForUser.isSystemUser();
349 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
352 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
353 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
354 userRolesInLocalApp);
355 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
356 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
357 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
358 // Apply changes in external Access system
360 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
362 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
364 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
366 systemUser, rolesGotDeletedByApprover, false);
368 } else if (!app.getAuthCentral() && systemUser) {
369 throw new Exception("For non-centralized application we cannot add systemUser");
370 } else { // if centralized app
371 if (app.getAuthCentral()) {
372 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
373 pushRemoteUser(roleInAppForUserList, userId, app, mapper,
374 applicationsRestClientService, false);
377 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
378 roleInAppForUserList);
379 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
381 userRolesInLocalApp);
382 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
383 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
385 // Apply changes in external Access system
386 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
388 epRequestValue, false, rolesGotDeletedFromApprover,
389 checkIfUserIsOnlyRoleAdmin);
391 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
392 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
393 checkIfUserIsOnlyRoleAdmin);
395 // In case if portal is not centralized then follow existing approach
396 else if (!app.getAuthCentral() && app.getId()
397 .equals(PortalConstants.PORTAL_APP_ID)) {
398 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
399 roleInAppForUserList);
400 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
402 userRolesInLocalApp);
403 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
404 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
405 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
406 } else {// remote app
407 FnUser remoteAppUser;
408 if (!app.getAuthCentral() && !app.getId()
409 .equals(PortalConstants.PORTAL_APP_ID)) {
411 remoteAppUser = checkIfRemoteUserExits(userId, app,
412 applicationsRestClientService);
414 if (remoteAppUser == null) {
415 addRemoteUser(roleInAppForUserList, userId, app,
416 mapper, applicationsRestClientService);
418 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
419 roleInAppForUserList, mapper,
420 applicationsRestClientService, appId, userId);
421 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
423 userRolesInRemoteApp);
424 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
425 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
426 epRequestValue, null, false, rolesGotDeletedByApprover, false);
428 // If no roles remain, request app to set user inactive.
429 if (userRolesInRemoteApp.size() == 0) {
430 logger.debug(EELFLoggerDelegate.debugLogger,
431 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
434 postUserToRemoteApp(userId, app,
435 applicationsRestClientService);
440 } catch (Exception e) {
441 String message = String.format(
442 "Failed to create user or update user roles for User %s, AppId %s",
443 userId, Long.toString(appId));
444 logger.error(EELFLoggerDelegate.errorLogger, message, e);
446 reqMessage = e.getMessage();
450 return new ExternalRequestFieldsValidator(result, reqMessage);
454 private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
455 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
457 pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
458 roleInAppForUserList, appRoleIdUsed);
462 private void postUserToRemoteApp(String userId, FnApp app,
463 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
465 getUser(userId, app, applicationsRestClientService);
469 private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
470 throws HTTPException {
471 return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
475 private void pushUserOnRemoteApp(String userId, FnApp app,
476 ApplicationsRestClientService applicationsRestClientService,
477 ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
481 client = fnUserService.loadUserByUsername(userId);
483 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
484 if (client == null) {
485 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
486 logger.error(EELFLoggerDelegate.errorLogger, msg);
487 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
488 if (!userList.isEmpty()) {
489 logger.debug(EELFLoggerDelegate.debugLogger,
490 userList.get(0).getOrgUserId() + " User was found in Portal");
491 client = userList.get(0);
492 client.setUserApps(Collections.EMPTY_SET);
493 client.setIsSystemUser(false);
495 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
496 throw new Exception(msg);
501 client.setLoginId(userId);
502 client.setActiveYn(true);
503 client.setOrgUserId(userId);
505 roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
506 SortedSet<Role> roles = new TreeSet<>();
508 List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
509 List<FnApp> appList = new ArrayList<>();
511 List<CentralV2Role> roleList = new ArrayList<>();
513 List<FnRole> userRoles = new ArrayList<>();
515 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
516 FnRole role = new FnRole();
517 role.setId(roleInappForUser.getRoleId());
518 role.setRoleName(roleInappForUser.getRoleName());
523 List<FnRole> userAppRoles = new ArrayList<>();
524 for (FnRole role : userRoles) {
525 FnRole appRole = getAppRoles.stream()
526 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
528 FnRole epRole = new FnRole();
529 if (appRole != null) {
530 epRole.setId(appRole.getId());
531 epRole.setRoleName(appRole.getRoleName());
533 userAppRoles.add(epRole);
535 userRoles = new ArrayList<>(userAppRoles);
537 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
539 for (CentralV2Role epRole : roleList) {
540 Role role = new Role();
541 FnRole appRole = getAppRoles.stream()
542 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
543 if (appRole != null) {
544 role.setId(appRole.getAppRoleId());
545 role.setRoleName(epRole.getName());
546 role.setFnRoleFunctions(epRole.getRoleFunctions());
550 client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
552 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
553 logger.debug(EELFLoggerDelegate.debugLogger,
554 "about to post a client to remote application, users json = " + userInString);
555 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
558 private FnRole roleToFnRole(Role role) {
559 return FnRole.builder()
561 .roleName(role.getRoleName())
562 .activeYn(role.getActiveYn())
563 .priority(role.getPriority())
564 .fnRoleFunctions(role.getFnRoleFunctions())
565 .childRoles(role.getChildRoles())
566 .parentRoles(role.getParentRoles())
570 private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
571 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
572 throws JsonProcessingException, HTTPException {
573 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
574 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
575 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
577 externalApp = appsCacheService.getApp(appId);
578 String appBaseUri = null;
579 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
580 if (externalApp != null) {
581 appBaseUri = externalApp.getAppRestEndpoint();
583 if (appBaseUri != null && appBaseUri.endsWith("/api")) {
584 for (EcompRole eprole : updatedUserRolesinRemote) {
585 RemoteRoleV1 role = new RemoteRoleV1();
586 role.setId(eprole.getId());
587 role.setName(eprole.getName());
588 updatedUserRolesinRemoteV1.add(role);
590 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
592 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
593 String.format("/user/%s/roles", userId));
594 return updateUserRolesInEcomp;
597 private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
598 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
599 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
600 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
604 private void createNewUserOnRemoteApp(String userId, FnApp app,
605 ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
608 FnUser client = fnUserService.loadUserByUsername(userId);
610 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
612 if (client == null) {
613 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
614 logger.error(EELFLoggerDelegate.errorLogger, msg);
615 throw new Exception(msg);
618 client.setLoginId(userId);
619 client.setActiveYn(true);
622 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
623 logger.debug(EELFLoggerDelegate.debugLogger,
624 "about to post new client to remote application, users json = " + userInString);
625 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
629 private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
630 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
631 if (roleInAppForUser.getIsApplied()) {
638 private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
639 Set<EcompRole> existingUserRoles = new TreeSet<>();
640 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
641 if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
642 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
643 EcompRole ecompRole = new EcompRole();
644 ecompRole.setId(roleInAppForUser.getRoleId());
645 ecompRole.setName(roleInAppForUser.getRoleName());
646 existingUserRoles.add(ecompRole);
649 return existingUserRoles;
652 private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
653 List<EpUserRolesRequest> epRequestIdVal;
655 epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
656 if (epRequestIdVal.size() > 0) {
657 EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
658 epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
659 epAppRolesRequestData.setRequestStatus("O");
660 epAppRolesRequestData.setUserId(user);
661 epUserRolesRequestService.saveOne(epAppRolesRequestData);
662 List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
663 .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
664 if (epUserAppRolesDetailList.size() > 0) {
665 for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
666 epRequestUpdateList.setRequestType("O");
667 epRequestUpdateList.setReqId(epAppRolesRequestData);
668 epRequestUpdateList.setReqId(epAppRolesRequestData);
669 epUserRolesRequestDetService.saveOne(epRequestUpdateList);
671 logger.debug(EELFLoggerDelegate.debugLogger,
672 "User App roles request from User Page is overridden");
676 } catch (Exception e) {
677 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
681 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
682 return constructUsersEcompRoles(roleInAppForUserList);
685 private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
686 Set<EcompRole> existingUserRoles = new TreeSet<>();
687 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
688 if (roleInAppForUser.getIsApplied()) {
689 EcompRole ecompRole = new EcompRole();
690 ecompRole.setId(roleInAppForUser.getRoleId());
691 ecompRole.setName(roleInAppForUser.getRoleName());
692 existingUserRoles.add(ecompRole);
695 return existingUserRoles;
698 public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
699 Set<EcompRole> userRolesInRemoteApp) {
700 RolesInAppForUser result;
701 result = new RolesInAppForUser();
702 result.setAppId(appId);
703 result.setOrgUserId(userId);
705 for (EcompRole role : userRolesInRemoteApp) {
706 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
707 roleInAppForUser.setRoleId(role.getId());
708 roleInAppForUser.setRoleName(role.getName());
709 roleInAppForUser.setIsApplied(true);
710 result.getRoles().add(roleInAppForUser);
715 private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
716 boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
717 boolean isLoggedInUserRoleAdminofApp) throws Exception {
719 List<FnUser> userInfo = checkIfUserExists(orgUserId);
720 if (userInfo.isEmpty()) {
721 createLocalUserIfNecessary(orgUserId, isSystemUser);
724 if (EPCommonSystemProperties
725 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
729 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
733 ObjectMapper mapper = new ObjectMapper();
734 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
735 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
736 ResponseEntity<String> getResponse = externalAccessRolesService
737 .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
739 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
740 String res = getResponse.getBody();
742 JSONArray extRoles = null;
743 if (!res.equals("{}")) {
744 jsonObj = new JSONObject(res);
745 extRoles = jsonObj.getJSONArray("role");
747 ExternalAccessUserRoleDetail userRoleDetail;
748 if (extRoles != null) {
749 for (int i = 0; i < extRoles.length(); i++) {
750 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
751 && !extRoles.getJSONObject(i).getString("name")
752 .equals(app.getAuthNamespace() + ".admin")
753 && !extRoles.getJSONObject(i).getString("name")
754 .equals(app.getAuthNamespace() + ".owner")) {
755 if (extRoles.getJSONObject(i).has("description")) {
756 ExternalRoleDescription desc = new ExternalRoleDescription(
757 extRoles.getJSONObject(i).getString("description"));
758 userRoleDetail = new ExternalAccessUserRoleDetail(
759 extRoles.getJSONObject(i).getString("name"), desc);
760 userRoleDetailList.add(userRoleDetail);
762 userRoleDetail = new ExternalAccessUserRoleDetail(
763 extRoles.getJSONObject(i).getString("name"), null);
764 userRoleDetailList.add(userRoleDetail);
771 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
772 userRoleDetailList, app);
774 List<EcompUserAppRoles> userAppList;
775 // If request coming from portal not from external role approval system then we have to check if user already
776 // have account admin or system admin as GUI will not send these roles
777 if (!isPortalRequest) {
778 FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
779 userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
780 if (!roleInAppUser.isEmpty()) {
781 for (EcompUserAppRoles userApp : userAppList) {
782 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
783 || userApp.getRoleId()
784 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
785 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
786 addSpecialRole.setIsApplied(true);
787 addSpecialRole.setRoleId(userApp.getRoleId());
788 addSpecialRole.setRoleName(userApp.getRoleName());
789 roleInAppUser.add(addSpecialRole);
794 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
795 .collect(Collectors.toList());
796 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
797 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
798 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
799 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
800 "_"), roleInAppUserNew);
802 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
803 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
804 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
807 if (isLoggedInUserRoleAdminofApp) {
808 if (deletedRolesByApprover.size() > 0) {
809 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
810 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
811 for (EcompRole role : deletedRolesByApprover) {
812 if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
813 .equals(role.getName())) {
814 newUpdatedRoles.add(userRole);
818 if (newUpdatedRoles.size() > 0) {
819 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
821 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
822 currentUserRolesToUpdate = new HashMap<>();
827 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
828 currentUserRolesToUpdate = new HashMap<>();
833 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
834 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
835 if (!(currentUserRolesToUpdate
836 .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
837 HttpEntity<String> entity = new HttpEntity<>(headers);
838 logger.debug(EELFLoggerDelegate.debugLogger,
839 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
841 ResponseEntity<String> deleteResponse = template.exchange(
843 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
844 + "userRole/" + name + "/" + userRole.getName(),
845 HttpMethod.DELETE, entity, String.class);
846 logger.debug(EELFLoggerDelegate.debugLogger,
847 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
848 userRole.getName(), deleteResponse.getBody());
851 // Check if user roles does not exists in External Central Auth System add them all
852 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
853 if (!(currentUserRolesInExternalSystem
854 .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
855 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
857 ExternalAccessUser extUser = new ExternalAccessUser(name,
858 app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
859 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
861 String formattedUserRole = mapper.writeValueAsString(extUser);
862 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
863 logger.debug(EELFLoggerDelegate.debugLogger,
864 "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
865 name, addUserRole.getRoleName());
866 ResponseEntity<String> addResponse = template
867 .exchange(SystemProperties
868 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
869 + "userRole", HttpMethod.POST, entity, String.class);
870 logger.debug(EELFLoggerDelegate.debugLogger,
871 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
872 addResponse.getBody(), addUserRole.getRoleName());
873 if (addResponse.getStatusCode().value() != 201
874 && addResponse.getStatusCode().value() != 404) {
875 logger.debug(EELFLoggerDelegate.debugLogger,
876 "Finished POST operation in external system but unable to save user role",
877 addResponse.getBody(),
878 addUserRole.getRoleName());
879 throw new Exception(addResponse.getBody());
883 } catch (HttpClientErrorException e) {
884 logger.error(EELFLoggerDelegate.errorLogger,
885 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
887 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
888 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
890 throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
891 "Please enter the valid systemUser");
893 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
894 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
895 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
897 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
899 } catch (Exception e) {
900 logger.error(EELFLoggerDelegate.errorLogger,
901 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
903 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
908 private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
909 List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
910 Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
911 //Add Account Admin role for partner app to prevent conflict
912 if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
913 FnRole role = new FnRole();
914 role.setRoleName(PortalConstants.ADMIN_ROLE
915 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
916 epRoleList.put(role.getRoleName(), role);
918 userRoleDetailList.removeIf(
919 userRoleDetail -> !epRoleList
920 .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
921 return userRoleDetailList;
924 private List<FnUser> checkIfUserExists(String userParams) {
925 return fnUserService.getUserWithOrgUserId(userParams);
929 private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
930 if (StringUtils.isEmpty(userId)) {
931 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
935 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
936 if (userList.size() == 0) {
939 client = fnUserService.loadUserByUsername(userId);
941 client = new FnUser();
942 client.setOrgUserId(userId);
943 client.setIsSystemUser(true);
944 client.setFirstName(userId.substring(0, userId.indexOf("@")));
946 if (client == null) {
947 String msg = "createLocalUserIfNecessary: cannot create user " + userId
948 + ", because not found in phonebook";
949 logger.error(EELFLoggerDelegate.errorLogger, msg);
951 client.setLoginId(userId);
952 client.setActiveYn(true);
954 fnUserService.saveFnUser(client);
956 } catch (Exception e) {
957 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
962 private FnUser checkIfRemoteUserExits(String userId, FnApp app,
963 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
964 FnUser checkRemoteUser = null;
966 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
967 } catch (HTTPException e) {
968 // Some apps are returning 400 if user is not found.
969 if (e.getResponseCode() == 400) {
970 logger.debug(EELFLoggerDelegate.debugLogger,
971 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
973 } else if (e.getResponseCode() == 404) {
974 logger.debug(EELFLoggerDelegate.debugLogger,
975 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
978 // Other response code, let it come thru.
982 return checkRemoteUser;
985 private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
986 throws HTTPException {
987 if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
988 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
989 if (userList != null && !userList.isEmpty()) {
990 return userList.get(0);
995 return getUser(userId, app, applicationsRestClientService);
998 private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
999 boolean externalSystemRequest, String reqType, boolean isSystemUser,
1000 Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
1001 boolean result = false;
1002 String userId = rolesInAppForUser.getOrgUserId();
1003 Long appId = rolesInAppForUser.getAppId();
1004 synchronized (syncRests) {
1005 createLocalUserIfNecessary(userId, isSystemUser);
1007 EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1009 i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1010 RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1011 EcompRole role = new EcompRole();
1012 role.setId(roleInAppForUser.getRoleId());
1013 role.setName(roleInAppForUser.getRoleName());
1014 userAppRoles[i] = role;
1017 EcompRole[] applicationRoles = null;
1019 if (isLoggedInUserRoleAdminOfApp) {
1020 List<EcompRole> roles = Arrays.stream(userAppRoles)
1021 .collect(Collectors.toList());
1022 List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1023 roles.addAll(roles1);
1024 applicationRoles = roles.toArray(new EcompRole[0]);
1027 syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1028 reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1030 } catch (Exception e) {
1031 logger.error(EELFLoggerDelegate.errorLogger,
1032 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1034 if ("DELETE".equals(reqType)) {
1035 throw new Exception(e.getMessage());
1042 private void syncUserRoles(String userId, Long appId,
1043 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1044 EcompRole[] appRoles) throws Exception {
1046 Transaction transaction = null;
1048 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1049 List<FnRole> roleInfo = externalAccessRolesService
1050 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1051 FnRole adminRole = new FnRole();
1052 if (roleInfo.size() > 0) {
1053 adminRole = roleInfo.get(0);
1054 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1057 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1058 if (userList.size() > 0) {
1059 FnUser client = userList.get(0);
1060 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1061 List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1063 .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1064 .setParameter("appId", appId)
1065 .setParameter("userId", client.getId())
1068 if ("DELETE".equals(reqType)) {
1069 for (FnUserRole userAppRoleList : userRoles) {
1070 List<FnRole> rolesList =
1071 (!userAppRoleList.getRoleId().getRoleName()
1072 .equals(adminRole.getRoleName()))
1073 ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1074 (userAppRoleList.getRoleId().getRoleName(), appId)
1075 : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1076 if (!rolesList.isEmpty()) {
1077 checkIfRoleInactive(rolesList.get(0));
1082 if (appRoles != null) {
1083 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1084 List<FnUserRole> finalUserRolesList = new ArrayList<>();
1085 if (checkIfUserisRoleAdmin) {
1086 for (EcompRole role : appRolesList) {
1087 for (FnUserRole userAppRoleList : userRoles) {
1088 if (userAppRoleList.getRoleId().getRoleName()
1089 .equals(role.getName())) {
1090 finalUserRolesList.add(userAppRoleList);
1095 userRoles = new ArrayList<>(finalUserRolesList);
1099 for (FnUserRole userRole : userRoles) {
1100 if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1101 && !PortalConstants.SYS_ADMIN_ROLE_ID
1102 .equals(userRole.getRoleId().getId())
1103 && !extRequestValue) {
1104 syncUserRolesExtension(userRole, appId,
1105 newUserAppRolesMap);
1106 } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1107 || "DELETE".equals(reqType))) {
1108 syncUserRolesExtension(userRole, appId,
1109 newUserAppRolesMap);
1110 } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1111 .equals(userRole.getRoleId().getId())) {
1112 syncUserRolesExtension(userRole, appId,
1113 newUserAppRolesMap);
1117 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1118 if (newRolesToAdd.size() > 0) {
1119 FnApp app = fnAppService.getById(appId);
1121 HashMap<Long, FnRole> rolesMap = new HashMap<>();
1122 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1123 String appIdValue = "";
1124 if (!extRequestValue) {
1125 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1127 @SuppressWarnings("unchecked")
1128 List<FnRole> roles = entityManager
1130 "from " + FnRole.class.getName() + " where appId is null "
1131 + appIdValue).getResultList();
1132 for (FnRole role : roles) {
1134 rolesMap.put(role.getId(), role);
1136 } else { // remote app
1137 @SuppressWarnings("unchecked")
1138 List<FnRole> roles = entityManager
1139 .createQuery("from EPRole where appId=:appId")
1140 .setParameter("appId", appId)
1142 for (FnRole role : roles) {
1143 if (!extRequestValue && app.getAuthCentral()) {
1144 rolesMap.put(role.getId(), role);
1146 rolesMap.put(role.getAppRoleId(), role);
1152 for (EcompRole userRole : newRolesToAdd) {
1153 FnUserRole userApp = new FnUserRole();
1154 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1155 .equals(adminRole.getRoleName())) {
1156 role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1157 userApp.setRoleId(role);
1158 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1159 && !extRequestValue) {
1161 } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1162 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1165 userApp.setRoleId(rolesMap.get(userRole.getId()));
1168 userApp.setUserId(client);
1169 userApp.setFnAppId(app);
1170 fnUserRoleService.saveOne(userApp);
1173 if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1175 * for local app -- hack - always make sure fn_role
1176 * table's app_id is null and not 1 for primary app in
1177 * this case being onap portal app; reason: hibernate
1178 * is rightly setting this to 1 while persisting to
1179 * fn_role as per the mapping but SDK role management
1180 * code expects the app_id to be null as there is no
1181 * concept of App_id in SDK
1183 Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1184 query.executeUpdate();
1188 transaction.commit();
1189 } catch (Exception e) {
1190 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1191 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1192 EcompPortalUtils.rollbackTransaction(transaction,
1193 "Exception occurred in syncUserRoles, Details: " + e.toString());
1194 if ("DELETE".equals(reqType)) {
1195 throw new SyncUserRolesException(e.getMessage());
1200 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1201 HashMap<Long, EcompRole> result = new HashMap<>();
1202 if (ecompRoles != null) {
1203 for (EcompRole ecompRole : ecompRoles) {
1204 if (ecompRole.getId() != null) {
1205 result.put(ecompRole.getId(), ecompRole);
1212 private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1213 HashMap<Long, EcompRole> newUserAppRolesMap) {
1216 if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1217 userAppRoleId = userRole.getRoleId().getId();
1218 } else { // remote app
1219 userAppRoleId = userRole.getId();
1222 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1223 fnUserRoleService.deleteById(userRole.getId());
1225 newUserAppRolesMap.remove(userAppRoleId);
1229 private Role fnRoleToRole(final FnRole role) {
1230 return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null, role.getActiveYn(),
1231 role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1234 @SuppressWarnings("unchecked")
1235 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue, Long userId) {
1236 List<RoleInAppForUser> rolesInAppForUser = null;
1237 FnApp app = fnAppService.getById(appId);
1238 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1240 // for onap portal app, no need to make a remote call
1241 List<Role> roleList = new ArrayList<>();
1242 if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1243 if (app.getAuthCentral()) {
1244 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1245 for (CentralV2Role cenRole : cenRoleList) {
1246 Role role = new Role();
1247 role.setActiveYn(cenRole.isActive());
1248 role.setId(cenRole.getId());
1249 role.setRoleName(cenRole.getName());
1250 role.setPriority(cenRole.getPriority());
1254 Optional<FnUser> user = fnUserService.getUser(userId);
1255 if (user.isPresent()) {
1256 roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole).collect(Collectors.toList());
1259 List<Role> activeRoleList = new ArrayList<>();
1260 for (Role role : roleList) {
1261 if (role.getActiveYn()) {
1262 if (role.getId() != 1) { // prevent portal admin from being added
1263 activeRoleList.add(role);
1264 } else if (extRequestValue) {
1265 activeRoleList.add(role);
1270 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1271 // If localUser does not exists return roles
1272 Set<FnRole> roleSet = null;
1273 FnRole[] roleSetList = null;
1274 if (localUser != null) {
1275 roleSet = localUser.getAppEPRoles(app);
1276 roleSetList = roleSet.toArray(new FnRole[0]);
1278 rolesInAppForUser = fnUserRoleService
1279 .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1280 return rolesInAppForUser;
1283 EcompRole[] appRoles = null;
1284 boolean checkIfUserIsApplicationAccAdmin = false;
1285 List<EcompRole> roles = new ArrayList<>();
1286 if (app.getAuthCentral()) {
1287 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1288 FnApp application = fnAppService.getById(appId);
1289 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1292 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1293 for (FnRole role : applicationRoles) {
1294 List<EpAppFunction> cenRoleFuncList = epAppFunctionService.getAppRoleFunctionList(role.getId(), app.getId());
1295 for (EpAppFunction roleFunc : cenRoleFuncList) {
1297 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1298 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1299 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1300 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1301 String name = roleFunc.getFunctionName();
1303 FnFunction function = new FnFunction();
1304 function.setAction(action);
1305 function.setType(type);
1306 function.setCode(functionCode);
1307 function.setName(name);
1308 role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1311 roleSetWithFunctioncds.add(role);
1316 for (FnRole role1 : roleSetWithFunctioncds) {
1317 EcompRole ecompRole = new EcompRole();
1318 ecompRole.setId(role1.getId());
1319 ecompRole.setName(role1.getRoleName());
1320 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1321 roles.add(ecompRole);
1324 if (checkIfUserIsApplicationAccAdmin) {
1325 appRoles = roles.toArray(new EcompRole[roles.size()]);
1326 logger.debug(EELFLoggerDelegate.debugLogger,
1327 "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1328 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1329 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1330 List<String> roleAdminAppRolesNames = new ArrayList<>();
1332 "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1333 + " where fu.role_id = ep.role_id"
1334 + " and fu.app_id = ep.app_id"
1335 + " and fu.user_id = :userId"
1336 + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1337 + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1340 + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id"
1341 + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1342 List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1343 .setParameter("userId", userId)
1345 List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1346 .collect(Collectors.toList());
1348 List<EcompRole> userapproverRolesList = new ArrayList<>();
1349 for (String str : getUserApproverRoles) {
1350 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1351 if (epRole != null) {
1352 userapproverRolesList.add(epRole);
1355 for (EcompRole role : userapproverRolesList) {
1357 List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1358 boolean checkIfFunctionsExits = roleFunList.stream()
1359 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1360 if (checkIfFunctionsExits) {
1361 roleAdminAppRoles.add(role);
1362 List<RoleFunction> filteredList = roleFunList.stream()
1363 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1364 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1365 .collect(Collectors.toList()));
1368 for (String name : roleAdminAppRolesNames) {
1369 roles.stream().filter(x -> name.equals(x.getName())).findAny().ifPresent(roleAdminAppRoles::add);
1372 appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1376 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1378 // Test this error case, for generating an internal ONAP Portal
1380 // EcompRole[] appRoles = null;
1381 // If there is an exception in the rest client api, then null will
1383 if (appRoles != null) {
1384 if (!app.getAuthCentral()) {
1385 syncAppRoles(appId, appRoles);
1387 EcompRole[] userAppRoles = null;
1390 if (app.getAuthCentral()) {
1391 List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1392 List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1393 .createNamedQuery("EPUserAppCurrentRoles")
1394 .setParameter("appId", app.getId())
1395 .setParameter("userId", actualUser.get(0).getId())
1397 List<EcompRole> setUserRoles = new ArrayList<>();
1398 for (EPUserAppCurrentRoles role : userAppsRolesList) {
1399 logger.debug(EELFLoggerDelegate.debugLogger,
1400 "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1401 EcompRole ecompRole = new EcompRole();
1402 ecompRole.setId(role.getRoleId());
1403 ecompRole.setName(role.getRoleName());
1404 setUserRoles.add(ecompRole);
1407 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1408 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1410 if (!checkIfUserisAccAdmin) {
1411 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1412 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1414 List<String> roleNames = new ArrayList<>();
1415 for (EcompRole role : setUserRoles) {
1416 EcompRole epRole = appRolesList.stream()
1417 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1418 List<RoleFunction> roleFunList = new ArrayList<>();
1420 if (epRole != null) {
1421 if (epRole.getRoleFunctions().size() > 0) {
1422 roleFunList.addAll(epRole.getRoleFunctions());
1424 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1425 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1426 if (checkIfFunctionsExits) {
1427 finalUserAppRolesList.add(role);
1428 List<RoleFunction> filteredList = roleFunList.stream()
1429 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1430 .collect(Collectors.toList());
1431 roleNames = filteredList.stream().map(RoleFunction::getCode)
1432 .collect(Collectors.toList());
1434 roleNames.add(epRole.getName());
1437 for (String name : roleNames) {
1438 EcompRole ecompRole = appRolesList.stream()
1439 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1440 if (ecompRole != null) {
1441 finalUserAppRolesList.add(ecompRole);
1445 for (String name : roleNames) {
1446 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1447 role -> role.getRoleName().equalsIgnoreCase(name));
1448 if (checkIfFunctionsExits) {
1449 appRolesList.stream().filter(x -> name.equals(x.getName()))
1450 .findAny().ifPresent(setUserRoles::add);
1453 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1456 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1457 String.format("/user/%s/roles", userId));
1459 } catch (HTTPException e) {
1460 // Some apps are returning 400 if user is not found.
1461 if (e.getResponseCode() == 400) {
1462 logger.debug(EELFLoggerDelegate.debugLogger,
1463 "getAppRolesForUser caught exception with response code 400; continuing", e);
1465 // Other response code, let it come thru.
1469 if (userAppRoles == null) {
1470 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1471 EcompPortalUtils.setExternalAppResponseCode(200);
1472 String message = String.format(
1473 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1474 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1475 + "Overriding to 200 until framework SDK returns a useful response.",
1476 Long.toString(appId), userId);
1477 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1481 HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1482 ArrayList<EcompRole> activeRoles = new ArrayList<>();
1483 if (userAppRoles != null) {
1484 for (EcompRole userAppRole : userAppRoles) {
1485 if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1486 EcompRole role = new EcompRole();
1487 role.setId(userAppRole.getId());
1488 role.setName(userAppRole.getName());
1489 activeRoles.add(role);
1493 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1495 boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1497 // If the remote application isn't down we MUST sync user
1498 // roles here in case we have this user here!
1499 syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null, checkIfUserisRoleAdmin,
1501 } catch (Exception e) {
1502 // TODO: we may need to check if user exists, maybe remote
1504 String message = String.format(
1505 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1506 Long.toString(appId));
1507 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1508 userAppRoles = new EcompRole[0];
1510 rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1512 } catch (Exception e) {
1513 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1514 Long.toString(appId));
1515 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1517 return rolesInAppForUser;
1520 private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1521 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1522 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1524 List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1526 List<FnRole> obsoleteRoles = new ArrayList<>();
1527 for (FnRole oldAppRole : currentAppRoles) {
1528 if (oldAppRole.getAppRoleId() != null) {
1530 role = newRolesMap.get(oldAppRole.getAppRoleId());
1532 if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1533 oldAppRole.setRoleName(role.getName());
1535 oldAppRole.setActiveYn(true);
1536 newRolesMap.remove(oldAppRole.getAppRoleId());
1538 obsoleteRoles.add(oldAppRole);
1541 obsoleteRoles.add(oldAppRole);
1544 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1545 if (obsoleteRoles.size() > 0) {
1546 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1547 for (FnRole role : obsoleteRoles) {
1548 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1549 Long roleId = role.getId();
1550 List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1552 logger.debug(EELFLoggerDelegate.debugLogger,
1553 "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1554 for (FnUserRole userRole : userRoles) {
1555 logger.debug(EELFLoggerDelegate.debugLogger,
1556 "syncAppRoles: about to delete userRole: " + userRole.toString());
1557 fnUserRoleService.deleteById(userRole.getId());
1558 logger.debug(EELFLoggerDelegate.debugLogger,
1559 "syncAppRoles: finished deleting userRole: " + userRole.toString());
1561 List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1562 int numMenuRoles = funcMenuRoles.size();
1563 logger.debug(EELFLoggerDelegate.debugLogger,
1564 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1565 for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1566 Long menuId = funcMenuRole.getMenuId().getMenuId();
1567 // If this is the only role for this menu item, then the
1568 // app and roles will be gone,
1569 // so must null out the url too, to be consistent
1570 List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService.retrieveByMenuId(menuId);
1571 int numMenuRoles2 = funcMenuRoles2.size();
1572 logger.debug(EELFLoggerDelegate.debugLogger,
1573 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1574 fnMenuFunctionalRolesService.delete(funcMenuRole);
1576 if (numMenuRoles2 == 1) {
1577 // If this is the only role for this menu item, then
1578 // the app and roles will be gone,
1579 // so must null out the url too, to be consistent
1580 logger.debug(EELFLoggerDelegate.debugLogger,
1581 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1582 List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1583 if (funcMenuItems.size() > 0) {
1584 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1585 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1586 funcMenuItem.setUrl("");
1590 boolean isPortalRequest = true;
1591 deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1592 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
1593 fnRoleService.delete(role);
1594 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1597 for (EcompRole role : newRolesToAdd) {
1598 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
1599 FnRole newRole = new FnRole();
1600 // Attention! All roles from remote application supposed to be
1602 newRole.setActiveYn(true);
1603 newRole.setRoleName(role.getName());
1604 newRole.setAppId(appId);
1605 newRole.setAppRoleId(role.getId());
1606 fnRoleService.saveOne(newRole);
1608 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1609 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1610 } catch (Exception e) {
1611 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1612 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1613 throw new Exception(e);
1617 private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1619 Session localSession = entityManager.unwrap(Session.class);
1623 // It should delete only when it portal's roleId
1624 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1625 // Delete from fn_role_function
1626 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1627 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1628 query = localSession.createSQLQuery(sql);
1629 query.executeUpdate();
1630 // Delete from fn_role_composite
1631 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1632 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1633 query = localSession.createSQLQuery(sql);
1634 query.executeUpdate();
1636 // Delete from ep_app_role_function
1637 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1638 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1639 query = localSession.createSQLQuery(sql);
1640 query.executeUpdate();
1641 // Delete from ep_role_notification
1642 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1643 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1644 query = localSession.createSQLQuery(sql);
1645 query.executeUpdate();
1646 // Delete from fn_user_pseudo_role
1647 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1648 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1649 query = localSession.createSQLQuery(sql);
1650 query.executeUpdate();
1651 // Delete form EP_WIDGET_CATALOG_ROLE
1652 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1653 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1654 query = localSession.createSQLQuery(sql);
1655 query.executeUpdate();
1656 // Delete form EP_WIDGET_CATALOG_ROLE
1657 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1658 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1659 query = localSession.createSQLQuery(sql);
1660 query.executeUpdate();
1661 if (!isPortalRequest) {
1662 // Delete form fn_menu_functional_roles
1663 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1664 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1665 query = localSession.createSQLQuery(sql);
1666 query.executeUpdate();
1668 } catch (Exception e) {
1669 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1670 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1674 private void checkIfRoleInactive(FnRole epRole) throws Exception {
1675 if (!epRole.getActiveYn()) {
1676 throw new Exception(epRole.getRoleName() + " role is unavailable");
1680 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1681 boolean result = false;
1682 // No changes if no new roles list or no userId.
1683 if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1684 && newAppsListWithAdminRoles.getAppsRoles() != null) {
1685 synchronized (syncRests) {
1686 List<FnApp> apps = fnAppService.getAppsFullList();
1687 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1688 for (FnApp app : apps) {
1689 enabledApps.put(app.getId(), app);
1691 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1692 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1693 // user Admin role may be added only for enabled apps
1694 if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1695 newAppsWhereUserIsAdmin.add(adminRole);
1699 boolean createNewUser = false;
1700 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1701 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1702 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1703 if (localUserList.size() > 0) {
1704 FnUser tmpUser = localUserList.get(0);
1705 oldAppsWhereUserIsAdmin = fnUserRoleService.retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1706 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1709 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1710 // we create new user only if he has Admin Role for any App
1711 createNewUser = true;
1713 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1714 oldAppsWhereUserIsAdmin);
1722 public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1723 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1724 List<FnUserRole> oldAppsWhereUserIsAdmin) {
1725 if (user != null || createNewUser) {
1726 if (createNewUser) {
1727 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1729 user.setActiveYn(true);
1732 for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1733 // user Admin role may be deleted only for enabled
1735 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1736 fnUserRoleService.saveOne(oldUserApp);
1739 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1740 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1741 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1742 FnUserRole newUserApp = new FnUserRole();
1743 newUserApp.setUserId(user);
1744 newUserApp.setFnAppId(app);
1745 newUserApp.setRoleId(role);
1746 fnUserRoleService.saveOne(newUserApp);
1748 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1749 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1757 public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1758 boolean result = false;
1760 // Reset All admin role for centralized applications
1761 List<FnApp> appList = fnAppService.getCentralizedApps();
1762 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1763 for (FnApp app : appList) {
1765 if (EPCommonSystemProperties
1766 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1767 name = user.getOrgUserId() + SystemProperties
1768 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1770 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1771 HttpEntity<String> entity = new HttpEntity<>(headers);
1772 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1774 ResponseEntity<String> getResponse = template
1775 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1776 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1778 if (getResponse.getBody().equals("{}")) {
1779 String addDesc = "{\"name\":\"" + extRole + "\"}";
1780 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1782 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1784 HttpMethod.POST, roleEntity, String.class);
1787 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1789 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1790 + "userRole/" + name + "/" + extRole,
1791 HttpMethod.DELETE, deleteUserRole, String.class);
1792 } catch (Exception e) {
1793 logger.error(EELFLoggerDelegate.errorLogger,
1794 " Role not found for this user may be it gets deleted before", e);
1797 } catch (Exception e) {
1798 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1799 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1800 app.getAuthNamespace(), e.getMessage());
1802 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1803 app.getAuthNamespace(), e);
1807 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1808 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1810 if (app.getAuthCentral()) {
1811 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1812 HttpEntity<String> entity = new HttpEntity<>(headers);
1814 if (EPCommonSystemProperties
1815 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1816 name = user.getOrgUserId() + SystemProperties
1817 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1819 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1820 ResponseEntity<String> getUserRolesResponse = template.exchange(
1821 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1822 + "userRoles/user/" + name,
1823 HttpMethod.GET, entity, String.class);
1824 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1825 if (!getUserRolesResponse.getBody().equals("{}")) {
1826 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1827 JSONArray extRoles = jsonObj.getJSONArray("userRole");
1828 final Map<String, JSONObject> extUserRoles = new HashMap<>();
1829 for (int i = 0; i < extRoles.length(); i++) {
1830 String userRole = extRoles.getJSONObject(i).getString("role");
1831 if (userRole.startsWith(app.getAuthNamespace() + ".")
1832 && !userRole.equals(app.getAuthNamespace() + ".admin")
1833 && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1835 extUserRoles.put(userRole, extRoles.getJSONObject(i));
1838 if (!extUserRoles.containsKey(extRole)) {
1839 // Assign with new apps user admin
1841 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1842 // Assign user role for an application in external access system
1843 ObjectMapper addUserRoleMapper = new ObjectMapper();
1844 String userRole = addUserRoleMapper.writeValueAsString(extUser);
1845 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1847 SystemProperties.getProperty(
1848 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1849 HttpMethod.POST, addUserRole, String.class);
1850 } catch (Exception e) {
1851 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1858 } catch (Exception e) {
1859 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1860 logger.debug(EELFLoggerDelegate.errorLogger,
1861 "Application name space not found in External system for app {} due to bad rquest name space ",
1862 app.getAuthNamespace(), e.getMessage());
1864 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1865 app.getAuthNamespace(), e);
1870 } catch (Exception e) {
1872 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);