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.RoleFunctionException;
96 import org.onap.portal.exception.SyncUserRolesException;
97 import org.onap.portal.logging.format.EPAppMessagesEnum;
98 import org.onap.portal.logging.logic.EPLogUtil;
99 import org.onap.portal.service.appFunction.EpAppFunctionService;
100 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
101 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
102 import org.onap.portal.service.app.FnAppService;
103 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
104 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
105 import org.onap.portal.service.role.FnRoleService;
106 import org.onap.portal.service.userRole.FnUserRoleService;
107 import org.onap.portal.service.user.FnUserService;
108 import org.onap.portal.utils.EPCommonSystemProperties;
109 import org.onap.portal.utils.EPUserUtils;
110 import org.onap.portal.utils.EcompPortalUtils;
111 import org.onap.portal.utils.PortalConstants;
112 import org.onap.portalsdk.core.domain.RoleFunction;
113 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
114 import org.onap.portalsdk.core.restful.domain.EcompRole;
115 import org.onap.portalsdk.core.util.SystemProperties;
116 import org.springframework.beans.factory.annotation.Autowired;
117 import org.springframework.http.HttpEntity;
118 import org.springframework.http.HttpHeaders;
119 import org.springframework.http.HttpMethod;
120 import org.springframework.http.HttpStatus;
121 import org.springframework.http.ResponseEntity;
122 import org.springframework.stereotype.Service;
123 import org.springframework.transaction.annotation.Transactional;
124 import org.springframework.web.client.HttpClientErrorException;
125 import org.springframework.web.client.RestTemplate;
129 public class AdminRolesService {
131 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
132 private static final Object syncRests = new Object();
133 private final RestTemplate template = new RestTemplate();
135 private Long SYS_ADMIN_ROLE_ID = 38L;
136 private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
137 private final Long ECOMP_APP_ID = 1L;
138 private final String ADMIN_ACCOUNT = "Is account admin for user {}";
140 private final AppsCacheService appsCacheService;
141 private final EntityManager entityManager;
142 private final FnUserService fnUserService;
143 private final FnRoleService fnRoleService;
144 private final FnAppService fnAppService;
145 private final FnMenuFunctionalService fnMenuFunctionalService;
146 private final FnUserRoleService fnUserRoleService;
147 private final EpAppFunctionService epAppFunctionService;
148 private final EcompUserAppRolesService ecompUserAppRolesService;
149 private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
150 private final ApplicationsRestClientService applicationsRestClientService;
151 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
152 private final ExternalAccessRolesService externalAccessRolesService;
153 private final EpUserRolesRequestService epUserRolesRequestService;
156 public AdminRolesService(AppsCacheService appsCacheService,
157 final EntityManager entityManager,
158 final FnUserService fnUserService, FnRoleService fnRoleService,
159 FnAppService fnAppService,
160 FnMenuFunctionalService fnMenuFunctionalService,
161 final FnUserRoleService fnUserRoleService,
162 EpAppFunctionService epAppFunctionService,
163 EcompUserAppRolesService ecompUserAppRolesService,
164 FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
165 ApplicationsRestClientService applicationsRestClientService,
166 EpUserRolesRequestDetService epUserRolesRequestDetService,
167 ExternalAccessRolesService externalAccessRolesService,
168 EpUserRolesRequestService epUserRolesRequestService) {
169 this.appsCacheService = appsCacheService;
170 this.entityManager = entityManager;
171 this.fnUserService = fnUserService;
172 this.fnRoleService = fnRoleService;
173 this.fnAppService = fnAppService;
174 this.fnMenuFunctionalService = fnMenuFunctionalService;
175 this.fnUserRoleService = fnUserRoleService;
176 this.epAppFunctionService = epAppFunctionService;
177 this.ecompUserAppRolesService = ecompUserAppRolesService;
178 this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
179 this.applicationsRestClientService = applicationsRestClientService;
180 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
181 this.externalAccessRolesService = externalAccessRolesService;
182 this.epUserRolesRequestService = epUserRolesRequestService;
185 public boolean isSuperAdmin(final String loginId) {
186 boolean isSuperAdmin;
188 isSuperAdmin = fnUserRoleService
189 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
190 } catch (Exception e) {
191 logger.error("isSuperAdmin exception: " + e.toString());
194 logger.info("isSuperAdmin " + isSuperAdmin);
198 public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
200 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
201 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
202 logger.debug(EELFLoggerDelegate.debugLogger,
203 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
204 orgUserId, userAdminApps.size());
206 for (FnUserRole userApp : userApps) {
207 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
208 userAdminApps.size() > 1)) {
209 logger.debug(EELFLoggerDelegate.debugLogger,
210 "Is account admin for userAdminApps() - for user {}, found Id {}",
211 orgUserId, userApp.getRoleId().getId());
215 } catch (Exception e) {
216 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
217 logger.error(EELFLoggerDelegate.errorLogger,
218 "Exception occurred while executing isAccountAdmin operation",
224 public boolean isUser(final long userId) {
226 FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
227 if (currentUser != null && currentUser.getId() != null) {
228 for (FnUserRole userApp : currentUser.getUserApps()) {
229 if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
230 FnRole role = userApp.getRoleId();
231 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
232 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
233 if (role.getActiveYn()) {
240 } catch (Exception e) {
241 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
242 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
248 public boolean isRoleAdmin(Long userId) {
250 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
251 List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
252 logger.debug(EELFLoggerDelegate.debugLogger,
253 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
254 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
255 Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
256 Set<String> roleFunSet;
257 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
258 .collect(Collectors.toSet());
259 if (!roleFunSet.isEmpty()) {
260 for (String roleFunction : roleFunSet) {
261 String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
262 getRoleFuncListOfPortalSet1.add(type);
266 boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
267 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
268 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
269 checkIfFunctionsExits);
271 return checkIfFunctionsExits;
273 } catch (Exception e) {
274 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
275 logger.error(EELFLoggerDelegate.errorLogger,
276 "Exception occurred while executing isRoleAdmin operation",
282 private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
283 boolean isApplicationAccountAdmin = false;
285 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
286 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
287 if (!userAdminApps.isEmpty()) {
288 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
289 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
292 } catch (Exception e) {
293 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
294 logger.error(EELFLoggerDelegate.errorLogger,
295 "Exception occurred while executing isAccountAdminOfApplication operation", e);
297 logger.debug(EELFLoggerDelegate.debugLogger,
298 "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
300 return isApplicationAccountAdmin;
304 private List<Integer> getAdminAppsForTheUser(final Long userId) {
305 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)";
306 return entityManager.createQuery(query, Integer.class)
307 .setParameter("userId", userId).getResultList();
310 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
311 AppWithRolesForUser newAppRolesForUser) {
312 boolean result = false;
313 boolean epRequestValue = false;
315 String reqMessage = "";
316 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
317 userId = newAppRolesForUser.getOrgUserId().trim();
319 Long appId = newAppRolesForUser.getAppId();
320 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
322 if (userId.length() > 0) {
323 ObjectMapper mapper = new ObjectMapper();
324 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
327 FnApp app = fnAppService.getById(appId);
329 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
331 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
333 boolean checkIfUserIsOnlyRoleAdmin =
334 isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
335 if (checkIfUserIsOnlyRoleAdmin) {
336 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
337 if (!roleInAppForUser.getIsApplied()) {
338 EcompRole ecompRole = new EcompRole();
339 ecompRole.setId(roleInAppForUser.getRoleId());
340 ecompRole.setName(roleInAppForUser.getRoleName());
341 rolesGotDeletedFromApprover.add(ecompRole);
346 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
348 boolean systemUser = newAppRolesForUser.isSystemUser();
350 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
353 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
354 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
355 userRolesInLocalApp);
356 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
357 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
358 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
359 // Apply changes in external Access system
361 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
363 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
365 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
367 systemUser, rolesGotDeletedByApprover, false);
369 } else if (!app.getAuthCentral() && systemUser) {
370 throw new Exception("For non-centralized application we cannot add systemUser");
371 } else { // if centralized app
372 if (app.getAuthCentral()) {
373 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
374 pushRemoteUser(roleInAppForUserList, userId, app, mapper,
375 applicationsRestClientService, false);
378 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
379 roleInAppForUserList);
380 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
382 userRolesInLocalApp);
383 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
384 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
386 // Apply changes in external Access system
387 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
389 epRequestValue, false, rolesGotDeletedFromApprover,
390 checkIfUserIsOnlyRoleAdmin);
392 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
393 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
394 checkIfUserIsOnlyRoleAdmin);
396 // In case if portal is not centralized then follow existing approach
397 else if (!app.getAuthCentral() && app.getId()
398 .equals(PortalConstants.PORTAL_APP_ID)) {
399 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
400 roleInAppForUserList);
401 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
403 userRolesInLocalApp);
404 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
405 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
406 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
407 } else {// remote app
408 FnUser remoteAppUser;
409 if (!app.getAuthCentral() && !app.getId()
410 .equals(PortalConstants.PORTAL_APP_ID)) {
412 remoteAppUser = checkIfRemoteUserExits(userId, app,
413 applicationsRestClientService);
415 if (remoteAppUser == null) {
416 addRemoteUser(roleInAppForUserList, userId, app,
417 mapper, applicationsRestClientService);
419 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
420 roleInAppForUserList, mapper,
421 applicationsRestClientService, appId, userId);
422 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
424 userRolesInRemoteApp);
425 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
426 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
427 epRequestValue, null, false, rolesGotDeletedByApprover, false);
429 // If no roles remain, request app to set user inactive.
430 if (userRolesInRemoteApp.size() == 0) {
431 logger.debug(EELFLoggerDelegate.debugLogger,
432 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
435 postUserToRemoteApp(userId, app,
436 applicationsRestClientService);
441 } catch (Exception e) {
442 String message = String.format(
443 "Failed to create user or update user roles for User %s, AppId %s",
444 userId, Long.toString(appId));
445 logger.error(EELFLoggerDelegate.errorLogger, message, e);
447 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,
1232 role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1235 @SuppressWarnings("unchecked")
1236 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue,
1238 List<RoleInAppForUser> rolesInAppForUser = null;
1239 FnApp app = fnAppService.getById(appId);
1240 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1242 // for onap portal app, no need to make a remote call
1243 List<Role> roleList = new ArrayList<>();
1244 if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1245 if (app.getAuthCentral()) {
1246 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1247 for (CentralV2Role cenRole : cenRoleList) {
1248 Role role = new Role();
1249 role.setActiveYn(cenRole.isActive());
1250 role.setId(cenRole.getId());
1251 role.setRoleName(cenRole.getName());
1252 role.setPriority(cenRole.getPriority());
1256 Optional<FnUser> user = fnUserService.getUser(userId);
1257 if (user.isPresent()) {
1258 roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole)
1259 .collect(Collectors.toList());
1262 List<Role> activeRoleList = new ArrayList<>();
1263 for (Role role : roleList) {
1264 if (role.getActiveYn()) {
1265 if (role.getId() != 1) { // prevent portal admin from being added
1266 activeRoleList.add(role);
1267 } else if (extRequestValue) {
1268 activeRoleList.add(role);
1273 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1274 // If localUser does not exists return roles
1275 Set<FnRole> roleSet = null;
1276 FnRole[] roleSetList = null;
1277 if (localUser != null) {
1278 roleSet = localUser.getAppEPRoles(app);
1279 roleSetList = roleSet.toArray(new FnRole[0]);
1281 rolesInAppForUser = fnUserRoleService
1282 .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1283 return rolesInAppForUser;
1286 EcompRole[] appRoles = null;
1287 boolean checkIfUserIsApplicationAccAdmin = false;
1288 List<EcompRole> roles = new ArrayList<>();
1289 if (app.getAuthCentral()) {
1290 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1291 FnApp application = fnAppService.getById(appId);
1292 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1295 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1296 for (FnRole role : applicationRoles) {
1297 List<EpAppFunction> cenRoleFuncList = epAppFunctionService
1298 .getAppRoleFunctionList(role.getId(), app.getId());
1299 for (EpAppFunction roleFunc : cenRoleFuncList) {
1301 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1302 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1303 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1304 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1305 String name = roleFunc.getFunctionName();
1307 FnFunction function = new FnFunction();
1308 function.setAction(action);
1309 function.setType(type);
1310 function.setCode(functionCode);
1311 function.setName(name);
1312 role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1315 roleSetWithFunctioncds.add(role);
1320 for (FnRole role1 : roleSetWithFunctioncds) {
1321 EcompRole ecompRole = new EcompRole();
1322 ecompRole.setId(role1.getId());
1323 ecompRole.setName(role1.getRoleName());
1324 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1325 roles.add(ecompRole);
1328 if (checkIfUserIsApplicationAccAdmin) {
1329 appRoles = roles.toArray(new EcompRole[roles.size()]);
1330 logger.debug(EELFLoggerDelegate.debugLogger,
1331 "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}",
1333 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1334 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1335 List<String> roleAdminAppRolesNames = new ArrayList<>();
1337 "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1338 + " where fu.role_id = ep.role_id"
1339 + " and fu.app_id = ep.app_id"
1340 + " and fu.user_id = :userId"
1341 + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1342 + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1345 + " 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"
1346 + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1347 List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1348 .setParameter("userId", userId)
1350 List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1351 .collect(Collectors.toList());
1353 List<EcompRole> userapproverRolesList = new ArrayList<>();
1354 for (String str : getUserApproverRoles) {
1355 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1356 if (epRole != null) {
1357 userapproverRolesList.add(epRole);
1360 for (EcompRole role : userapproverRolesList) {
1362 List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1363 boolean checkIfFunctionsExits = roleFunList.stream()
1364 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1365 if (checkIfFunctionsExits) {
1366 roleAdminAppRoles.add(role);
1367 List<RoleFunction> filteredList = roleFunList.stream()
1368 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1369 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1370 .collect(Collectors.toList()));
1373 for (String name : roleAdminAppRolesNames) {
1374 roles.stream().filter(x -> name.equals(x.getName())).findAny()
1375 .ifPresent(roleAdminAppRoles::add);
1378 appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1382 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1384 // Test this error case, for generating an internal ONAP Portal
1386 // EcompRole[] appRoles = null;
1387 // If there is an exception in the rest client api, then null will
1389 if (appRoles != null) {
1390 if (!app.getAuthCentral()) {
1391 syncAppRoles(appId, appRoles);
1393 EcompRole[] userAppRoles = null;
1396 if (app.getAuthCentral()) {
1397 List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1398 List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1399 .createNamedQuery("EPUserAppCurrentRoles")
1400 .setParameter("appId", app.getId())
1401 .setParameter("userId", actualUser.get(0).getId())
1403 List<EcompRole> setUserRoles = new ArrayList<>();
1404 for (EPUserAppCurrentRoles role : userAppsRolesList) {
1405 logger.debug(EELFLoggerDelegate.debugLogger,
1406 "In getAppRolesForUser() - userAppsRolesList get userRolename = {}",
1407 role.getRoleName());
1408 EcompRole ecompRole = new EcompRole();
1409 ecompRole.setId(role.getRoleId());
1410 ecompRole.setName(role.getRoleName());
1411 setUserRoles.add(ecompRole);
1414 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1415 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1417 if (!checkIfUserisAccAdmin) {
1418 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1419 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1421 List<String> roleNames = new ArrayList<>();
1422 for (EcompRole role : setUserRoles) {
1423 EcompRole epRole = appRolesList.stream()
1424 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1425 List<RoleFunction> roleFunList = new ArrayList<>();
1427 if (epRole != null) {
1428 if (epRole.getRoleFunctions().size() > 0) {
1429 roleFunList.addAll(epRole.getRoleFunctions());
1431 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1432 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1433 if (checkIfFunctionsExits) {
1434 finalUserAppRolesList.add(role);
1435 List<RoleFunction> filteredList = roleFunList.stream()
1436 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1437 .collect(Collectors.toList());
1438 roleNames = filteredList.stream().map(RoleFunction::getCode)
1439 .collect(Collectors.toList());
1441 roleNames.add(epRole.getName());
1444 for (String name : roleNames) {
1445 EcompRole ecompRole = appRolesList.stream()
1446 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1447 if (ecompRole != null) {
1448 finalUserAppRolesList.add(ecompRole);
1452 for (String name : roleNames) {
1453 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1454 role -> role.getRoleName().equalsIgnoreCase(name));
1455 if (checkIfFunctionsExits) {
1456 appRolesList.stream().filter(x -> name.equals(x.getName()))
1457 .findAny().ifPresent(setUserRoles::add);
1460 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1463 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1464 String.format("/user/%s/roles", userId));
1466 } catch (HTTPException e) {
1467 // Some apps are returning 400 if user is not found.
1468 if (e.getResponseCode() == 400) {
1469 logger.debug(EELFLoggerDelegate.debugLogger,
1470 "getAppRolesForUser caught exception with response code 400; continuing", e);
1472 // Other response code, let it come thru.
1476 if (userAppRoles == null) {
1477 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1478 EcompPortalUtils.setExternalAppResponseCode(200);
1479 String message = String.format(
1480 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1481 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1482 + "Overriding to 200 until framework SDK returns a useful response.",
1483 Long.toString(appId), userId);
1484 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1488 HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1489 ArrayList<EcompRole> activeRoles = new ArrayList<>();
1490 if (userAppRoles != null) {
1491 for (EcompRole userAppRole : userAppRoles) {
1492 if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1493 EcompRole role = new EcompRole();
1494 role.setId(userAppRole.getId());
1495 role.setName(userAppRole.getName());
1496 activeRoles.add(role);
1500 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1502 boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1504 // If the remote application isn't down we MUST sync user
1505 // roles here in case we have this user here!
1506 syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null,
1507 checkIfUserisRoleAdmin,
1509 } catch (Exception e) {
1510 // TODO: we may need to check if user exists, maybe remote
1512 String message = String.format(
1513 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1514 Long.toString(appId));
1515 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1516 userAppRoles = new EcompRole[0];
1518 rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1520 } catch (Exception e) {
1521 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1522 Long.toString(appId));
1523 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1525 return rolesInAppForUser;
1528 private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1529 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1530 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1532 List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1534 List<FnRole> obsoleteRoles = new ArrayList<>();
1535 for (FnRole oldAppRole : currentAppRoles) {
1536 if (oldAppRole.getAppRoleId() != null) {
1538 role = newRolesMap.get(oldAppRole.getAppRoleId());
1540 if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1541 oldAppRole.setRoleName(role.getName());
1543 oldAppRole.setActiveYn(true);
1544 newRolesMap.remove(oldAppRole.getAppRoleId());
1546 obsoleteRoles.add(oldAppRole);
1549 obsoleteRoles.add(oldAppRole);
1552 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1553 if (obsoleteRoles.size() > 0) {
1554 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1555 for (FnRole role : obsoleteRoles) {
1556 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1557 Long roleId = role.getId();
1558 List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1560 logger.debug(EELFLoggerDelegate.debugLogger,
1561 "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1562 for (FnUserRole userRole : userRoles) {
1563 logger.debug(EELFLoggerDelegate.debugLogger,
1564 "syncAppRoles: about to delete userRole: " + userRole.toString());
1565 fnUserRoleService.deleteById(userRole.getId());
1566 logger.debug(EELFLoggerDelegate.debugLogger,
1567 "syncAppRoles: finished deleting userRole: " + userRole.toString());
1569 List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1570 int numMenuRoles = funcMenuRoles.size();
1571 logger.debug(EELFLoggerDelegate.debugLogger,
1572 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1573 for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1574 Long menuId = funcMenuRole.getMenuId().getMenuId();
1575 // If this is the only role for this menu item, then the
1576 // app and roles will be gone,
1577 // so must null out the url too, to be consistent
1578 List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService
1579 .retrieveByMenuId(menuId);
1580 int numMenuRoles2 = funcMenuRoles2.size();
1581 logger.debug(EELFLoggerDelegate.debugLogger,
1582 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1583 fnMenuFunctionalRolesService.delete(funcMenuRole);
1585 if (numMenuRoles2 == 1) {
1586 // If this is the only role for this menu item, then
1587 // the app and roles will be gone,
1588 // so must null out the url too, to be consistent
1589 logger.debug(EELFLoggerDelegate.debugLogger,
1590 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1591 List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1592 if (funcMenuItems.size() > 0) {
1593 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1594 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1595 funcMenuItem.setUrl("");
1599 boolean isPortalRequest = true;
1600 deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1601 logger.debug(EELFLoggerDelegate.debugLogger,
1602 "syncAppRoles: about to delete the role: " + role.toString());
1603 fnRoleService.delete(role);
1604 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1607 for (EcompRole role : newRolesToAdd) {
1608 logger.debug(EELFLoggerDelegate.debugLogger,
1609 "syncAppRoles: about to add missing role: " + role.toString());
1610 FnRole newRole = new FnRole();
1611 // Attention! All roles from remote application supposed to be
1613 newRole.setActiveYn(true);
1614 newRole.setRoleName(role.getName());
1615 newRole.setAppId(appId);
1616 newRole.setAppRoleId(role.getId());
1617 fnRoleService.saveOne(newRole);
1619 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1620 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1621 } catch (Exception e) {
1622 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1623 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1624 throw new Exception(e);
1628 private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1630 Session localSession = entityManager.unwrap(Session.class);
1634 // It should delete only when it portal's roleId
1635 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1636 // Delete from fn_role_function
1637 sql = "DELETE FROM fn_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 fn_role_composite
1642 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1643 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1644 query = localSession.createSQLQuery(sql);
1645 query.executeUpdate();
1647 // Delete from ep_app_role_function
1648 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1649 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1650 query = localSession.createSQLQuery(sql);
1651 query.executeUpdate();
1652 // Delete from ep_role_notification
1653 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1654 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1655 query = localSession.createSQLQuery(sql);
1656 query.executeUpdate();
1657 // Delete from fn_user_pseudo_role
1658 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1659 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1660 query = localSession.createSQLQuery(sql);
1661 query.executeUpdate();
1662 // Delete form EP_WIDGET_CATALOG_ROLE
1663 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1664 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1665 query = localSession.createSQLQuery(sql);
1666 query.executeUpdate();
1667 // Delete form EP_WIDGET_CATALOG_ROLE
1668 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1669 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1670 query = localSession.createSQLQuery(sql);
1671 query.executeUpdate();
1672 if (!isPortalRequest) {
1673 // Delete form fn_menu_functional_roles
1674 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1675 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1676 query = localSession.createSQLQuery(sql);
1677 query.executeUpdate();
1679 } catch (Exception e) {
1680 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1681 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1685 private void checkIfRoleInactive(FnRole epRole) throws Exception {
1686 if (!epRole.getActiveYn()) {
1687 throw new Exception(epRole.getRoleName() + " role is unavailable");
1691 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1692 boolean result = false;
1693 // No changes if no new roles list or no userId.
1694 if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1695 && newAppsListWithAdminRoles.getAppsRoles() != null) {
1696 synchronized (syncRests) {
1697 List<FnApp> apps = fnAppService.getAppsFullList();
1698 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1699 for (FnApp app : apps) {
1700 enabledApps.put(app.getId(), app);
1702 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1703 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1704 // user Admin role may be added only for enabled apps
1705 if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1706 newAppsWhereUserIsAdmin.add(adminRole);
1710 boolean createNewUser = false;
1711 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1712 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1713 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1714 if (localUserList.size() > 0) {
1715 FnUser tmpUser = localUserList.get(0);
1716 oldAppsWhereUserIsAdmin = fnUserRoleService
1717 .retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1718 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1721 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1722 // we create new user only if he has Admin Role for any App
1723 createNewUser = true;
1725 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1726 oldAppsWhereUserIsAdmin);
1734 public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1735 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1736 List<FnUserRole> oldAppsWhereUserIsAdmin) {
1737 if (user != null || createNewUser) {
1738 if (createNewUser) {
1739 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1741 user.setActiveYn(true);
1744 for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1745 // user Admin role may be deleted only for enabled
1747 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1748 fnUserRoleService.saveOne(oldUserApp);
1751 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1752 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1753 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1754 FnUserRole newUserApp = new FnUserRole();
1755 newUserApp.setUserId(user);
1756 newUserApp.setFnAppId(app);
1757 newUserApp.setRoleId(role);
1758 fnUserRoleService.saveOne(newUserApp);
1760 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1761 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1768 public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1769 boolean result = false;
1771 // Reset All admin role for centralized applications
1772 List<FnApp> appList = fnAppService.getCentralizedApps();
1773 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1774 for (FnApp app : appList) {
1776 if (EPCommonSystemProperties
1777 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1778 name = user.getOrgUserId() + SystemProperties
1779 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1781 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1782 HttpEntity<String> entity = new HttpEntity<>(headers);
1783 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1785 ResponseEntity<String> getResponse = template
1786 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1787 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1789 if (getResponse.getBody().equals("{}")) {
1790 String addDesc = "{\"name\":\"" + extRole + "\"}";
1791 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1793 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1795 HttpMethod.POST, roleEntity, String.class);
1798 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1800 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1801 + "userRole/" + name + "/" + extRole,
1802 HttpMethod.DELETE, deleteUserRole, String.class);
1803 } catch (Exception e) {
1804 logger.error(EELFLoggerDelegate.errorLogger,
1805 " Role not found for this user may be it gets deleted before", e);
1808 } catch (Exception e) {
1809 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1810 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1811 app.getAuthNamespace(), e.getMessage());
1813 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1814 app.getAuthNamespace(), e);
1818 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1819 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1821 if (app.getAuthCentral()) {
1822 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1823 HttpEntity<String> entity = new HttpEntity<>(headers);
1825 if (EPCommonSystemProperties
1826 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1827 name = user.getOrgUserId() + SystemProperties
1828 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1830 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1831 ResponseEntity<String> getUserRolesResponse = template.exchange(
1832 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1833 + "userRoles/user/" + name,
1834 HttpMethod.GET, entity, String.class);
1835 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1836 if (!getUserRolesResponse.getBody().equals("{}")) {
1837 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1838 JSONArray extRoles = jsonObj.getJSONArray("userRole");
1839 final Map<String, JSONObject> extUserRoles = new HashMap<>();
1840 for (int i = 0; i < extRoles.length(); i++) {
1841 String userRole = extRoles.getJSONObject(i).getString("role");
1842 if (userRole.startsWith(app.getAuthNamespace() + ".")
1843 && !userRole.equals(app.getAuthNamespace() + ".admin")
1844 && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1846 extUserRoles.put(userRole, extRoles.getJSONObject(i));
1849 if (!extUserRoles.containsKey(extRole)) {
1850 // Assign with new apps user admin
1852 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1853 // Assign user role for an application in external access system
1854 ObjectMapper addUserRoleMapper = new ObjectMapper();
1855 String userRole = addUserRoleMapper.writeValueAsString(extUser);
1856 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1858 SystemProperties.getProperty(
1859 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1860 HttpMethod.POST, addUserRole, String.class);
1861 } catch (Exception e) {
1862 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1869 } catch (Exception e) {
1870 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1871 logger.debug(EELFLoggerDelegate.errorLogger,
1872 "Application name space not found in External system for app {} due to bad rquest name space ",
1873 app.getAuthNamespace(), e.getMessage());
1875 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1876 app.getAuthNamespace(), e);
1881 } catch (Exception e) {
1883 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
1888 public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
1889 final String getAllAppsFunctionsOfUser =
1890 "select distinct ep.function_cd from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_app fa , fn_role fr\n"
1891 + " where fu.role_id = ep.role_id \n"
1892 + " and fu.app_id = ep.app_id\n"
1893 + " and fu.user_id =:userId\n"
1894 + " and ea.function_cd = ep.function_cd\n"
1895 + " and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1))\n"
1896 + " and fr.role_id = fu.role_id and fr.active_yn='Y' \n"
1898 + " select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f\n"
1899 + " where role_id = 999\n"
1900 + " and app_r_f.function_cd = a_f.function_cd\n"
1903 + " 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\n"
1904 + " and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'\n"
1906 List getRoleFuncListOfPortal = entityManager.createNativeQuery(getAllAppsFunctionsOfUser)
1907 .setParameter("userId", OrgUserId).getResultList();
1908 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
1909 Set<String> roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
1910 .collect(Collectors.toSet());
1911 if (!roleFunSet.isEmpty()) {
1912 for (String roleFunction : roleFunSet) {
1913 String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
1914 getRoleFuncListOfPortalSet.remove(roleFunction);
1915 getRoleFuncListOfPortalSet.add(roleFun);
1919 Set<String> finalRoleFunctionSet = new HashSet<>();
1920 for (String roleFn : getRoleFuncListOfPortalSet) {
1921 finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
1924 return finalRoleFunctionSet;