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.DomainVo;
70 import org.onap.portal.domain.db.ep.EpAppFunction;
71 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
72 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
73 import org.onap.portal.domain.db.fn.FnApp;
74 import org.onap.portal.domain.db.fn.FnFunction;
75 import org.onap.portal.domain.db.fn.FnMenuFunctional;
76 import org.onap.portal.domain.db.fn.FnMenuFunctionalRoles;
77 import org.onap.portal.domain.db.fn.FnRole;
78 import org.onap.portal.domain.db.fn.FnRoleFunction;
79 import org.onap.portal.domain.db.fn.FnUser;
80 import org.onap.portal.domain.db.fn.FnUserRole;
81 import org.onap.portal.domain.dto.model.ExternalSystemRoleApproval;
82 import org.onap.portal.domain.dto.model.ExternalSystemUser;
83 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
84 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
85 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
86 import org.onap.portal.domain.dto.transport.CentralV2Role;
87 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
88 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
89 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
90 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
91 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
92 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
93 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
94 import org.onap.portal.domain.dto.transport.Role;
95 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
96 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
97 import org.onap.portal.exception.DeleteDomainObjectFailedException;
98 import org.onap.portal.exception.RoleFunctionException;
99 import org.onap.portal.exception.SyncUserRolesException;
100 import org.onap.portal.logging.format.EPAppMessagesEnum;
101 import org.onap.portal.logging.logic.EPLogUtil;
102 import org.onap.portal.service.app.FnAppService;
103 import org.onap.portal.service.appFunction.EpAppFunctionService;
104 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
105 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
106 import org.onap.portal.service.role.FnRoleService;
107 import org.onap.portal.service.roleFunction.FnRoleFunctionService;
108 import org.onap.portal.service.user.FnUserService;
109 import org.onap.portal.service.userRole.FnUserRoleService;
110 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
111 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
112 import org.onap.portal.utils.EPCommonSystemProperties;
113 import org.onap.portal.utils.EPUserUtils;
114 import org.onap.portal.utils.EcompPortalUtils;
115 import org.onap.portal.utils.PortalConstants;
116 import org.onap.portalsdk.core.domain.RoleFunction;
117 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
118 import org.onap.portalsdk.core.restful.domain.EcompRole;
119 import org.onap.portalsdk.core.util.SystemProperties;
120 import org.springframework.beans.factory.annotation.Autowired;
121 import org.springframework.http.HttpEntity;
122 import org.springframework.http.HttpHeaders;
123 import org.springframework.http.HttpMethod;
124 import org.springframework.http.HttpStatus;
125 import org.springframework.http.ResponseEntity;
126 import org.springframework.stereotype.Service;
127 import org.springframework.transaction.annotation.Transactional;
128 import org.springframework.web.client.HttpClientErrorException;
129 import org.springframework.web.client.RestTemplate;
133 public class AdminRolesService {
135 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
136 private static final Object syncRests = new Object();
137 private final RestTemplate template = new RestTemplate();
139 private Long SYS_ADMIN_ROLE_ID = 38L;
140 private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
141 private final Long ECOMP_APP_ID = 1L;
142 private final String ADMIN_ACCOUNT = "Is account admin for user {}";
144 private final AppsCacheService appsCacheService;
145 private final EntityManager entityManager;
146 private final FnUserService fnUserService;
147 private final FnRoleService fnRoleService;
148 private final FnAppService fnAppService;
149 private final FnRoleFunctionService fnRoleFunctionService;
150 private final FnMenuFunctionalService fnMenuFunctionalService;
151 private final FnUserRoleService fnUserRoleService;
152 private final EpAppFunctionService epAppFunctionService;
153 private final EcompUserAppRolesService ecompUserAppRolesService;
154 private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
155 private final ApplicationsRestClientService applicationsRestClientService;
156 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
157 private final ExternalAccessRolesService externalAccessRolesService;
158 private final EpUserRolesRequestService epUserRolesRequestService;
161 public AdminRolesService(AppsCacheService appsCacheService,
162 final EntityManager entityManager,
163 final FnUserService fnUserService, FnRoleService fnRoleService,
164 FnAppService fnAppService,
165 FnRoleFunctionService fnRoleFunctionService, FnMenuFunctionalService fnMenuFunctionalService,
166 final FnUserRoleService fnUserRoleService,
167 EpAppFunctionService epAppFunctionService,
168 EcompUserAppRolesService ecompUserAppRolesService,
169 FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
170 ApplicationsRestClientService applicationsRestClientService,
171 EpUserRolesRequestDetService epUserRolesRequestDetService,
172 ExternalAccessRolesService externalAccessRolesService,
173 EpUserRolesRequestService epUserRolesRequestService) {
174 this.appsCacheService = appsCacheService;
175 this.entityManager = entityManager;
176 this.fnUserService = fnUserService;
177 this.fnRoleService = fnRoleService;
178 this.fnAppService = fnAppService;
179 this.fnRoleFunctionService = fnRoleFunctionService;
180 this.fnMenuFunctionalService = fnMenuFunctionalService;
181 this.fnUserRoleService = fnUserRoleService;
182 this.epAppFunctionService = epAppFunctionService;
183 this.ecompUserAppRolesService = ecompUserAppRolesService;
184 this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
185 this.applicationsRestClientService = applicationsRestClientService;
186 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
187 this.externalAccessRolesService = externalAccessRolesService;
188 this.epUserRolesRequestService = epUserRolesRequestService;
191 public boolean isSuperAdmin(final String loginId) {
192 boolean isSuperAdmin;
194 isSuperAdmin = fnUserRoleService
195 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
196 } catch (Exception e) {
197 logger.error("isSuperAdmin exception: " + e.toString());
200 logger.info("isSuperAdmin " + isSuperAdmin);
204 public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
206 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
207 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
208 logger.debug(EELFLoggerDelegate.debugLogger,
209 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
210 orgUserId, userAdminApps.size());
212 for (FnUserRole userApp : userApps) {
213 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
214 userAdminApps.size() > 1)) {
215 logger.debug(EELFLoggerDelegate.debugLogger,
216 "Is account admin for userAdminApps() - for user {}, found Id {}",
217 orgUserId, userApp.getRoleId().getId());
221 } catch (Exception e) {
222 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
223 logger.error(EELFLoggerDelegate.errorLogger,
224 "Exception occurred while executing isAccountAdmin operation",
230 public boolean isUser(final long userId) {
232 FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
233 if (currentUser != null && currentUser.getId() != null) {
234 for (FnUserRole userApp : currentUser.getUserApps()) {
235 if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
236 FnRole role = userApp.getRoleId();
237 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
238 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
239 if (role.getActiveYn()) {
246 } catch (Exception e) {
247 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
248 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
254 public boolean isRoleAdmin(Long userId) {
256 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
257 List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
258 logger.debug(EELFLoggerDelegate.debugLogger,
259 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
260 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
261 Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
262 Set<String> roleFunSet;
263 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
264 .collect(Collectors.toSet());
265 if (!roleFunSet.isEmpty()) {
266 for (String roleFunction : roleFunSet) {
267 String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
268 getRoleFuncListOfPortalSet1.add(type);
272 boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
273 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
274 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
275 checkIfFunctionsExits);
277 return checkIfFunctionsExits;
279 } catch (Exception e) {
280 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
281 logger.error(EELFLoggerDelegate.errorLogger,
282 "Exception occurred while executing isRoleAdmin operation",
288 public boolean isAccountAdminOfApplication(Long userId, FnApp app) {
289 boolean isApplicationAccountAdmin = false;
291 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
292 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
293 if (!userAdminApps.isEmpty()) {
294 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
295 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
298 } catch (Exception e) {
299 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
300 logger.error(EELFLoggerDelegate.errorLogger,
301 "Exception occurred while executing isAccountAdminOfApplication operation", e);
303 logger.debug(EELFLoggerDelegate.debugLogger,
304 "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
306 return isApplicationAccountAdmin;
310 private List<Integer> getAdminAppsForTheUser(final Long userId) {
311 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)";
312 return entityManager.createQuery(query, Integer.class)
313 .setParameter("userId", userId).getResultList();
316 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
317 AppWithRolesForUser newAppRolesForUser) {
318 boolean result = false;
319 boolean epRequestValue = false;
321 String reqMessage = "";
322 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
323 userId = newAppRolesForUser.getOrgUserId().trim();
325 Long appId = newAppRolesForUser.getAppId();
326 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
328 if (userId.length() > 0) {
329 ObjectMapper mapper = new ObjectMapper();
330 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
333 FnApp app = fnAppService.getById(appId);
335 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
337 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
339 boolean checkIfUserIsOnlyRoleAdmin =
340 isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
341 if (checkIfUserIsOnlyRoleAdmin) {
342 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
343 if (!roleInAppForUser.getIsApplied()) {
344 EcompRole ecompRole = new EcompRole();
345 ecompRole.setId(roleInAppForUser.getRoleId());
346 ecompRole.setName(roleInAppForUser.getRoleName());
347 rolesGotDeletedFromApprover.add(ecompRole);
352 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
354 boolean systemUser = newAppRolesForUser.isSystemUser();
356 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
359 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
360 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
361 userRolesInLocalApp);
362 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
363 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
364 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
365 // Apply changes in external Access system
367 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
369 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
371 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
373 systemUser, rolesGotDeletedByApprover, false);
375 } else if (!app.getAuthCentral() && systemUser) {
376 throw new Exception("For non-centralized application we cannot add systemUser");
377 } else { // if centralized app
378 if (app.getAuthCentral()) {
379 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
380 pushRemoteUser(roleInAppForUserList, userId, app, mapper,
381 applicationsRestClientService, false);
384 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
385 roleInAppForUserList);
386 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
388 userRolesInLocalApp);
389 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
390 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
392 // Apply changes in external Access system
393 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
395 epRequestValue, false, rolesGotDeletedFromApprover,
396 checkIfUserIsOnlyRoleAdmin);
398 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
399 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
400 checkIfUserIsOnlyRoleAdmin);
402 // In case if portal is not centralized then follow existing approach
403 else if (!app.getAuthCentral() && app.getId()
404 .equals(PortalConstants.PORTAL_APP_ID)) {
405 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
406 roleInAppForUserList);
407 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
409 userRolesInLocalApp);
410 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
411 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
412 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
413 } else {// remote app
414 FnUser remoteAppUser;
415 if (!app.getAuthCentral() && !app.getId()
416 .equals(PortalConstants.PORTAL_APP_ID)) {
418 remoteAppUser = checkIfRemoteUserExits(userId, app,
419 applicationsRestClientService);
421 if (remoteAppUser == null) {
422 addRemoteUser(roleInAppForUserList, userId, app,
423 mapper, applicationsRestClientService);
425 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
426 roleInAppForUserList, mapper,
427 applicationsRestClientService, appId, userId);
428 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
430 userRolesInRemoteApp);
431 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
432 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
433 epRequestValue, null, false, rolesGotDeletedByApprover, false);
435 // If no roles remain, request app to set user inactive.
436 if (userRolesInRemoteApp.size() == 0) {
437 logger.debug(EELFLoggerDelegate.debugLogger,
438 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
441 postUserToRemoteApp(userId, app,
442 applicationsRestClientService);
447 } catch (Exception e) {
448 String message = String.format(
449 "Failed to create user or update user roles for User %s, AppId %s",
450 userId, Long.toString(appId));
451 logger.error(EELFLoggerDelegate.errorLogger, message, e);
453 reqMessage = e.getMessage();
456 return new ExternalRequestFieldsValidator(result, reqMessage);
460 private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
461 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
463 pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
464 roleInAppForUserList, appRoleIdUsed);
468 private void postUserToRemoteApp(String userId, FnApp app,
469 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
471 getUser(userId, app, applicationsRestClientService);
475 private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
476 throws HTTPException {
477 return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
481 private void pushUserOnRemoteApp(String userId, FnApp app,
482 ApplicationsRestClientService applicationsRestClientService,
483 ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
487 client = fnUserService.loadUserByUsername(userId);
489 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
490 if (client == null) {
491 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
492 logger.error(EELFLoggerDelegate.errorLogger, msg);
493 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
494 if (!userList.isEmpty()) {
495 logger.debug(EELFLoggerDelegate.debugLogger,
496 userList.get(0).getOrgUserId() + " User was found in Portal");
497 client = userList.get(0);
498 client.setUserApps(Collections.EMPTY_SET);
499 client.setIsSystemUser(false);
501 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
502 throw new Exception(msg);
507 client.setLoginId(userId);
508 client.setActiveYn(true);
509 client.setOrgUserId(userId);
511 roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
512 SortedSet<Role> roles = new TreeSet<>();
514 List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
515 List<FnApp> appList = new ArrayList<>();
517 List<CentralV2Role> roleList = new ArrayList<>();
519 List<FnRole> userRoles = new ArrayList<>();
521 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
522 FnRole role = new FnRole();
523 role.setId(roleInappForUser.getRoleId());
524 role.setRoleName(roleInappForUser.getRoleName());
529 List<FnRole> userAppRoles = new ArrayList<>();
530 for (FnRole role : userRoles) {
531 FnRole appRole = getAppRoles.stream()
532 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
534 FnRole epRole = new FnRole();
535 if (appRole != null) {
536 epRole.setId(appRole.getId());
537 epRole.setRoleName(appRole.getRoleName());
539 userAppRoles.add(epRole);
541 userRoles = new ArrayList<>(userAppRoles);
543 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
545 for (CentralV2Role epRole : roleList) {
546 Role role = new Role();
547 FnRole appRole = getAppRoles.stream()
548 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
549 List<FnRoleFunction> fnRoleFunctions = new ArrayList<>();
550 for (DomainVo vo : epRole.getRoleFunctions()) {
551 Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
552 roleFunction.ifPresent(fnRoleFunctions::add);
554 if (appRole != null) {
555 role.setId(appRole.getAppRoleId());
556 role.setRoleName(epRole.getName());
557 role.setFnRoleFunctions(new HashSet<>(fnRoleFunctions));
561 client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
563 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
564 logger.debug(EELFLoggerDelegate.debugLogger,
565 "about to post a client to remote application, users json = " + userInString);
566 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
569 private FnRole roleToFnRole(Role role) {
570 return FnRole.builder()
572 .roleName(role.getRoleName())
573 .activeYn(role.getActiveYn())
574 .priority(role.getPriority())
575 .fnRoleFunctions(role.getFnRoleFunctions())
576 .childRoles(role.getChildRoles())
577 .parentRoles(role.getParentRoles())
581 private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
582 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
583 throws JsonProcessingException, HTTPException {
584 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
585 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
586 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
588 externalApp = appsCacheService.getApp(appId);
589 String appBaseUri = null;
590 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
591 if (externalApp != null) {
592 appBaseUri = externalApp.getAppRestEndpoint();
594 if (appBaseUri != null && appBaseUri.endsWith("/api")) {
595 for (EcompRole eprole : updatedUserRolesinRemote) {
596 RemoteRoleV1 role = new RemoteRoleV1();
597 role.setId(eprole.getId());
598 role.setName(eprole.getName());
599 updatedUserRolesinRemoteV1.add(role);
601 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
603 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
604 String.format("/user/%s/roles", userId));
605 return updateUserRolesInEcomp;
608 private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
609 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
610 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
611 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
615 private void createNewUserOnRemoteApp(String userId, FnApp app,
616 ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
619 FnUser client = fnUserService.loadUserByUsername(userId);
621 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
623 if (client == null) {
624 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
625 logger.error(EELFLoggerDelegate.errorLogger, msg);
626 throw new Exception(msg);
629 client.setLoginId(userId);
630 client.setActiveYn(true);
633 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
634 logger.debug(EELFLoggerDelegate.debugLogger,
635 "about to post new client to remote application, users json = " + userInString);
636 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
640 private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
641 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
642 if (roleInAppForUser.getIsApplied()) {
649 private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
650 Set<EcompRole> existingUserRoles = new TreeSet<>();
651 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
652 if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
653 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
654 EcompRole ecompRole = new EcompRole();
655 ecompRole.setId(roleInAppForUser.getRoleId());
656 ecompRole.setName(roleInAppForUser.getRoleName());
657 existingUserRoles.add(ecompRole);
660 return existingUserRoles;
663 private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
664 List<EpUserRolesRequest> epRequestIdVal;
666 epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
667 if (epRequestIdVal.size() > 0) {
668 EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
669 epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
670 epAppRolesRequestData.setRequestStatus("O");
671 epAppRolesRequestData.setUserId(user);
672 epUserRolesRequestService.saveOne(epAppRolesRequestData);
673 List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
674 .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
675 if (epUserAppRolesDetailList.size() > 0) {
676 for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
677 epRequestUpdateList.setRequestType("O");
678 epRequestUpdateList.setReqId(epAppRolesRequestData);
679 epRequestUpdateList.setReqId(epAppRolesRequestData);
680 epUserRolesRequestDetService.saveOne(epRequestUpdateList);
682 logger.debug(EELFLoggerDelegate.debugLogger,
683 "User App roles request from User Page is overridden");
687 } catch (Exception e) {
688 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
692 public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
693 Set<EcompRole> userRolesInRemoteApp) {
694 RolesInAppForUser result;
695 result = new RolesInAppForUser();
696 result.setAppId(appId);
697 result.setOrgUserId(userId);
699 for (EcompRole role : userRolesInRemoteApp) {
700 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
701 roleInAppForUser.setRoleId(role.getId());
702 roleInAppForUser.setRoleName(role.getName());
703 roleInAppForUser.setIsApplied(true);
704 result.getRoles().add(roleInAppForUser);
709 private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
710 boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
711 boolean isLoggedInUserRoleAdminofApp) throws Exception {
713 List<FnUser> userInfo = checkIfUserExists(orgUserId);
714 if (userInfo.isEmpty()) {
715 createLocalUserIfNecessary(orgUserId, isSystemUser);
718 if (EPCommonSystemProperties
719 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
723 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
727 ObjectMapper mapper = new ObjectMapper();
728 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
729 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
730 ResponseEntity<String> getResponse = externalAccessRolesService
731 .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
733 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
734 String res = getResponse.getBody();
736 JSONArray extRoles = null;
737 if (!res.equals("{}")) {
738 jsonObj = new JSONObject(res);
739 extRoles = jsonObj.getJSONArray("role");
741 ExternalAccessUserRoleDetail userRoleDetail;
742 if (extRoles != null) {
743 for (int i = 0; i < extRoles.length(); i++) {
744 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
745 && !extRoles.getJSONObject(i).getString("name")
746 .equals(app.getAuthNamespace() + ".admin")
747 && !extRoles.getJSONObject(i).getString("name")
748 .equals(app.getAuthNamespace() + ".owner")) {
749 if (extRoles.getJSONObject(i).has("description")) {
750 ExternalRoleDescription desc = new ExternalRoleDescription(
751 extRoles.getJSONObject(i).getString("description"));
752 userRoleDetail = new ExternalAccessUserRoleDetail(
753 extRoles.getJSONObject(i).getString("name"), desc);
754 userRoleDetailList.add(userRoleDetail);
756 userRoleDetail = new ExternalAccessUserRoleDetail(
757 extRoles.getJSONObject(i).getString("name"), null);
758 userRoleDetailList.add(userRoleDetail);
765 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
766 userRoleDetailList, app);
768 List<EcompUserAppRoles> userAppList;
769 // If request coming from portal not from external role approval system then we have to check if user already
770 // have account admin or system admin as GUI will not send these roles
771 if (!isPortalRequest) {
772 FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
773 userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
774 if (!roleInAppUser.isEmpty()) {
775 for (EcompUserAppRoles userApp : userAppList) {
776 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
777 || userApp.getRoleId()
778 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
779 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
780 addSpecialRole.setIsApplied(true);
781 addSpecialRole.setRoleId(userApp.getRoleId());
782 addSpecialRole.setRoleName(userApp.getRoleName());
783 roleInAppUser.add(addSpecialRole);
788 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
789 .collect(Collectors.toList());
790 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
791 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
792 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
793 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
794 "_"), roleInAppUserNew);
796 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
797 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
798 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
801 if (isLoggedInUserRoleAdminofApp) {
802 if (deletedRolesByApprover.size() > 0) {
803 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
804 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
805 for (EcompRole role : deletedRolesByApprover) {
806 if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
807 .equals(role.getName())) {
808 newUpdatedRoles.add(userRole);
812 if (newUpdatedRoles.size() > 0) {
813 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
815 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
816 currentUserRolesToUpdate = new HashMap<>();
821 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
822 currentUserRolesToUpdate = new HashMap<>();
827 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
828 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
829 if (!(currentUserRolesToUpdate
830 .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
831 HttpEntity<String> entity = new HttpEntity<>(headers);
832 logger.debug(EELFLoggerDelegate.debugLogger,
833 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
835 ResponseEntity<String> deleteResponse = template.exchange(
837 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
838 + "userRole/" + name + "/" + userRole.getName(),
839 HttpMethod.DELETE, entity, String.class);
840 logger.debug(EELFLoggerDelegate.debugLogger,
841 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
842 userRole.getName(), deleteResponse.getBody());
845 // Check if user roles does not exists in External Central Auth System add them all
846 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
847 if (!(currentUserRolesInExternalSystem
848 .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
849 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
851 ExternalAccessUser extUser = new ExternalAccessUser(name,
852 app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
853 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
855 String formattedUserRole = mapper.writeValueAsString(extUser);
856 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
857 logger.debug(EELFLoggerDelegate.debugLogger,
858 "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
859 name, addUserRole.getRoleName());
860 ResponseEntity<String> addResponse = template
861 .exchange(SystemProperties
862 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
863 + "userRole", HttpMethod.POST, entity, String.class);
864 logger.debug(EELFLoggerDelegate.debugLogger,
865 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
866 addResponse.getBody(), addUserRole.getRoleName());
867 if (addResponse.getStatusCode().value() != 201
868 && addResponse.getStatusCode().value() != 404) {
869 logger.debug(EELFLoggerDelegate.debugLogger,
870 "Finished POST operation in external system but unable to save user role",
871 addResponse.getBody(),
872 addUserRole.getRoleName());
873 throw new Exception(addResponse.getBody());
877 } catch (HttpClientErrorException e) {
878 logger.error(EELFLoggerDelegate.errorLogger,
879 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
881 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
882 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
884 throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
885 "Please enter the valid systemUser");
887 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
888 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
889 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
891 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
893 } catch (Exception e) {
894 logger.error(EELFLoggerDelegate.errorLogger,
895 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
897 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
902 private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
903 List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
904 Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
905 //Add Account Admin role for partner app to prevent conflict
906 if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
907 FnRole role = new FnRole();
908 role.setRoleName(PortalConstants.ADMIN_ROLE
909 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
910 epRoleList.put(role.getRoleName(), role);
912 userRoleDetailList.removeIf(
913 userRoleDetail -> !epRoleList
914 .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
915 return userRoleDetailList;
918 private List<FnUser> checkIfUserExists(String userParams) {
919 return fnUserService.getUserWithOrgUserId(userParams);
923 private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
924 if (StringUtils.isEmpty(userId)) {
925 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
929 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
930 if (userList.size() == 0) {
933 client = fnUserService.loadUserByUsername(userId);
935 client = new FnUser();
936 client.setOrgUserId(userId);
937 client.setIsSystemUser(true);
938 client.setFirstName(userId.substring(0, userId.indexOf("@")));
940 if (client == null) {
941 String msg = "createLocalUserIfNecessary: cannot create user " + userId
942 + ", because not found in phonebook";
943 logger.error(EELFLoggerDelegate.errorLogger, msg);
945 client.setLoginId(userId);
946 client.setActiveYn(true);
948 fnUserService.saveFnUser(client);
950 } catch (Exception e) {
951 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
956 private FnUser checkIfRemoteUserExits(String userId, FnApp app,
957 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
958 FnUser checkRemoteUser = null;
960 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
961 } catch (HTTPException e) {
962 // Some apps are returning 400 if user is not found.
963 if (e.getResponseCode() == 400) {
964 logger.debug(EELFLoggerDelegate.debugLogger,
965 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
967 } else if (e.getResponseCode() == 404) {
968 logger.debug(EELFLoggerDelegate.debugLogger,
969 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
972 // Other response code, let it come thru.
976 return checkRemoteUser;
979 private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
980 throws HTTPException {
981 if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
982 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
983 if (userList != null && !userList.isEmpty()) {
984 return userList.get(0);
989 return getUser(userId, app, applicationsRestClientService);
992 private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
993 boolean externalSystemRequest, String reqType, boolean isSystemUser,
994 Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
995 boolean result = false;
996 String userId = rolesInAppForUser.getOrgUserId();
997 Long appId = rolesInAppForUser.getAppId();
998 synchronized (syncRests) {
999 createLocalUserIfNecessary(userId, isSystemUser);
1001 EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1003 i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1004 RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1005 EcompRole role = new EcompRole();
1006 role.setId(roleInAppForUser.getRoleId());
1007 role.setName(roleInAppForUser.getRoleName());
1008 userAppRoles[i] = role;
1011 EcompRole[] applicationRoles = null;
1013 if (isLoggedInUserRoleAdminOfApp) {
1014 List<EcompRole> roles = Arrays.stream(userAppRoles)
1015 .collect(Collectors.toList());
1016 List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1017 roles.addAll(roles1);
1018 applicationRoles = roles.toArray(new EcompRole[0]);
1021 syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1022 reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1024 } catch (Exception e) {
1025 logger.error(EELFLoggerDelegate.errorLogger,
1026 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1028 if ("DELETE".equals(reqType)) {
1029 throw new Exception(e.getMessage());
1036 private void syncUserRoles(String userId, Long appId,
1037 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1038 EcompRole[] appRoles) throws Exception {
1040 Transaction transaction = null;
1042 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1043 List<FnRole> roleInfo = externalAccessRolesService
1044 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1045 FnRole adminRole = new FnRole();
1046 if (roleInfo.size() > 0) {
1047 adminRole = roleInfo.get(0);
1048 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1051 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1052 if (userList.size() > 0) {
1053 FnUser client = userList.get(0);
1054 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1055 List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1057 .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1058 .setParameter("appId", appId)
1059 .setParameter("userId", client.getId())
1062 if ("DELETE".equals(reqType)) {
1063 for (FnUserRole userAppRoleList : userRoles) {
1064 List<FnRole> rolesList =
1065 (!userAppRoleList.getRoleId().getRoleName()
1066 .equals(adminRole.getRoleName()))
1067 ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1068 (userAppRoleList.getRoleId().getRoleName(), appId)
1069 : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1070 if (!rolesList.isEmpty()) {
1071 checkIfRoleInactive(rolesList.get(0));
1076 if (appRoles != null) {
1077 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1078 List<FnUserRole> finalUserRolesList = new ArrayList<>();
1079 if (checkIfUserisRoleAdmin) {
1080 for (EcompRole role : appRolesList) {
1081 for (FnUserRole userAppRoleList : userRoles) {
1082 if (userAppRoleList.getRoleId().getRoleName()
1083 .equals(role.getName())) {
1084 finalUserRolesList.add(userAppRoleList);
1089 userRoles = new ArrayList<>(finalUserRolesList);
1093 for (FnUserRole userRole : userRoles) {
1094 if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1095 && !PortalConstants.SYS_ADMIN_ROLE_ID
1096 .equals(userRole.getRoleId().getId())
1097 && !extRequestValue) {
1098 syncUserRolesExtension(userRole, appId,
1099 newUserAppRolesMap);
1100 } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1101 || "DELETE".equals(reqType))) {
1102 syncUserRolesExtension(userRole, appId,
1103 newUserAppRolesMap);
1104 } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1105 .equals(userRole.getRoleId().getId())) {
1106 syncUserRolesExtension(userRole, appId,
1107 newUserAppRolesMap);
1111 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1112 if (newRolesToAdd.size() > 0) {
1113 FnApp app = fnAppService.getById(appId);
1115 HashMap<Long, FnRole> rolesMap = new HashMap<>();
1116 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1117 String appIdValue = "";
1118 if (!extRequestValue) {
1119 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1121 @SuppressWarnings("unchecked")
1122 List<FnRole> roles = entityManager
1124 "from " + FnRole.class.getName() + " where appId is null "
1125 + appIdValue).getResultList();
1126 for (FnRole role : roles) {
1128 rolesMap.put(role.getId(), role);
1130 } else { // remote app
1131 @SuppressWarnings("unchecked")
1132 List<FnRole> roles = entityManager
1133 .createQuery("from EPRole where appId=:appId")
1134 .setParameter("appId", appId)
1136 for (FnRole role : roles) {
1137 if (!extRequestValue && app.getAuthCentral()) {
1138 rolesMap.put(role.getId(), role);
1140 rolesMap.put(role.getAppRoleId(), role);
1146 for (EcompRole userRole : newRolesToAdd) {
1147 FnUserRole userApp = new FnUserRole();
1148 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1149 .equals(adminRole.getRoleName())) {
1150 role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1151 userApp.setRoleId(role);
1152 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1153 && !extRequestValue) {
1155 } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1156 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1159 userApp.setRoleId(rolesMap.get(userRole.getId()));
1162 userApp.setUserId(client);
1163 userApp.setFnAppId(app);
1164 fnUserRoleService.saveOne(userApp);
1167 if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1169 * for local app -- hack - always make sure fn_role
1170 * table's app_id is null and not 1 for primary app in
1171 * this case being onap portal app; reason: hibernate
1172 * is rightly setting this to 1 while persisting to
1173 * fn_role as per the mapping but SDK role management
1174 * code expects the app_id to be null as there is no
1175 * concept of App_id in SDK
1177 Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1178 query.executeUpdate();
1182 transaction.commit();
1183 } catch (Exception e) {
1184 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1185 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1186 EcompPortalUtils.rollbackTransaction(transaction,
1187 "Exception occurred in syncUserRoles, Details: " + e.toString());
1188 if ("DELETE".equals(reqType)) {
1189 throw new SyncUserRolesException(e.getMessage());
1194 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1195 HashMap<Long, EcompRole> result = new HashMap<>();
1196 if (ecompRoles != null) {
1197 for (EcompRole ecompRole : ecompRoles) {
1198 if (ecompRole.getId() != null) {
1199 result.put(ecompRole.getId(), ecompRole);
1206 private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1207 HashMap<Long, EcompRole> newUserAppRolesMap) {
1210 if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1211 userAppRoleId = userRole.getRoleId().getId();
1212 } else { // remote app
1213 userAppRoleId = userRole.getId();
1216 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1217 fnUserRoleService.deleteById(userRole.getId());
1219 newUserAppRolesMap.remove(userAppRoleId);
1223 private Role fnRoleToRole(final FnRole role) {
1224 return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null,
1226 role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1229 @SuppressWarnings("unchecked")
1230 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue,
1232 List<RoleInAppForUser> rolesInAppForUser = null;
1233 FnApp app = fnAppService.getById(appId);
1234 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1236 // for onap portal app, no need to make a remote call
1237 List<Role> roleList = new ArrayList<>();
1238 if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1239 if (app.getAuthCentral()) {
1240 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1241 for (CentralV2Role cenRole : cenRoleList) {
1242 Role role = new Role();
1243 role.setActiveYn(cenRole.isActive());
1244 role.setId(cenRole.getId());
1245 role.setRoleName(cenRole.getName());
1246 role.setPriority(cenRole.getPriority());
1250 Optional<FnUser> user = fnUserService.getUser(userId);
1251 if (user.isPresent()) {
1252 roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole)
1253 .collect(Collectors.toList());
1256 List<Role> activeRoleList = new ArrayList<>();
1257 for (Role role : roleList) {
1258 if (role.getActiveYn()) {
1259 if (role.getId() != 1) { // prevent portal admin from being added
1260 activeRoleList.add(role);
1261 } else if (extRequestValue) {
1262 activeRoleList.add(role);
1267 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1268 // If localUser does not exists return roles
1269 Set<FnRole> roleSet = null;
1270 FnRole[] roleSetList = null;
1271 if (localUser != null) {
1272 roleSet = localUser.getAppEPRoles(app);
1273 roleSetList = roleSet.toArray(new FnRole[0]);
1275 rolesInAppForUser = fnUserRoleService
1276 .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1277 return rolesInAppForUser;
1280 EcompRole[] appRoles = null;
1281 boolean checkIfUserIsApplicationAccAdmin = false;
1282 List<EcompRole> roles = new ArrayList<>();
1283 if (app.getAuthCentral()) {
1284 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1285 FnApp application = fnAppService.getById(appId);
1286 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1289 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1290 for (FnRole role : applicationRoles) {
1291 List<EpAppFunction> cenRoleFuncList = epAppFunctionService
1292 .getAppRoleFunctionList(role.getId(), app.getId());
1293 for (EpAppFunction roleFunc : cenRoleFuncList) {
1295 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1296 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1297 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1298 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1299 String name = roleFunc.getFunctionName();
1301 FnFunction function = new FnFunction();
1302 function.setAction(action);
1303 function.setType(type);
1304 function.setCode(functionCode);
1305 function.setName(name);
1306 role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1309 roleSetWithFunctioncds.add(role);
1314 for (FnRole role1 : roleSetWithFunctioncds) {
1315 EcompRole ecompRole = new EcompRole();
1316 ecompRole.setId(role1.getId());
1317 ecompRole.setName(role1.getRoleName());
1318 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1319 roles.add(ecompRole);
1322 if (checkIfUserIsApplicationAccAdmin) {
1323 appRoles = roles.toArray(new EcompRole[roles.size()]);
1324 logger.debug(EELFLoggerDelegate.debugLogger,
1325 "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}",
1327 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1328 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1329 List<String> roleAdminAppRolesNames = new ArrayList<>();
1331 "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1332 + " where fu.role_id = ep.role_id"
1333 + " and fu.app_id = ep.app_id"
1334 + " and fu.user_id = :userId"
1335 + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1336 + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1339 + " 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"
1340 + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1341 List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1342 .setParameter("userId", userId)
1344 List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1345 .collect(Collectors.toList());
1347 List<EcompRole> userapproverRolesList = new ArrayList<>();
1348 for (String str : getUserApproverRoles) {
1349 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1350 if (epRole != null) {
1351 userapproverRolesList.add(epRole);
1354 for (EcompRole role : userapproverRolesList) {
1356 List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1357 boolean checkIfFunctionsExits = roleFunList.stream()
1358 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1359 if (checkIfFunctionsExits) {
1360 roleAdminAppRoles.add(role);
1361 List<RoleFunction> filteredList = roleFunList.stream()
1362 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1363 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1364 .collect(Collectors.toList()));
1367 for (String name : roleAdminAppRolesNames) {
1368 roles.stream().filter(x -> name.equals(x.getName())).findAny()
1369 .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 = {}",
1401 role.getRoleName());
1402 EcompRole ecompRole = new EcompRole();
1403 ecompRole.setId(role.getRoleId());
1404 ecompRole.setName(role.getRoleName());
1405 setUserRoles.add(ecompRole);
1408 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1409 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1411 if (!checkIfUserisAccAdmin) {
1412 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1413 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1415 List<String> roleNames = new ArrayList<>();
1416 for (EcompRole role : setUserRoles) {
1417 EcompRole epRole = appRolesList.stream()
1418 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1419 List<RoleFunction> roleFunList = new ArrayList<>();
1421 if (epRole != null) {
1422 if (epRole.getRoleFunctions().size() > 0) {
1423 roleFunList.addAll(epRole.getRoleFunctions());
1425 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1426 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1427 if (checkIfFunctionsExits) {
1428 finalUserAppRolesList.add(role);
1429 List<RoleFunction> filteredList = roleFunList.stream()
1430 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1431 .collect(Collectors.toList());
1432 roleNames = filteredList.stream().map(RoleFunction::getCode)
1433 .collect(Collectors.toList());
1435 roleNames.add(epRole.getName());
1438 for (String name : roleNames) {
1439 EcompRole ecompRole = appRolesList.stream()
1440 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1441 if (ecompRole != null) {
1442 finalUserAppRolesList.add(ecompRole);
1446 for (String name : roleNames) {
1447 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1448 role -> role.getRoleName().equalsIgnoreCase(name));
1449 if (checkIfFunctionsExits) {
1450 appRolesList.stream().filter(x -> name.equals(x.getName()))
1451 .findAny().ifPresent(setUserRoles::add);
1454 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1457 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1458 String.format("/user/%s/roles", userId));
1460 } catch (HTTPException e) {
1461 // Some apps are returning 400 if user is not found.
1462 if (e.getResponseCode() == 400) {
1463 logger.debug(EELFLoggerDelegate.debugLogger,
1464 "getAppRolesForUser caught exception with response code 400; continuing", e);
1466 // Other response code, let it come thru.
1470 if (userAppRoles == null) {
1471 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1472 EcompPortalUtils.setExternalAppResponseCode(200);
1473 String message = String.format(
1474 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1475 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1476 + "Overriding to 200 until framework SDK returns a useful response.",
1477 Long.toString(appId), userId);
1478 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1482 HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1483 ArrayList<EcompRole> activeRoles = new ArrayList<>();
1484 if (userAppRoles != null) {
1485 for (EcompRole userAppRole : userAppRoles) {
1486 if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1487 EcompRole role = new EcompRole();
1488 role.setId(userAppRole.getId());
1489 role.setName(userAppRole.getName());
1490 activeRoles.add(role);
1494 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1496 boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1498 // If the remote application isn't down we MUST sync user
1499 // roles here in case we have this user here!
1500 syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null,
1501 checkIfUserisRoleAdmin,
1503 } catch (Exception e) {
1504 // TODO: we may need to check if user exists, maybe remote
1506 String message = String.format(
1507 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1508 Long.toString(appId));
1509 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1510 userAppRoles = new EcompRole[0];
1512 rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1514 } catch (Exception e) {
1515 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1516 Long.toString(appId));
1517 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1519 return rolesInAppForUser;
1522 private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1523 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1524 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1526 List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1528 List<FnRole> obsoleteRoles = new ArrayList<>();
1529 for (FnRole oldAppRole : currentAppRoles) {
1530 if (oldAppRole.getAppRoleId() != null) {
1532 role = newRolesMap.get(oldAppRole.getAppRoleId());
1534 if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1535 oldAppRole.setRoleName(role.getName());
1537 oldAppRole.setActiveYn(true);
1538 newRolesMap.remove(oldAppRole.getAppRoleId());
1540 obsoleteRoles.add(oldAppRole);
1543 obsoleteRoles.add(oldAppRole);
1546 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1547 if (obsoleteRoles.size() > 0) {
1548 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1549 for (FnRole role : obsoleteRoles) {
1550 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1551 Long roleId = role.getId();
1552 List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1554 logger.debug(EELFLoggerDelegate.debugLogger,
1555 "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1556 for (FnUserRole userRole : userRoles) {
1557 logger.debug(EELFLoggerDelegate.debugLogger,
1558 "syncAppRoles: about to delete userRole: " + userRole.toString());
1559 fnUserRoleService.deleteById(userRole.getId());
1560 logger.debug(EELFLoggerDelegate.debugLogger,
1561 "syncAppRoles: finished deleting userRole: " + userRole.toString());
1563 List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1564 int numMenuRoles = funcMenuRoles.size();
1565 logger.debug(EELFLoggerDelegate.debugLogger,
1566 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1567 for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1568 Long menuId = funcMenuRole.getMenuId().getMenuId();
1569 // If this is the only role for this menu item, then the
1570 // app and roles will be gone,
1571 // so must null out the url too, to be consistent
1572 List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService
1573 .retrieveByMenuId(menuId);
1574 int numMenuRoles2 = funcMenuRoles2.size();
1575 logger.debug(EELFLoggerDelegate.debugLogger,
1576 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1577 fnMenuFunctionalRolesService.delete(funcMenuRole);
1579 if (numMenuRoles2 == 1) {
1580 // If this is the only role for this menu item, then
1581 // the app and roles will be gone,
1582 // so must null out the url too, to be consistent
1583 logger.debug(EELFLoggerDelegate.debugLogger,
1584 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1585 List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1586 if (funcMenuItems.size() > 0) {
1587 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1588 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1589 funcMenuItem.setUrl("");
1593 boolean isPortalRequest = true;
1594 deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1595 logger.debug(EELFLoggerDelegate.debugLogger,
1596 "syncAppRoles: about to delete the role: " + role.toString());
1597 fnRoleService.delete(role);
1598 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1601 for (EcompRole role : newRolesToAdd) {
1602 logger.debug(EELFLoggerDelegate.debugLogger,
1603 "syncAppRoles: about to add missing role: " + role.toString());
1604 FnRole newRole = new FnRole();
1605 // Attention! All roles from remote application supposed to be
1607 newRole.setActiveYn(true);
1608 newRole.setRoleName(role.getName());
1609 newRole.setAppId(appId);
1610 newRole.setAppRoleId(role.getId());
1611 fnRoleService.saveOne(newRole);
1613 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1614 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1615 } catch (Exception e) {
1616 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1617 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1618 throw new Exception(e);
1622 private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1624 Session localSession = entityManager.unwrap(Session.class);
1628 // It should delete only when it portal's roleId
1629 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1630 // Delete from fn_role_function
1631 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1632 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1633 query = localSession.createSQLQuery(sql);
1634 query.executeUpdate();
1635 // Delete from fn_role_composite
1636 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1637 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1638 query = localSession.createSQLQuery(sql);
1639 query.executeUpdate();
1641 // Delete from ep_app_role_function
1642 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1643 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1644 query = localSession.createSQLQuery(sql);
1645 query.executeUpdate();
1646 // Delete from ep_role_notification
1647 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1648 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1649 query = localSession.createSQLQuery(sql);
1650 query.executeUpdate();
1651 // Delete from fn_user_pseudo_role
1652 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_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_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1658 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1659 query = localSession.createSQLQuery(sql);
1660 query.executeUpdate();
1661 // Delete form EP_WIDGET_CATALOG_ROLE
1662 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1663 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1664 query = localSession.createSQLQuery(sql);
1665 query.executeUpdate();
1666 if (!isPortalRequest) {
1667 // Delete form fn_menu_functional_roles
1668 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1669 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1670 query = localSession.createSQLQuery(sql);
1671 query.executeUpdate();
1673 } catch (Exception e) {
1674 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1675 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1679 private void checkIfRoleInactive(FnRole epRole) throws Exception {
1680 if (!epRole.getActiveYn()) {
1681 throw new Exception(epRole.getRoleName() + " role is unavailable");
1685 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1686 boolean result = false;
1687 // No changes if no new roles list or no userId.
1688 if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1689 && newAppsListWithAdminRoles.getAppsRoles() != null) {
1690 synchronized (syncRests) {
1691 List<FnApp> apps = fnAppService.getAppsFullList();
1692 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1693 for (FnApp app : apps) {
1694 enabledApps.put(app.getId(), app);
1696 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1697 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1698 // user Admin role may be added only for enabled apps
1699 if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1700 newAppsWhereUserIsAdmin.add(adminRole);
1704 boolean createNewUser = false;
1705 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1706 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1707 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1708 if (localUserList.size() > 0) {
1709 FnUser tmpUser = localUserList.get(0);
1710 oldAppsWhereUserIsAdmin = fnUserRoleService
1711 .retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1712 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1715 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1716 // we create new user only if he has Admin Role for any App
1717 createNewUser = true;
1719 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1720 oldAppsWhereUserIsAdmin);
1728 public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1729 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1730 List<FnUserRole> oldAppsWhereUserIsAdmin) {
1731 if (user != null || createNewUser) {
1732 if (createNewUser) {
1733 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1735 user.setActiveYn(true);
1738 for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1739 // user Admin role may be deleted only for enabled
1741 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1742 fnUserRoleService.saveOne(oldUserApp);
1745 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1746 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1747 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1748 FnUserRole newUserApp = new FnUserRole();
1749 newUserApp.setUserId(user);
1750 newUserApp.setFnAppId(app);
1751 newUserApp.setRoleId(role);
1752 fnUserRoleService.saveOne(newUserApp);
1754 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1755 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1762 public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1763 boolean result = false;
1765 // Reset All admin role for centralized applications
1766 List<FnApp> appList = fnAppService.getCentralizedApps();
1767 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1768 for (FnApp app : appList) {
1770 if (EPCommonSystemProperties
1771 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1772 name = user.getOrgUserId() + SystemProperties
1773 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1775 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1776 HttpEntity<String> entity = new HttpEntity<>(headers);
1777 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1779 ResponseEntity<String> getResponse = template
1780 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1781 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1783 if (getResponse.getBody().equals("{}")) {
1784 String addDesc = "{\"name\":\"" + extRole + "\"}";
1785 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1787 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1789 HttpMethod.POST, roleEntity, String.class);
1792 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1794 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1795 + "userRole/" + name + "/" + extRole,
1796 HttpMethod.DELETE, deleteUserRole, String.class);
1797 } catch (Exception e) {
1798 logger.error(EELFLoggerDelegate.errorLogger,
1799 " Role not found for this user may be it gets deleted before", e);
1802 } catch (Exception e) {
1803 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1804 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1805 app.getAuthNamespace(), e.getMessage());
1807 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1808 app.getAuthNamespace(), e);
1812 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1813 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1815 if (app.getAuthCentral()) {
1816 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1817 HttpEntity<String> entity = new HttpEntity<>(headers);
1819 if (EPCommonSystemProperties
1820 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1821 name = user.getOrgUserId() + SystemProperties
1822 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1824 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1825 ResponseEntity<String> getUserRolesResponse = template.exchange(
1826 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1827 + "userRoles/user/" + name,
1828 HttpMethod.GET, entity, String.class);
1829 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1830 if (!getUserRolesResponse.getBody().equals("{}")) {
1831 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1832 JSONArray extRoles = jsonObj.getJSONArray("userRole");
1833 final Map<String, JSONObject> extUserRoles = new HashMap<>();
1834 for (int i = 0; i < extRoles.length(); i++) {
1835 String userRole = extRoles.getJSONObject(i).getString("role");
1836 if (userRole.startsWith(app.getAuthNamespace() + ".")
1837 && !userRole.equals(app.getAuthNamespace() + ".admin")
1838 && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1840 extUserRoles.put(userRole, extRoles.getJSONObject(i));
1843 if (!extUserRoles.containsKey(extRole)) {
1844 // Assign with new apps user admin
1846 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1847 // Assign user role for an application in external access system
1848 ObjectMapper addUserRoleMapper = new ObjectMapper();
1849 String userRole = addUserRoleMapper.writeValueAsString(extUser);
1850 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1852 SystemProperties.getProperty(
1853 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1854 HttpMethod.POST, addUserRole, String.class);
1855 } catch (Exception e) {
1856 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1863 } catch (Exception e) {
1864 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1865 logger.debug(EELFLoggerDelegate.errorLogger,
1866 "Application name space not found in External system for app {} due to bad rquest name space ",
1867 app.getAuthNamespace(), e.getMessage());
1869 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1870 app.getAuthNamespace(), e);
1875 } catch (Exception e) {
1877 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
1882 public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
1883 final String getAllAppsFunctionsOfUser =
1884 "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"
1885 + " where fu.role_id = ep.role_id \n"
1886 + " and fu.app_id = ep.app_id\n"
1887 + " and fu.user_id =:userId\n"
1888 + " and ea.function_cd = ep.function_cd\n"
1889 + " and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1))\n"
1890 + " and fr.role_id = fu.role_id and fr.active_yn='Y' \n"
1892 + " select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f\n"
1893 + " where role_id = 999\n"
1894 + " and app_r_f.function_cd = a_f.function_cd\n"
1897 + " 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"
1898 + " and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'\n"
1900 List getRoleFuncListOfPortal = entityManager.createNativeQuery(getAllAppsFunctionsOfUser)
1901 .setParameter("userId", OrgUserId).getResultList();
1902 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
1903 Set<String> roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
1904 .collect(Collectors.toSet());
1905 if (!roleFunSet.isEmpty()) {
1906 for (String roleFunction : roleFunSet) {
1907 String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
1908 getRoleFuncListOfPortalSet.remove(roleFunction);
1909 getRoleFuncListOfPortalSet.add(roleFun);
1913 Set<String> finalRoleFunctionSet = new HashSet<>();
1914 for (String roleFn : getRoleFuncListOfPortalSet) {
1915 finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
1918 return finalRoleFunctionSet;
1921 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
1922 AppsListWithAdminRole appsListWithAdminRole = null;
1925 List<FnUser> userList = fnUserService.getUserWithOrgUserId(orgUserId);
1926 HashMap<Long, Long> appsUserAdmin = new HashMap<>();
1927 if (userList != null && userList.size() > 0) {
1928 FnUser user = userList.get(0);
1929 List<FnUserRole> userAppList = new ArrayList<>();
1931 userAppList = fnUserRoleService.retrieveByUserIdAndRoleId(user.getId(), ACCOUNT_ADMIN_ROLE_ID);
1932 } catch (Exception e) {
1933 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
1934 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
1936 for (FnUserRole userApp : userAppList) {
1937 appsUserAdmin.put(userApp.getFnAppId().getId(), userApp.getUserId().getId());
1941 appsListWithAdminRole = new AppsListWithAdminRole();
1942 appsListWithAdminRole.setOrgUserId(orgUserId);
1943 List<FnApp> appsList = new ArrayList<>();
1945 appsList = fnAppService.findAll();
1946 } catch (Exception e) {
1947 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
1948 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
1950 for (FnApp app : appsList) {
1951 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
1952 appNameIdIsAdmin.setId(app.getId());
1953 appNameIdIsAdmin.setAppName(app.getAppName());
1954 appNameIdIsAdmin.setIsAdmin(appsUserAdmin.containsKey(app.getId()));
1955 appNameIdIsAdmin.setRestrictedApp(app.isRestrictedApp());
1956 appsListWithAdminRole.getAppsRoles().add(appNameIdIsAdmin);
1958 } catch (Exception e) {
1959 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
1961 return appsListWithAdminRole;
1964 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser,
1966 boolean result = false;
1967 boolean externalSystemRequest = true;
1968 List<FnUser> userInfo = null;
1970 List<EpUserRolesRequest> epRequestId = null;
1971 String orgUserId = "";
1972 String updateStatus = "";
1973 String reqMessage = "";
1975 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1976 orgUserId = newAppRolesForUser.getLoginId().trim();
1978 String appName = newAppRolesForUser.getApplicationName();
1979 String logMessage = ("DELETE").equals(reqType) ? "Deleting" : "Assigning/Updating";
1980 if (orgUserId.length() > 0) {
1981 ObjectMapper mapper = new ObjectMapper();
1982 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1983 int epRequestIdSize = 0;
1985 app = fnAppService.getAppDetail(appName);
1986 userInfo = checkIfUserExists(orgUserId);
1987 reqMessage = "Updated Successfully";
1988 if (!reqType.equals("DELETE") && (userInfo.isEmpty())) {
1989 reqMessage = validateNewUser(orgUserId, app);
1991 if (!userInfo.isEmpty()) {
1992 validateExternalRequestFields(app);
1993 user = userInfo.get(0);
1994 epRequestId = epUserRolesRequestService.userAppRolesRequestList(user.getId(), app.getId());
1995 epRequestIdSize = epRequestId.size();
1997 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getAuthCentral()) {
1998 logger.debug(EELFLoggerDelegate.debugLogger,
1999 "setExternalRequestUserAppRole: Starting GET roles for app {}", app.getId());
2000 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
2001 logger.debug(EELFLoggerDelegate.debugLogger,
2002 "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}", app.getId(),
2004 if (appRoles.length > 0) {
2005 syncAppRoles(app.getId(), appRoles);
2008 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
2009 app.getId(), app.getMlAppName());
2010 List<EcompUserAppRoles> userRoleList = null;
2011 if (!userInfo.isEmpty()) {
2012 userRoleList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
2014 // Check if list contains just account admin role
2015 boolean checkIfAdminRoleExists = false;
2016 if (reqType.equals("DELETE") && userRoleList != null) {
2017 checkIfAdminRoleExists = userRoleList.stream()
2018 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
2020 checkIfAdminRoleExists = roleInAppForUserList.stream()
2021 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
2023 if (app.getAuthCentral()) {
2025 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
2026 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
2027 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
2028 List<RoleInAppForUser> remoteUserRoles = new ArrayList<>(roleInAppForUserList);
2029 remoteUserRoles.removeIf(role -> {
2030 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
2032 String orgUserIdNewOrExist = (!userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
2033 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist, app, mapper,
2034 applicationsRestClientService, true);
2036 } catch (Exception e) {
2037 reqMessage = e.getMessage();
2038 logger.error(EELFLoggerDelegate.errorLogger,
2039 "setExternalRequestUserAppRole: Failed to added remote user", e);
2040 throw new Exception(reqMessage);
2042 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
2043 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2044 userRolesInLocalApp);
2045 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
2046 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2047 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2048 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), roleAppUserList,
2049 externalSystemRequest, false, rolesGotDeletedByApprover, false);
2051 logger.info(EELFLoggerDelegate.debugLogger,
2052 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
2053 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
2054 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,
2055 false, rolesGotDeletedByApprover, false);
2056 } else if (!app.getAuthCentral() && app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2057 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
2058 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2059 userRolesInLocalApp);
2060 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2062 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,
2063 false, rolesGotDeletedByApprover, false);
2065 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
2066 FnUser remoteAppUser = null;
2067 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
2068 if (remoteAppUser == null) {
2069 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper,
2070 applicationsRestClientService);
2071 reqMessage = "Saved Successfully";
2073 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
2074 applicationsRestClientService, app.getId(), orgUserId);
2075 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2076 userRolesInRemoteApp);
2077 logger.info(EELFLoggerDelegate.debugLogger,
2078 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
2079 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
2080 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2081 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
2082 reqType, false, rolesGotDeletedByApprover, false);
2084 if (!(reqType.equals("DELETE")) && userInfo.isEmpty()) {
2085 reqMessage = "Saved Successfully";
2087 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
2088 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2089 userRolesInRemoteApp);
2090 logger.info(EELFLoggerDelegate.debugLogger,
2091 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
2092 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
2093 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2094 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
2095 reqType, false, rolesGotDeletedByApprover, false);
2098 reqMessage = "Failed to save the user app role(s)";
2100 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
2102 applyChangesToAppRolesRequest(user.getId(), updateStatus, epRequestId.get(0));
2105 } catch (Exception e) {
2106 String message = String.format(
2107 "setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
2108 orgUserId, appName);
2109 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2111 reqMessage = e.getMessage();
2112 if (epRequestIdSize > 0 && userInfo != null && !userInfo.isEmpty()) {
2114 applyChangesToAppRolesRequest(user.getId(),
2115 updateStatus, epRequestId.get(0));
2119 return new ExternalRequestFieldsValidator(result, reqMessage);
2122 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
2123 return constructUsersEcompRoles(roleInAppForUserList);
2126 private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
2127 Set<EcompRole> existingUserRoles = new TreeSet<>();
2128 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
2129 if (roleInAppForUser.getIsApplied()) {
2130 EcompRole ecompRole = new EcompRole();
2131 ecompRole.setId(roleInAppForUser.getRoleId());
2132 ecompRole.setName(roleInAppForUser.getRoleName());
2133 existingUserRoles.add(ecompRole);
2136 return existingUserRoles;
2139 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
2140 Long appId, String appName) throws Exception {
2141 List<RoleInAppForUser> existingUserRoles = new ArrayList<>();
2142 List<FnRole> existingAppRole;
2143 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
2144 RoleInAppForUser ecompRole = new RoleInAppForUser();
2145 existingAppRole = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(roleInAppForUser.getRoleName(), appId);
2146 if (existingAppRole.isEmpty()) {
2147 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
2148 roleInAppForUserList);
2149 throw new Exception("'" + roleInAppForUser.getRoleName() + "'" + " role does not exist for " + appName
2152 if (!existingAppRole.get(0).getActiveYn()) {
2153 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
2154 roleInAppForUserList);
2155 throw new Exception(
2156 roleInAppForUser.getRoleName() + " role is unavailable for " + appName + " application");
2159 List<FnRole> roleInfo = externalAccessRolesService
2160 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
2161 FnRole adminRole = new FnRole();
2162 if (roleInfo.size() > 0) {
2163 adminRole = roleInfo.get(0);
2164 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
2166 ecompRole.setRoleId(
2167 (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getRoleName())) ? existingAppRole
2169 .getId() : existingAppRole.get(0).getAppRoleId());
2170 ecompRole.setRoleName(roleInAppForUser.getRoleName());
2171 ecompRole.setIsApplied(true);
2172 existingUserRoles.add(ecompRole);
2175 return existingUserRoles;
2178 private void validateExternalRequestFields(FnApp app) throws Exception {
2180 throw new Exception("Application does not exist");
2181 } else if (!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2182 throw new Exception(app.getMlAppName() + " application is unavailable");
2186 private String validateNewUser(String orgUserId, FnApp app) throws Exception {
2187 FnUser epUser = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
2188 if (epUser == null) {
2189 throw new Exception("User does not exist");
2190 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
2191 throw new Exception("User does not exist");
2192 } else if (app == null) {
2193 throw new Exception("Application does not exist");
2195 return "Saved Successfully";
2198 private void applyChangesToAppRolesRequest(final Long userId, final String updateStatus,
2199 final EpUserRolesRequest epUserAppRolesRequest) {
2201 epUserAppRolesRequest.setUpdatedDate(LocalDateTime.now());
2202 epUserAppRolesRequest.setRequestStatus(updateStatus);
2203 epUserAppRolesRequest.setUserId(fnUserService.getUser(userId).get());
2204 epUserRolesRequestService.saveOne(epUserAppRolesRequest);
2205 List<EpUserRolesRequestDet> epUserAppRolessDetailList = epUserRolesRequestDetService
2206 .appRolesRequestDetailList(epUserAppRolesRequest.getReqId());
2207 if (epUserAppRolessDetailList.size() > 0) {
2208 for (EpUserRolesRequestDet epRequestUpdateData : epUserAppRolessDetailList) {
2209 epRequestUpdateData.setRequestType(updateStatus);
2210 epRequestUpdateData.setReqId(epUserAppRolesRequest);
2211 epRequestUpdateData.setReqId(epUserAppRolesRequest);
2212 epUserRolesRequestDetService.saveOne(epRequestUpdateData);
2215 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
2216 } catch (Exception e) {
2217 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);