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.ecomp.EPUserAppRolesRequest;
82 import org.onap.portal.domain.dto.model.ExternalSystemRoleApproval;
83 import org.onap.portal.domain.dto.model.ExternalSystemUser;
84 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
85 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
86 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
87 import org.onap.portal.domain.dto.transport.CentralV2Role;
88 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
89 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
90 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
91 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
92 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
93 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
94 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
95 import org.onap.portal.domain.dto.transport.Role;
96 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
97 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
98 import org.onap.portal.exception.DeleteDomainObjectFailedException;
99 import org.onap.portal.exception.RoleFunctionException;
100 import org.onap.portal.exception.SyncUserRolesException;
101 import org.onap.portal.logging.format.EPAppMessagesEnum;
102 import org.onap.portal.logging.logic.EPLogUtil;
103 import org.onap.portal.service.app.FnAppService;
104 import org.onap.portal.service.appFunction.EpAppFunctionService;
105 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
106 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
107 import org.onap.portal.service.role.FnRoleService;
108 import org.onap.portal.service.roleFunction.FnRoleFunctionService;
109 import org.onap.portal.service.user.FnUserService;
110 import org.onap.portal.service.userRole.FnUserRoleService;
111 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
112 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
113 import org.onap.portal.utils.EPCommonSystemProperties;
114 import org.onap.portal.utils.EPUserUtils;
115 import org.onap.portal.utils.EcompPortalUtils;
116 import org.onap.portal.utils.PortalConstants;
117 import org.onap.portalsdk.core.domain.RoleFunction;
118 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
119 import org.onap.portalsdk.core.restful.domain.EcompRole;
120 import org.onap.portalsdk.core.util.SystemProperties;
121 import org.springframework.beans.factory.annotation.Autowired;
122 import org.springframework.http.HttpEntity;
123 import org.springframework.http.HttpHeaders;
124 import org.springframework.http.HttpMethod;
125 import org.springframework.http.HttpStatus;
126 import org.springframework.http.ResponseEntity;
127 import org.springframework.stereotype.Service;
128 import org.springframework.transaction.annotation.Transactional;
129 import org.springframework.web.client.HttpClientErrorException;
130 import org.springframework.web.client.RestTemplate;
134 public class AdminRolesService {
136 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
137 private static final Object syncRests = new Object();
138 private final RestTemplate template = new RestTemplate();
140 private Long SYS_ADMIN_ROLE_ID = 38L;
141 private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
142 private final Long ECOMP_APP_ID = 1L;
143 private final String ADMIN_ACCOUNT = "Is account admin for user {}";
145 private final AppsCacheService appsCacheService;
146 private final EntityManager entityManager;
147 private final FnUserService fnUserService;
148 private final FnRoleService fnRoleService;
149 private final FnAppService fnAppService;
150 private final FnRoleFunctionService fnRoleFunctionService;
151 private final FnMenuFunctionalService fnMenuFunctionalService;
152 private final FnUserRoleService fnUserRoleService;
153 private final EpAppFunctionService epAppFunctionService;
154 private final EcompUserAppRolesService ecompUserAppRolesService;
155 private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
156 private final ApplicationsRestClientService applicationsRestClientService;
157 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
158 private final ExternalAccessRolesService externalAccessRolesService;
159 private final EpUserRolesRequestService epUserRolesRequestService;
162 public AdminRolesService(AppsCacheService appsCacheService,
163 final EntityManager entityManager,
164 final FnUserService fnUserService, FnRoleService fnRoleService,
165 FnAppService fnAppService,
166 FnRoleFunctionService fnRoleFunctionService, FnMenuFunctionalService fnMenuFunctionalService,
167 final FnUserRoleService fnUserRoleService,
168 EpAppFunctionService epAppFunctionService,
169 EcompUserAppRolesService ecompUserAppRolesService,
170 FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
171 ApplicationsRestClientService applicationsRestClientService,
172 EpUserRolesRequestDetService epUserRolesRequestDetService,
173 ExternalAccessRolesService externalAccessRolesService,
174 EpUserRolesRequestService epUserRolesRequestService) {
175 this.appsCacheService = appsCacheService;
176 this.entityManager = entityManager;
177 this.fnUserService = fnUserService;
178 this.fnRoleService = fnRoleService;
179 this.fnAppService = fnAppService;
180 this.fnRoleFunctionService = fnRoleFunctionService;
181 this.fnMenuFunctionalService = fnMenuFunctionalService;
182 this.fnUserRoleService = fnUserRoleService;
183 this.epAppFunctionService = epAppFunctionService;
184 this.ecompUserAppRolesService = ecompUserAppRolesService;
185 this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
186 this.applicationsRestClientService = applicationsRestClientService;
187 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
188 this.externalAccessRolesService = externalAccessRolesService;
189 this.epUserRolesRequestService = epUserRolesRequestService;
192 public boolean isSuperAdmin(final String loginId) {
193 boolean isSuperAdmin;
195 isSuperAdmin = fnUserRoleService
196 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
197 } catch (Exception e) {
198 logger.error("isSuperAdmin exception: " + e.toString());
201 logger.info("isSuperAdmin " + isSuperAdmin);
205 public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
207 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
208 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
209 logger.debug(EELFLoggerDelegate.debugLogger,
210 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
211 orgUserId, userAdminApps.size());
213 for (FnUserRole userApp : userApps) {
214 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
215 userAdminApps.size() > 1)) {
216 logger.debug(EELFLoggerDelegate.debugLogger,
217 "Is account admin for userAdminApps() - for user {}, found Id {}",
218 orgUserId, userApp.getRoleId().getId());
222 } catch (Exception e) {
223 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
224 logger.error(EELFLoggerDelegate.errorLogger,
225 "Exception occurred while executing isAccountAdmin operation",
231 public boolean isUser(final long userId) {
233 FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
234 if (currentUser != null && currentUser.getId() != null) {
235 for (FnUserRole userApp : currentUser.getUserApps()) {
236 if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
237 FnRole role = userApp.getRoleId();
238 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
239 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
240 if (role.getActiveYn()) {
247 } catch (Exception e) {
248 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
249 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
255 public boolean isRoleAdmin(Long userId) {
257 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
258 List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
259 logger.debug(EELFLoggerDelegate.debugLogger,
260 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
261 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
262 Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
263 Set<String> roleFunSet;
264 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
265 .collect(Collectors.toSet());
266 if (!roleFunSet.isEmpty()) {
267 for (String roleFunction : roleFunSet) {
268 String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
269 getRoleFuncListOfPortalSet1.add(type);
273 boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
274 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
275 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
276 checkIfFunctionsExits);
278 return checkIfFunctionsExits;
280 } catch (Exception e) {
281 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
282 logger.error(EELFLoggerDelegate.errorLogger,
283 "Exception occurred while executing isRoleAdmin operation",
289 private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
290 boolean isApplicationAccountAdmin = false;
292 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
293 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
294 if (!userAdminApps.isEmpty()) {
295 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
296 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
299 } catch (Exception e) {
300 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
301 logger.error(EELFLoggerDelegate.errorLogger,
302 "Exception occurred while executing isAccountAdminOfApplication operation", e);
304 logger.debug(EELFLoggerDelegate.debugLogger,
305 "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
307 return isApplicationAccountAdmin;
311 private List<Integer> getAdminAppsForTheUser(final Long userId) {
312 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)";
313 return entityManager.createQuery(query, Integer.class)
314 .setParameter("userId", userId).getResultList();
317 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
318 AppWithRolesForUser newAppRolesForUser) {
319 boolean result = false;
320 boolean epRequestValue = false;
322 String reqMessage = "";
323 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
324 userId = newAppRolesForUser.getOrgUserId().trim();
326 Long appId = newAppRolesForUser.getAppId();
327 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
329 if (userId.length() > 0) {
330 ObjectMapper mapper = new ObjectMapper();
331 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
334 FnApp app = fnAppService.getById(appId);
336 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
338 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
340 boolean checkIfUserIsOnlyRoleAdmin =
341 isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
342 if (checkIfUserIsOnlyRoleAdmin) {
343 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
344 if (!roleInAppForUser.getIsApplied()) {
345 EcompRole ecompRole = new EcompRole();
346 ecompRole.setId(roleInAppForUser.getRoleId());
347 ecompRole.setName(roleInAppForUser.getRoleName());
348 rolesGotDeletedFromApprover.add(ecompRole);
353 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
355 boolean systemUser = newAppRolesForUser.isSystemUser();
357 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
360 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
361 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
362 userRolesInLocalApp);
363 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
364 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
365 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
366 // Apply changes in external Access system
368 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
370 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
372 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
374 systemUser, rolesGotDeletedByApprover, false);
376 } else if (!app.getAuthCentral() && systemUser) {
377 throw new Exception("For non-centralized application we cannot add systemUser");
378 } else { // if centralized app
379 if (app.getAuthCentral()) {
380 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
381 pushRemoteUser(roleInAppForUserList, userId, app, mapper,
382 applicationsRestClientService, false);
385 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
386 roleInAppForUserList);
387 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
389 userRolesInLocalApp);
390 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
391 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
393 // Apply changes in external Access system
394 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
396 epRequestValue, false, rolesGotDeletedFromApprover,
397 checkIfUserIsOnlyRoleAdmin);
399 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
400 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
401 checkIfUserIsOnlyRoleAdmin);
403 // In case if portal is not centralized then follow existing approach
404 else if (!app.getAuthCentral() && app.getId()
405 .equals(PortalConstants.PORTAL_APP_ID)) {
406 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
407 roleInAppForUserList);
408 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
410 userRolesInLocalApp);
411 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
412 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
413 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
414 } else {// remote app
415 FnUser remoteAppUser;
416 if (!app.getAuthCentral() && !app.getId()
417 .equals(PortalConstants.PORTAL_APP_ID)) {
419 remoteAppUser = checkIfRemoteUserExits(userId, app,
420 applicationsRestClientService);
422 if (remoteAppUser == null) {
423 addRemoteUser(roleInAppForUserList, userId, app,
424 mapper, applicationsRestClientService);
426 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
427 roleInAppForUserList, mapper,
428 applicationsRestClientService, appId, userId);
429 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
431 userRolesInRemoteApp);
432 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
433 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
434 epRequestValue, null, false, rolesGotDeletedByApprover, false);
436 // If no roles remain, request app to set user inactive.
437 if (userRolesInRemoteApp.size() == 0) {
438 logger.debug(EELFLoggerDelegate.debugLogger,
439 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
442 postUserToRemoteApp(userId, app,
443 applicationsRestClientService);
448 } catch (Exception e) {
449 String message = String.format(
450 "Failed to create user or update user roles for User %s, AppId %s",
451 userId, Long.toString(appId));
452 logger.error(EELFLoggerDelegate.errorLogger, message, e);
454 reqMessage = e.getMessage();
457 return new ExternalRequestFieldsValidator(result, reqMessage);
461 private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
462 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
464 pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
465 roleInAppForUserList, appRoleIdUsed);
469 private void postUserToRemoteApp(String userId, FnApp app,
470 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
472 getUser(userId, app, applicationsRestClientService);
476 private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
477 throws HTTPException {
478 return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
482 private void pushUserOnRemoteApp(String userId, FnApp app,
483 ApplicationsRestClientService applicationsRestClientService,
484 ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
488 client = fnUserService.loadUserByUsername(userId);
490 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
491 if (client == null) {
492 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
493 logger.error(EELFLoggerDelegate.errorLogger, msg);
494 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
495 if (!userList.isEmpty()) {
496 logger.debug(EELFLoggerDelegate.debugLogger,
497 userList.get(0).getOrgUserId() + " User was found in Portal");
498 client = userList.get(0);
499 client.setUserApps(Collections.EMPTY_SET);
500 client.setIsSystemUser(false);
502 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
503 throw new Exception(msg);
508 client.setLoginId(userId);
509 client.setActiveYn(true);
510 client.setOrgUserId(userId);
512 roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
513 SortedSet<Role> roles = new TreeSet<>();
515 List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
516 List<FnApp> appList = new ArrayList<>();
518 List<CentralV2Role> roleList = new ArrayList<>();
520 List<FnRole> userRoles = new ArrayList<>();
522 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
523 FnRole role = new FnRole();
524 role.setId(roleInappForUser.getRoleId());
525 role.setRoleName(roleInappForUser.getRoleName());
530 List<FnRole> userAppRoles = new ArrayList<>();
531 for (FnRole role : userRoles) {
532 FnRole appRole = getAppRoles.stream()
533 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
535 FnRole epRole = new FnRole();
536 if (appRole != null) {
537 epRole.setId(appRole.getId());
538 epRole.setRoleName(appRole.getRoleName());
540 userAppRoles.add(epRole);
542 userRoles = new ArrayList<>(userAppRoles);
544 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
546 for (CentralV2Role epRole : roleList) {
547 Role role = new Role();
548 FnRole appRole = getAppRoles.stream()
549 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
550 List<FnRoleFunction> fnRoleFunctions = new ArrayList<>();
551 for (DomainVo vo : epRole.getRoleFunctions()) {
552 Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
553 roleFunction.ifPresent(fnRoleFunctions::add);
555 if (appRole != null) {
556 role.setId(appRole.getAppRoleId());
557 role.setRoleName(epRole.getName());
558 role.setFnRoleFunctions(new HashSet<>(fnRoleFunctions));
562 client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
564 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
565 logger.debug(EELFLoggerDelegate.debugLogger,
566 "about to post a client to remote application, users json = " + userInString);
567 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
570 private FnRole roleToFnRole(Role role) {
571 return FnRole.builder()
573 .roleName(role.getRoleName())
574 .activeYn(role.getActiveYn())
575 .priority(role.getPriority())
576 .fnRoleFunctions(role.getFnRoleFunctions())
577 .childRoles(role.getChildRoles())
578 .parentRoles(role.getParentRoles())
582 private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
583 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
584 throws JsonProcessingException, HTTPException {
585 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
586 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
587 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
589 externalApp = appsCacheService.getApp(appId);
590 String appBaseUri = null;
591 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
592 if (externalApp != null) {
593 appBaseUri = externalApp.getAppRestEndpoint();
595 if (appBaseUri != null && appBaseUri.endsWith("/api")) {
596 for (EcompRole eprole : updatedUserRolesinRemote) {
597 RemoteRoleV1 role = new RemoteRoleV1();
598 role.setId(eprole.getId());
599 role.setName(eprole.getName());
600 updatedUserRolesinRemoteV1.add(role);
602 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
604 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
605 String.format("/user/%s/roles", userId));
606 return updateUserRolesInEcomp;
609 private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
610 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
611 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
612 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
616 private void createNewUserOnRemoteApp(String userId, FnApp app,
617 ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
620 FnUser client = fnUserService.loadUserByUsername(userId);
622 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
624 if (client == null) {
625 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
626 logger.error(EELFLoggerDelegate.errorLogger, msg);
627 throw new Exception(msg);
630 client.setLoginId(userId);
631 client.setActiveYn(true);
634 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
635 logger.debug(EELFLoggerDelegate.debugLogger,
636 "about to post new client to remote application, users json = " + userInString);
637 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
641 private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
642 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
643 if (roleInAppForUser.getIsApplied()) {
650 private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
651 Set<EcompRole> existingUserRoles = new TreeSet<>();
652 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
653 if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
654 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
655 EcompRole ecompRole = new EcompRole();
656 ecompRole.setId(roleInAppForUser.getRoleId());
657 ecompRole.setName(roleInAppForUser.getRoleName());
658 existingUserRoles.add(ecompRole);
661 return existingUserRoles;
664 private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
665 List<EpUserRolesRequest> epRequestIdVal;
667 epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
668 if (epRequestIdVal.size() > 0) {
669 EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
670 epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
671 epAppRolesRequestData.setRequestStatus("O");
672 epAppRolesRequestData.setUserId(user);
673 epUserRolesRequestService.saveOne(epAppRolesRequestData);
674 List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
675 .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
676 if (epUserAppRolesDetailList.size() > 0) {
677 for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
678 epRequestUpdateList.setRequestType("O");
679 epRequestUpdateList.setReqId(epAppRolesRequestData);
680 epRequestUpdateList.setReqId(epAppRolesRequestData);
681 epUserRolesRequestDetService.saveOne(epRequestUpdateList);
683 logger.debug(EELFLoggerDelegate.debugLogger,
684 "User App roles request from User Page is overridden");
688 } catch (Exception e) {
689 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
693 public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
694 Set<EcompRole> userRolesInRemoteApp) {
695 RolesInAppForUser result;
696 result = new RolesInAppForUser();
697 result.setAppId(appId);
698 result.setOrgUserId(userId);
700 for (EcompRole role : userRolesInRemoteApp) {
701 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
702 roleInAppForUser.setRoleId(role.getId());
703 roleInAppForUser.setRoleName(role.getName());
704 roleInAppForUser.setIsApplied(true);
705 result.getRoles().add(roleInAppForUser);
710 private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
711 boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
712 boolean isLoggedInUserRoleAdminofApp) throws Exception {
714 List<FnUser> userInfo = checkIfUserExists(orgUserId);
715 if (userInfo.isEmpty()) {
716 createLocalUserIfNecessary(orgUserId, isSystemUser);
719 if (EPCommonSystemProperties
720 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
724 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
728 ObjectMapper mapper = new ObjectMapper();
729 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
730 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
731 ResponseEntity<String> getResponse = externalAccessRolesService
732 .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
734 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
735 String res = getResponse.getBody();
737 JSONArray extRoles = null;
738 if (!res.equals("{}")) {
739 jsonObj = new JSONObject(res);
740 extRoles = jsonObj.getJSONArray("role");
742 ExternalAccessUserRoleDetail userRoleDetail;
743 if (extRoles != null) {
744 for (int i = 0; i < extRoles.length(); i++) {
745 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
746 && !extRoles.getJSONObject(i).getString("name")
747 .equals(app.getAuthNamespace() + ".admin")
748 && !extRoles.getJSONObject(i).getString("name")
749 .equals(app.getAuthNamespace() + ".owner")) {
750 if (extRoles.getJSONObject(i).has("description")) {
751 ExternalRoleDescription desc = new ExternalRoleDescription(
752 extRoles.getJSONObject(i).getString("description"));
753 userRoleDetail = new ExternalAccessUserRoleDetail(
754 extRoles.getJSONObject(i).getString("name"), desc);
755 userRoleDetailList.add(userRoleDetail);
757 userRoleDetail = new ExternalAccessUserRoleDetail(
758 extRoles.getJSONObject(i).getString("name"), null);
759 userRoleDetailList.add(userRoleDetail);
766 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
767 userRoleDetailList, app);
769 List<EcompUserAppRoles> userAppList;
770 // If request coming from portal not from external role approval system then we have to check if user already
771 // have account admin or system admin as GUI will not send these roles
772 if (!isPortalRequest) {
773 FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
774 userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
775 if (!roleInAppUser.isEmpty()) {
776 for (EcompUserAppRoles userApp : userAppList) {
777 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
778 || userApp.getRoleId()
779 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
780 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
781 addSpecialRole.setIsApplied(true);
782 addSpecialRole.setRoleId(userApp.getRoleId());
783 addSpecialRole.setRoleName(userApp.getRoleName());
784 roleInAppUser.add(addSpecialRole);
789 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
790 .collect(Collectors.toList());
791 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
792 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
793 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
794 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
795 "_"), roleInAppUserNew);
797 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
798 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
799 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
802 if (isLoggedInUserRoleAdminofApp) {
803 if (deletedRolesByApprover.size() > 0) {
804 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
805 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
806 for (EcompRole role : deletedRolesByApprover) {
807 if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
808 .equals(role.getName())) {
809 newUpdatedRoles.add(userRole);
813 if (newUpdatedRoles.size() > 0) {
814 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
816 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
817 currentUserRolesToUpdate = new HashMap<>();
822 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
823 currentUserRolesToUpdate = new HashMap<>();
828 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
829 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
830 if (!(currentUserRolesToUpdate
831 .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
832 HttpEntity<String> entity = new HttpEntity<>(headers);
833 logger.debug(EELFLoggerDelegate.debugLogger,
834 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
836 ResponseEntity<String> deleteResponse = template.exchange(
838 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
839 + "userRole/" + name + "/" + userRole.getName(),
840 HttpMethod.DELETE, entity, String.class);
841 logger.debug(EELFLoggerDelegate.debugLogger,
842 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
843 userRole.getName(), deleteResponse.getBody());
846 // Check if user roles does not exists in External Central Auth System add them all
847 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
848 if (!(currentUserRolesInExternalSystem
849 .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
850 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
852 ExternalAccessUser extUser = new ExternalAccessUser(name,
853 app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
854 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
856 String formattedUserRole = mapper.writeValueAsString(extUser);
857 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
858 logger.debug(EELFLoggerDelegate.debugLogger,
859 "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
860 name, addUserRole.getRoleName());
861 ResponseEntity<String> addResponse = template
862 .exchange(SystemProperties
863 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
864 + "userRole", HttpMethod.POST, entity, String.class);
865 logger.debug(EELFLoggerDelegate.debugLogger,
866 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
867 addResponse.getBody(), addUserRole.getRoleName());
868 if (addResponse.getStatusCode().value() != 201
869 && addResponse.getStatusCode().value() != 404) {
870 logger.debug(EELFLoggerDelegate.debugLogger,
871 "Finished POST operation in external system but unable to save user role",
872 addResponse.getBody(),
873 addUserRole.getRoleName());
874 throw new Exception(addResponse.getBody());
878 } catch (HttpClientErrorException e) {
879 logger.error(EELFLoggerDelegate.errorLogger,
880 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
882 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
883 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
885 throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
886 "Please enter the valid systemUser");
888 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
889 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
890 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
892 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
894 } catch (Exception e) {
895 logger.error(EELFLoggerDelegate.errorLogger,
896 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
898 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
903 private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
904 List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
905 Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
906 //Add Account Admin role for partner app to prevent conflict
907 if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
908 FnRole role = new FnRole();
909 role.setRoleName(PortalConstants.ADMIN_ROLE
910 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
911 epRoleList.put(role.getRoleName(), role);
913 userRoleDetailList.removeIf(
914 userRoleDetail -> !epRoleList
915 .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
916 return userRoleDetailList;
919 private List<FnUser> checkIfUserExists(String userParams) {
920 return fnUserService.getUserWithOrgUserId(userParams);
924 private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
925 if (StringUtils.isEmpty(userId)) {
926 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
930 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
931 if (userList.size() == 0) {
934 client = fnUserService.loadUserByUsername(userId);
936 client = new FnUser();
937 client.setOrgUserId(userId);
938 client.setIsSystemUser(true);
939 client.setFirstName(userId.substring(0, userId.indexOf("@")));
941 if (client == null) {
942 String msg = "createLocalUserIfNecessary: cannot create user " + userId
943 + ", because not found in phonebook";
944 logger.error(EELFLoggerDelegate.errorLogger, msg);
946 client.setLoginId(userId);
947 client.setActiveYn(true);
949 fnUserService.saveFnUser(client);
951 } catch (Exception e) {
952 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
957 private FnUser checkIfRemoteUserExits(String userId, FnApp app,
958 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
959 FnUser checkRemoteUser = null;
961 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
962 } catch (HTTPException e) {
963 // Some apps are returning 400 if user is not found.
964 if (e.getResponseCode() == 400) {
965 logger.debug(EELFLoggerDelegate.debugLogger,
966 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
968 } else if (e.getResponseCode() == 404) {
969 logger.debug(EELFLoggerDelegate.debugLogger,
970 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
973 // Other response code, let it come thru.
977 return checkRemoteUser;
980 private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
981 throws HTTPException {
982 if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
983 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
984 if (userList != null && !userList.isEmpty()) {
985 return userList.get(0);
990 return getUser(userId, app, applicationsRestClientService);
993 private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
994 boolean externalSystemRequest, String reqType, boolean isSystemUser,
995 Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
996 boolean result = false;
997 String userId = rolesInAppForUser.getOrgUserId();
998 Long appId = rolesInAppForUser.getAppId();
999 synchronized (syncRests) {
1000 createLocalUserIfNecessary(userId, isSystemUser);
1002 EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1004 i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1005 RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1006 EcompRole role = new EcompRole();
1007 role.setId(roleInAppForUser.getRoleId());
1008 role.setName(roleInAppForUser.getRoleName());
1009 userAppRoles[i] = role;
1012 EcompRole[] applicationRoles = null;
1014 if (isLoggedInUserRoleAdminOfApp) {
1015 List<EcompRole> roles = Arrays.stream(userAppRoles)
1016 .collect(Collectors.toList());
1017 List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1018 roles.addAll(roles1);
1019 applicationRoles = roles.toArray(new EcompRole[0]);
1022 syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1023 reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1025 } catch (Exception e) {
1026 logger.error(EELFLoggerDelegate.errorLogger,
1027 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1029 if ("DELETE".equals(reqType)) {
1030 throw new Exception(e.getMessage());
1037 private void syncUserRoles(String userId, Long appId,
1038 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1039 EcompRole[] appRoles) throws Exception {
1041 Transaction transaction = null;
1043 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1044 List<FnRole> roleInfo = externalAccessRolesService
1045 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1046 FnRole adminRole = new FnRole();
1047 if (roleInfo.size() > 0) {
1048 adminRole = roleInfo.get(0);
1049 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1052 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1053 if (userList.size() > 0) {
1054 FnUser client = userList.get(0);
1055 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1056 List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1058 .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1059 .setParameter("appId", appId)
1060 .setParameter("userId", client.getId())
1063 if ("DELETE".equals(reqType)) {
1064 for (FnUserRole userAppRoleList : userRoles) {
1065 List<FnRole> rolesList =
1066 (!userAppRoleList.getRoleId().getRoleName()
1067 .equals(adminRole.getRoleName()))
1068 ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1069 (userAppRoleList.getRoleId().getRoleName(), appId)
1070 : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1071 if (!rolesList.isEmpty()) {
1072 checkIfRoleInactive(rolesList.get(0));
1077 if (appRoles != null) {
1078 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1079 List<FnUserRole> finalUserRolesList = new ArrayList<>();
1080 if (checkIfUserisRoleAdmin) {
1081 for (EcompRole role : appRolesList) {
1082 for (FnUserRole userAppRoleList : userRoles) {
1083 if (userAppRoleList.getRoleId().getRoleName()
1084 .equals(role.getName())) {
1085 finalUserRolesList.add(userAppRoleList);
1090 userRoles = new ArrayList<>(finalUserRolesList);
1094 for (FnUserRole userRole : userRoles) {
1095 if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1096 && !PortalConstants.SYS_ADMIN_ROLE_ID
1097 .equals(userRole.getRoleId().getId())
1098 && !extRequestValue) {
1099 syncUserRolesExtension(userRole, appId,
1100 newUserAppRolesMap);
1101 } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1102 || "DELETE".equals(reqType))) {
1103 syncUserRolesExtension(userRole, appId,
1104 newUserAppRolesMap);
1105 } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1106 .equals(userRole.getRoleId().getId())) {
1107 syncUserRolesExtension(userRole, appId,
1108 newUserAppRolesMap);
1112 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1113 if (newRolesToAdd.size() > 0) {
1114 FnApp app = fnAppService.getById(appId);
1116 HashMap<Long, FnRole> rolesMap = new HashMap<>();
1117 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1118 String appIdValue = "";
1119 if (!extRequestValue) {
1120 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1122 @SuppressWarnings("unchecked")
1123 List<FnRole> roles = entityManager
1125 "from " + FnRole.class.getName() + " where appId is null "
1126 + appIdValue).getResultList();
1127 for (FnRole role : roles) {
1129 rolesMap.put(role.getId(), role);
1131 } else { // remote app
1132 @SuppressWarnings("unchecked")
1133 List<FnRole> roles = entityManager
1134 .createQuery("from EPRole where appId=:appId")
1135 .setParameter("appId", appId)
1137 for (FnRole role : roles) {
1138 if (!extRequestValue && app.getAuthCentral()) {
1139 rolesMap.put(role.getId(), role);
1141 rolesMap.put(role.getAppRoleId(), role);
1147 for (EcompRole userRole : newRolesToAdd) {
1148 FnUserRole userApp = new FnUserRole();
1149 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1150 .equals(adminRole.getRoleName())) {
1151 role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1152 userApp.setRoleId(role);
1153 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1154 && !extRequestValue) {
1156 } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1157 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1160 userApp.setRoleId(rolesMap.get(userRole.getId()));
1163 userApp.setUserId(client);
1164 userApp.setFnAppId(app);
1165 fnUserRoleService.saveOne(userApp);
1168 if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1170 * for local app -- hack - always make sure fn_role
1171 * table's app_id is null and not 1 for primary app in
1172 * this case being onap portal app; reason: hibernate
1173 * is rightly setting this to 1 while persisting to
1174 * fn_role as per the mapping but SDK role management
1175 * code expects the app_id to be null as there is no
1176 * concept of App_id in SDK
1178 Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1179 query.executeUpdate();
1183 transaction.commit();
1184 } catch (Exception e) {
1185 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1186 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1187 EcompPortalUtils.rollbackTransaction(transaction,
1188 "Exception occurred in syncUserRoles, Details: " + e.toString());
1189 if ("DELETE".equals(reqType)) {
1190 throw new SyncUserRolesException(e.getMessage());
1195 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1196 HashMap<Long, EcompRole> result = new HashMap<>();
1197 if (ecompRoles != null) {
1198 for (EcompRole ecompRole : ecompRoles) {
1199 if (ecompRole.getId() != null) {
1200 result.put(ecompRole.getId(), ecompRole);
1207 private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1208 HashMap<Long, EcompRole> newUserAppRolesMap) {
1211 if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1212 userAppRoleId = userRole.getRoleId().getId();
1213 } else { // remote app
1214 userAppRoleId = userRole.getId();
1217 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1218 fnUserRoleService.deleteById(userRole.getId());
1220 newUserAppRolesMap.remove(userAppRoleId);
1224 private Role fnRoleToRole(final FnRole role) {
1225 return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null,
1227 role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1230 @SuppressWarnings("unchecked")
1231 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue,
1233 List<RoleInAppForUser> rolesInAppForUser = null;
1234 FnApp app = fnAppService.getById(appId);
1235 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1237 // for onap portal app, no need to make a remote call
1238 List<Role> roleList = new ArrayList<>();
1239 if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1240 if (app.getAuthCentral()) {
1241 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1242 for (CentralV2Role cenRole : cenRoleList) {
1243 Role role = new Role();
1244 role.setActiveYn(cenRole.isActive());
1245 role.setId(cenRole.getId());
1246 role.setRoleName(cenRole.getName());
1247 role.setPriority(cenRole.getPriority());
1251 Optional<FnUser> user = fnUserService.getUser(userId);
1252 if (user.isPresent()) {
1253 roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole)
1254 .collect(Collectors.toList());
1257 List<Role> activeRoleList = new ArrayList<>();
1258 for (Role role : roleList) {
1259 if (role.getActiveYn()) {
1260 if (role.getId() != 1) { // prevent portal admin from being added
1261 activeRoleList.add(role);
1262 } else if (extRequestValue) {
1263 activeRoleList.add(role);
1268 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1269 // If localUser does not exists return roles
1270 Set<FnRole> roleSet = null;
1271 FnRole[] roleSetList = null;
1272 if (localUser != null) {
1273 roleSet = localUser.getAppEPRoles(app);
1274 roleSetList = roleSet.toArray(new FnRole[0]);
1276 rolesInAppForUser = fnUserRoleService
1277 .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1278 return rolesInAppForUser;
1281 EcompRole[] appRoles = null;
1282 boolean checkIfUserIsApplicationAccAdmin = false;
1283 List<EcompRole> roles = new ArrayList<>();
1284 if (app.getAuthCentral()) {
1285 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1286 FnApp application = fnAppService.getById(appId);
1287 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1290 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1291 for (FnRole role : applicationRoles) {
1292 List<EpAppFunction> cenRoleFuncList = epAppFunctionService
1293 .getAppRoleFunctionList(role.getId(), app.getId());
1294 for (EpAppFunction roleFunc : cenRoleFuncList) {
1296 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1297 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1298 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1299 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1300 String name = roleFunc.getFunctionName();
1302 FnFunction function = new FnFunction();
1303 function.setAction(action);
1304 function.setType(type);
1305 function.setCode(functionCode);
1306 function.setName(name);
1307 role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1310 roleSetWithFunctioncds.add(role);
1315 for (FnRole role1 : roleSetWithFunctioncds) {
1316 EcompRole ecompRole = new EcompRole();
1317 ecompRole.setId(role1.getId());
1318 ecompRole.setName(role1.getRoleName());
1319 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1320 roles.add(ecompRole);
1323 if (checkIfUserIsApplicationAccAdmin) {
1324 appRoles = roles.toArray(new EcompRole[roles.size()]);
1325 logger.debug(EELFLoggerDelegate.debugLogger,
1326 "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}",
1328 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1329 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1330 List<String> roleAdminAppRolesNames = new ArrayList<>();
1332 "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1333 + " where fu.role_id = ep.role_id"
1334 + " and fu.app_id = ep.app_id"
1335 + " and fu.user_id = :userId"
1336 + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1337 + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1340 + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id"
1341 + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1342 List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1343 .setParameter("userId", userId)
1345 List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1346 .collect(Collectors.toList());
1348 List<EcompRole> userapproverRolesList = new ArrayList<>();
1349 for (String str : getUserApproverRoles) {
1350 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1351 if (epRole != null) {
1352 userapproverRolesList.add(epRole);
1355 for (EcompRole role : userapproverRolesList) {
1357 List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1358 boolean checkIfFunctionsExits = roleFunList.stream()
1359 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1360 if (checkIfFunctionsExits) {
1361 roleAdminAppRoles.add(role);
1362 List<RoleFunction> filteredList = roleFunList.stream()
1363 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1364 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1365 .collect(Collectors.toList()));
1368 for (String name : roleAdminAppRolesNames) {
1369 roles.stream().filter(x -> name.equals(x.getName())).findAny()
1370 .ifPresent(roleAdminAppRoles::add);
1373 appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1377 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1379 // Test this error case, for generating an internal ONAP Portal
1381 // EcompRole[] appRoles = null;
1382 // If there is an exception in the rest client api, then null will
1384 if (appRoles != null) {
1385 if (!app.getAuthCentral()) {
1386 syncAppRoles(appId, appRoles);
1388 EcompRole[] userAppRoles = null;
1391 if (app.getAuthCentral()) {
1392 List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1393 List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1394 .createNamedQuery("EPUserAppCurrentRoles")
1395 .setParameter("appId", app.getId())
1396 .setParameter("userId", actualUser.get(0).getId())
1398 List<EcompRole> setUserRoles = new ArrayList<>();
1399 for (EPUserAppCurrentRoles role : userAppsRolesList) {
1400 logger.debug(EELFLoggerDelegate.debugLogger,
1401 "In getAppRolesForUser() - userAppsRolesList get userRolename = {}",
1402 role.getRoleName());
1403 EcompRole ecompRole = new EcompRole();
1404 ecompRole.setId(role.getRoleId());
1405 ecompRole.setName(role.getRoleName());
1406 setUserRoles.add(ecompRole);
1409 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1410 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1412 if (!checkIfUserisAccAdmin) {
1413 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1414 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1416 List<String> roleNames = new ArrayList<>();
1417 for (EcompRole role : setUserRoles) {
1418 EcompRole epRole = appRolesList.stream()
1419 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1420 List<RoleFunction> roleFunList = new ArrayList<>();
1422 if (epRole != null) {
1423 if (epRole.getRoleFunctions().size() > 0) {
1424 roleFunList.addAll(epRole.getRoleFunctions());
1426 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1427 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1428 if (checkIfFunctionsExits) {
1429 finalUserAppRolesList.add(role);
1430 List<RoleFunction> filteredList = roleFunList.stream()
1431 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1432 .collect(Collectors.toList());
1433 roleNames = filteredList.stream().map(RoleFunction::getCode)
1434 .collect(Collectors.toList());
1436 roleNames.add(epRole.getName());
1439 for (String name : roleNames) {
1440 EcompRole ecompRole = appRolesList.stream()
1441 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1442 if (ecompRole != null) {
1443 finalUserAppRolesList.add(ecompRole);
1447 for (String name : roleNames) {
1448 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1449 role -> role.getRoleName().equalsIgnoreCase(name));
1450 if (checkIfFunctionsExits) {
1451 appRolesList.stream().filter(x -> name.equals(x.getName()))
1452 .findAny().ifPresent(setUserRoles::add);
1455 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1458 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1459 String.format("/user/%s/roles", userId));
1461 } catch (HTTPException e) {
1462 // Some apps are returning 400 if user is not found.
1463 if (e.getResponseCode() == 400) {
1464 logger.debug(EELFLoggerDelegate.debugLogger,
1465 "getAppRolesForUser caught exception with response code 400; continuing", e);
1467 // Other response code, let it come thru.
1471 if (userAppRoles == null) {
1472 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1473 EcompPortalUtils.setExternalAppResponseCode(200);
1474 String message = String.format(
1475 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1476 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1477 + "Overriding to 200 until framework SDK returns a useful response.",
1478 Long.toString(appId), userId);
1479 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1483 HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1484 ArrayList<EcompRole> activeRoles = new ArrayList<>();
1485 if (userAppRoles != null) {
1486 for (EcompRole userAppRole : userAppRoles) {
1487 if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1488 EcompRole role = new EcompRole();
1489 role.setId(userAppRole.getId());
1490 role.setName(userAppRole.getName());
1491 activeRoles.add(role);
1495 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1497 boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1499 // If the remote application isn't down we MUST sync user
1500 // roles here in case we have this user here!
1501 syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null,
1502 checkIfUserisRoleAdmin,
1504 } catch (Exception e) {
1505 // TODO: we may need to check if user exists, maybe remote
1507 String message = String.format(
1508 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1509 Long.toString(appId));
1510 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1511 userAppRoles = new EcompRole[0];
1513 rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1515 } catch (Exception e) {
1516 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1517 Long.toString(appId));
1518 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1520 return rolesInAppForUser;
1523 private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1524 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1525 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1527 List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1529 List<FnRole> obsoleteRoles = new ArrayList<>();
1530 for (FnRole oldAppRole : currentAppRoles) {
1531 if (oldAppRole.getAppRoleId() != null) {
1533 role = newRolesMap.get(oldAppRole.getAppRoleId());
1535 if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1536 oldAppRole.setRoleName(role.getName());
1538 oldAppRole.setActiveYn(true);
1539 newRolesMap.remove(oldAppRole.getAppRoleId());
1541 obsoleteRoles.add(oldAppRole);
1544 obsoleteRoles.add(oldAppRole);
1547 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1548 if (obsoleteRoles.size() > 0) {
1549 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1550 for (FnRole role : obsoleteRoles) {
1551 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1552 Long roleId = role.getId();
1553 List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1555 logger.debug(EELFLoggerDelegate.debugLogger,
1556 "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1557 for (FnUserRole userRole : userRoles) {
1558 logger.debug(EELFLoggerDelegate.debugLogger,
1559 "syncAppRoles: about to delete userRole: " + userRole.toString());
1560 fnUserRoleService.deleteById(userRole.getId());
1561 logger.debug(EELFLoggerDelegate.debugLogger,
1562 "syncAppRoles: finished deleting userRole: " + userRole.toString());
1564 List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1565 int numMenuRoles = funcMenuRoles.size();
1566 logger.debug(EELFLoggerDelegate.debugLogger,
1567 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1568 for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1569 Long menuId = funcMenuRole.getMenuId().getMenuId();
1570 // If this is the only role for this menu item, then the
1571 // app and roles will be gone,
1572 // so must null out the url too, to be consistent
1573 List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService
1574 .retrieveByMenuId(menuId);
1575 int numMenuRoles2 = funcMenuRoles2.size();
1576 logger.debug(EELFLoggerDelegate.debugLogger,
1577 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1578 fnMenuFunctionalRolesService.delete(funcMenuRole);
1580 if (numMenuRoles2 == 1) {
1581 // If this is the only role for this menu item, then
1582 // the app and roles will be gone,
1583 // so must null out the url too, to be consistent
1584 logger.debug(EELFLoggerDelegate.debugLogger,
1585 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1586 List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1587 if (funcMenuItems.size() > 0) {
1588 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1589 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1590 funcMenuItem.setUrl("");
1594 boolean isPortalRequest = true;
1595 deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1596 logger.debug(EELFLoggerDelegate.debugLogger,
1597 "syncAppRoles: about to delete the role: " + role.toString());
1598 fnRoleService.delete(role);
1599 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1602 for (EcompRole role : newRolesToAdd) {
1603 logger.debug(EELFLoggerDelegate.debugLogger,
1604 "syncAppRoles: about to add missing role: " + role.toString());
1605 FnRole newRole = new FnRole();
1606 // Attention! All roles from remote application supposed to be
1608 newRole.setActiveYn(true);
1609 newRole.setRoleName(role.getName());
1610 newRole.setAppId(appId);
1611 newRole.setAppRoleId(role.getId());
1612 fnRoleService.saveOne(newRole);
1614 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1615 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1616 } catch (Exception e) {
1617 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1618 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1619 throw new Exception(e);
1623 private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1625 Session localSession = entityManager.unwrap(Session.class);
1629 // It should delete only when it portal's roleId
1630 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1631 // Delete from fn_role_function
1632 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1633 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1634 query = localSession.createSQLQuery(sql);
1635 query.executeUpdate();
1636 // Delete from fn_role_composite
1637 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1638 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1639 query = localSession.createSQLQuery(sql);
1640 query.executeUpdate();
1642 // Delete from ep_app_role_function
1643 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1644 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1645 query = localSession.createSQLQuery(sql);
1646 query.executeUpdate();
1647 // Delete from ep_role_notification
1648 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1649 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1650 query = localSession.createSQLQuery(sql);
1651 query.executeUpdate();
1652 // Delete from fn_user_pseudo_role
1653 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1654 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1655 query = localSession.createSQLQuery(sql);
1656 query.executeUpdate();
1657 // Delete form EP_WIDGET_CATALOG_ROLE
1658 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE 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_user_roles_request_det WHERE requested_role_id=" + roleId;
1664 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1665 query = localSession.createSQLQuery(sql);
1666 query.executeUpdate();
1667 if (!isPortalRequest) {
1668 // Delete form fn_menu_functional_roles
1669 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1670 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1671 query = localSession.createSQLQuery(sql);
1672 query.executeUpdate();
1674 } catch (Exception e) {
1675 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1676 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1680 private void checkIfRoleInactive(FnRole epRole) throws Exception {
1681 if (!epRole.getActiveYn()) {
1682 throw new Exception(epRole.getRoleName() + " role is unavailable");
1686 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1687 boolean result = false;
1688 // No changes if no new roles list or no userId.
1689 if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1690 && newAppsListWithAdminRoles.getAppsRoles() != null) {
1691 synchronized (syncRests) {
1692 List<FnApp> apps = fnAppService.getAppsFullList();
1693 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1694 for (FnApp app : apps) {
1695 enabledApps.put(app.getId(), app);
1697 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1698 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1699 // user Admin role may be added only for enabled apps
1700 if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1701 newAppsWhereUserIsAdmin.add(adminRole);
1705 boolean createNewUser = false;
1706 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1707 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1708 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1709 if (localUserList.size() > 0) {
1710 FnUser tmpUser = localUserList.get(0);
1711 oldAppsWhereUserIsAdmin = fnUserRoleService
1712 .retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1713 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1716 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1717 // we create new user only if he has Admin Role for any App
1718 createNewUser = true;
1720 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1721 oldAppsWhereUserIsAdmin);
1729 public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1730 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1731 List<FnUserRole> oldAppsWhereUserIsAdmin) {
1732 if (user != null || createNewUser) {
1733 if (createNewUser) {
1734 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1736 user.setActiveYn(true);
1739 for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1740 // user Admin role may be deleted only for enabled
1742 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1743 fnUserRoleService.saveOne(oldUserApp);
1746 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1747 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1748 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1749 FnUserRole newUserApp = new FnUserRole();
1750 newUserApp.setUserId(user);
1751 newUserApp.setFnAppId(app);
1752 newUserApp.setRoleId(role);
1753 fnUserRoleService.saveOne(newUserApp);
1755 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1756 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1763 public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1764 boolean result = false;
1766 // Reset All admin role for centralized applications
1767 List<FnApp> appList = fnAppService.getCentralizedApps();
1768 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1769 for (FnApp app : appList) {
1771 if (EPCommonSystemProperties
1772 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1773 name = user.getOrgUserId() + SystemProperties
1774 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1776 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1777 HttpEntity<String> entity = new HttpEntity<>(headers);
1778 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1780 ResponseEntity<String> getResponse = template
1781 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1782 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1784 if (getResponse.getBody().equals("{}")) {
1785 String addDesc = "{\"name\":\"" + extRole + "\"}";
1786 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1788 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1790 HttpMethod.POST, roleEntity, String.class);
1793 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1795 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1796 + "userRole/" + name + "/" + extRole,
1797 HttpMethod.DELETE, deleteUserRole, String.class);
1798 } catch (Exception e) {
1799 logger.error(EELFLoggerDelegate.errorLogger,
1800 " Role not found for this user may be it gets deleted before", e);
1803 } catch (Exception e) {
1804 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1805 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1806 app.getAuthNamespace(), e.getMessage());
1808 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1809 app.getAuthNamespace(), e);
1813 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1814 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1816 if (app.getAuthCentral()) {
1817 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1818 HttpEntity<String> entity = new HttpEntity<>(headers);
1820 if (EPCommonSystemProperties
1821 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1822 name = user.getOrgUserId() + SystemProperties
1823 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1825 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1826 ResponseEntity<String> getUserRolesResponse = template.exchange(
1827 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1828 + "userRoles/user/" + name,
1829 HttpMethod.GET, entity, String.class);
1830 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1831 if (!getUserRolesResponse.getBody().equals("{}")) {
1832 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1833 JSONArray extRoles = jsonObj.getJSONArray("userRole");
1834 final Map<String, JSONObject> extUserRoles = new HashMap<>();
1835 for (int i = 0; i < extRoles.length(); i++) {
1836 String userRole = extRoles.getJSONObject(i).getString("role");
1837 if (userRole.startsWith(app.getAuthNamespace() + ".")
1838 && !userRole.equals(app.getAuthNamespace() + ".admin")
1839 && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1841 extUserRoles.put(userRole, extRoles.getJSONObject(i));
1844 if (!extUserRoles.containsKey(extRole)) {
1845 // Assign with new apps user admin
1847 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1848 // Assign user role for an application in external access system
1849 ObjectMapper addUserRoleMapper = new ObjectMapper();
1850 String userRole = addUserRoleMapper.writeValueAsString(extUser);
1851 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1853 SystemProperties.getProperty(
1854 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1855 HttpMethod.POST, addUserRole, String.class);
1856 } catch (Exception e) {
1857 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1864 } catch (Exception e) {
1865 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1866 logger.debug(EELFLoggerDelegate.errorLogger,
1867 "Application name space not found in External system for app {} due to bad rquest name space ",
1868 app.getAuthNamespace(), e.getMessage());
1870 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1871 app.getAuthNamespace(), e);
1876 } catch (Exception e) {
1878 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
1883 public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
1884 final String getAllAppsFunctionsOfUser =
1885 "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"
1886 + " where fu.role_id = ep.role_id \n"
1887 + " and fu.app_id = ep.app_id\n"
1888 + " and fu.user_id =:userId\n"
1889 + " and ea.function_cd = ep.function_cd\n"
1890 + " and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1))\n"
1891 + " and fr.role_id = fu.role_id and fr.active_yn='Y' \n"
1893 + " select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f\n"
1894 + " where role_id = 999\n"
1895 + " and app_r_f.function_cd = a_f.function_cd\n"
1898 + " 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"
1899 + " and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'\n"
1901 List getRoleFuncListOfPortal = entityManager.createNativeQuery(getAllAppsFunctionsOfUser)
1902 .setParameter("userId", OrgUserId).getResultList();
1903 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
1904 Set<String> roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
1905 .collect(Collectors.toSet());
1906 if (!roleFunSet.isEmpty()) {
1907 for (String roleFunction : roleFunSet) {
1908 String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
1909 getRoleFuncListOfPortalSet.remove(roleFunction);
1910 getRoleFuncListOfPortalSet.add(roleFun);
1914 Set<String> finalRoleFunctionSet = new HashSet<>();
1915 for (String roleFn : getRoleFuncListOfPortalSet) {
1916 finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
1919 return finalRoleFunctionSet;
1922 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
1923 AppsListWithAdminRole appsListWithAdminRole = null;
1926 List<FnUser> userList = fnUserService.getUserWithOrgUserId(orgUserId);
1927 HashMap<Long, Long> appsUserAdmin = new HashMap<>();
1928 if (userList != null && userList.size() > 0) {
1929 FnUser user = userList.get(0);
1930 List<FnUserRole> userAppList = new ArrayList<>();
1932 userAppList = fnUserRoleService.retrieveByUserIdAndRoleId(user.getId(), ACCOUNT_ADMIN_ROLE_ID);
1933 } catch (Exception e) {
1934 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
1935 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
1937 for (FnUserRole userApp : userAppList) {
1938 appsUserAdmin.put(userApp.getFnAppId().getId(), userApp.getUserId().getId());
1942 appsListWithAdminRole = new AppsListWithAdminRole();
1943 appsListWithAdminRole.setOrgUserId(orgUserId);
1944 List<FnApp> appsList = new ArrayList<>();
1946 appsList = fnAppService.findAll();
1947 } catch (Exception e) {
1948 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
1949 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
1951 for (FnApp app : appsList) {
1952 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
1953 appNameIdIsAdmin.setId(app.getId());
1954 appNameIdIsAdmin.setAppName(app.getAppName());
1955 appNameIdIsAdmin.setIsAdmin(appsUserAdmin.containsKey(app.getId()));
1956 appNameIdIsAdmin.setRestrictedApp(app.isRestrictedApp());
1957 appsListWithAdminRole.getAppsRoles().add(appNameIdIsAdmin);
1959 } catch (Exception e) {
1960 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
1962 return appsListWithAdminRole;
1965 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser,
1967 boolean result = false;
1968 boolean externalSystemRequest = true;
1969 List<FnUser> userInfo = null;
1971 List<EpUserRolesRequest> epRequestId = null;
1972 String orgUserId = "";
1973 String updateStatus = "";
1974 String reqMessage = "";
1976 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1977 orgUserId = newAppRolesForUser.getLoginId().trim();
1979 String appName = newAppRolesForUser.getApplicationName();
1980 String logMessage = ("DELETE").equals(reqType) ? "Deleting" : "Assigning/Updating";
1981 if (orgUserId.length() > 0) {
1982 ObjectMapper mapper = new ObjectMapper();
1983 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1984 int epRequestIdSize = 0;
1986 app = fnAppService.getAppDetail(appName);
1987 userInfo = checkIfUserExists(orgUserId);
1988 reqMessage = "Updated Successfully";
1989 if (!reqType.equals("DELETE") && (userInfo.isEmpty())) {
1990 reqMessage = validateNewUser(orgUserId, app);
1992 if (!userInfo.isEmpty()) {
1993 validateExternalRequestFields(app);
1994 user = userInfo.get(0);
1995 epRequestId = epUserRolesRequestService.userAppRolesRequestList(user.getId(), app.getId());
1996 epRequestIdSize = epRequestId.size();
1998 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getAuthCentral()) {
1999 logger.debug(EELFLoggerDelegate.debugLogger,
2000 "setExternalRequestUserAppRole: Starting GET roles for app {}", app.getId());
2001 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
2002 logger.debug(EELFLoggerDelegate.debugLogger,
2003 "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}", app.getId(),
2005 if (appRoles.length > 0) {
2006 syncAppRoles(app.getId(), appRoles);
2009 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
2010 app.getId(), app.getMlAppName());
2011 List<EcompUserAppRoles> userRoleList = null;
2012 if (!userInfo.isEmpty()) {
2013 userRoleList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
2015 // Check if list contains just account admin role
2016 boolean checkIfAdminRoleExists = false;
2017 if (reqType.equals("DELETE") && userRoleList != null) {
2018 checkIfAdminRoleExists = userRoleList.stream()
2019 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
2021 checkIfAdminRoleExists = roleInAppForUserList.stream()
2022 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
2024 if (app.getAuthCentral()) {
2026 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
2027 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
2028 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
2029 List<RoleInAppForUser> remoteUserRoles = new ArrayList<>(roleInAppForUserList);
2030 remoteUserRoles.removeIf(role -> {
2031 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
2033 String orgUserIdNewOrExist = (!userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
2034 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist, app, mapper,
2035 applicationsRestClientService, true);
2037 } catch (Exception e) {
2038 reqMessage = e.getMessage();
2039 logger.error(EELFLoggerDelegate.errorLogger,
2040 "setExternalRequestUserAppRole: Failed to added remote user", e);
2041 throw new Exception(reqMessage);
2043 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
2044 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2045 userRolesInLocalApp);
2046 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
2047 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2048 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2049 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), roleAppUserList,
2050 externalSystemRequest, false, rolesGotDeletedByApprover, false);
2052 logger.info(EELFLoggerDelegate.debugLogger,
2053 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
2054 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
2055 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,
2056 false, rolesGotDeletedByApprover, false);
2057 } else if (!app.getAuthCentral() && app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2058 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
2059 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2060 userRolesInLocalApp);
2061 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2063 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,
2064 false, rolesGotDeletedByApprover, false);
2066 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
2067 FnUser remoteAppUser = null;
2068 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
2069 if (remoteAppUser == null) {
2070 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper,
2071 applicationsRestClientService);
2072 reqMessage = "Saved Successfully";
2074 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
2075 applicationsRestClientService, app.getId(), orgUserId);
2076 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2077 userRolesInRemoteApp);
2078 logger.info(EELFLoggerDelegate.debugLogger,
2079 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
2080 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
2081 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2082 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
2083 reqType, false, rolesGotDeletedByApprover, false);
2085 if (!(reqType.equals("DELETE")) && userInfo.isEmpty()) {
2086 reqMessage = "Saved Successfully";
2088 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
2089 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
2090 userRolesInRemoteApp);
2091 logger.info(EELFLoggerDelegate.debugLogger,
2092 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
2093 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
2094 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
2095 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
2096 reqType, false, rolesGotDeletedByApprover, false);
2099 reqMessage = "Failed to save the user app role(s)";
2101 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
2103 applyChangesToAppRolesRequest(user.getId(), updateStatus, epRequestId.get(0));
2106 } catch (Exception e) {
2107 String message = String.format(
2108 "setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
2109 orgUserId, appName);
2110 logger.error(EELFLoggerDelegate.errorLogger, message, e);
2112 reqMessage = e.getMessage();
2113 if (epRequestIdSize > 0 && userInfo != null && !userInfo.isEmpty()) {
2115 applyChangesToAppRolesRequest(user.getId(),
2116 updateStatus, epRequestId.get(0));
2120 return new ExternalRequestFieldsValidator(result, reqMessage);
2123 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
2124 return constructUsersEcompRoles(roleInAppForUserList);
2127 private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
2128 Set<EcompRole> existingUserRoles = new TreeSet<>();
2129 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
2130 if (roleInAppForUser.getIsApplied()) {
2131 EcompRole ecompRole = new EcompRole();
2132 ecompRole.setId(roleInAppForUser.getRoleId());
2133 ecompRole.setName(roleInAppForUser.getRoleName());
2134 existingUserRoles.add(ecompRole);
2137 return existingUserRoles;
2140 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
2141 Long appId, String appName) throws Exception {
2142 List<RoleInAppForUser> existingUserRoles = new ArrayList<>();
2143 List<FnRole> existingAppRole;
2144 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
2145 RoleInAppForUser ecompRole = new RoleInAppForUser();
2146 existingAppRole = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(roleInAppForUser.getRoleName(), appId);
2147 if (existingAppRole.isEmpty()) {
2148 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
2149 roleInAppForUserList);
2150 throw new Exception("'" + roleInAppForUser.getRoleName() + "'" + " role does not exist for " + appName
2153 if (!existingAppRole.get(0).getActiveYn()) {
2154 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
2155 roleInAppForUserList);
2156 throw new Exception(
2157 roleInAppForUser.getRoleName() + " role is unavailable for " + appName + " application");
2160 List<FnRole> roleInfo = externalAccessRolesService
2161 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
2162 FnRole adminRole = new FnRole();
2163 if (roleInfo.size() > 0) {
2164 adminRole = roleInfo.get(0);
2165 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
2167 ecompRole.setRoleId(
2168 (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getRoleName())) ? existingAppRole
2170 .getId() : existingAppRole.get(0).getAppRoleId());
2171 ecompRole.setRoleName(roleInAppForUser.getRoleName());
2172 ecompRole.setIsApplied(true);
2173 existingUserRoles.add(ecompRole);
2176 return existingUserRoles;
2179 private void validateExternalRequestFields(FnApp app) throws Exception {
2181 throw new Exception("Application does not exist");
2182 } else if (!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2183 throw new Exception(app.getMlAppName() + " application is unavailable");
2187 private String validateNewUser(String orgUserId, FnApp app) throws Exception {
2188 FnUser epUser = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
2189 if (epUser == null) {
2190 throw new Exception("User does not exist");
2191 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
2192 throw new Exception("User does not exist");
2193 } else if (app == null) {
2194 throw new Exception("Application does not exist");
2196 return "Saved Successfully";
2199 private void applyChangesToAppRolesRequest(final Long userId, final String updateStatus,
2200 final EpUserRolesRequest epUserAppRolesRequest) {
2202 epUserAppRolesRequest.setUpdatedDate(LocalDateTime.now());
2203 epUserAppRolesRequest.setRequestStatus(updateStatus);
2204 epUserAppRolesRequest.setUserId(fnUserService.getUser(userId).get());
2205 epUserRolesRequestService.saveOne(epUserAppRolesRequest);
2206 List<EpUserRolesRequestDet> epUserAppRolessDetailList = epUserRolesRequestDetService
2207 .appRolesRequestDetailList(epUserAppRolesRequest.getReqId());
2208 if (epUserAppRolessDetailList.size() > 0) {
2209 for (EpUserRolesRequestDet epRequestUpdateData : epUserAppRolessDetailList) {
2210 epRequestUpdateData.setRequestType(updateStatus);
2211 epRequestUpdateData.setReqId(epUserAppRolesRequest);
2212 epRequestUpdateData.setReqId(epUserAppRolesRequest);
2213 epUserRolesRequestDetService.saveOne(epRequestUpdateData);
2216 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
2217 } catch (Exception e) {
2218 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);