2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
41 package org.onap.portal.service;
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.DeserializationFeature;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import java.time.LocalDateTime;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.List;
55 import java.util.Optional;
57 import java.util.SortedSet;
58 import java.util.TreeSet;
59 import java.util.stream.Collectors;
60 import javax.persistence.EntityManager;
61 import javax.persistence.Query;
62 import javax.persistence.Tuple;
63 import org.apache.commons.lang.StringUtils;
64 import org.apache.cxf.transport.http.HTTPException;
65 import org.hibernate.Session;
66 import org.hibernate.Transaction;
67 import org.json.JSONArray;
68 import org.json.JSONObject;
69 import org.onap.portal.domain.db.ep.EpAppFunction;
70 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
71 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
72 import org.onap.portal.domain.db.fn.FnApp;
73 import org.onap.portal.domain.db.fn.FnFunction;
74 import org.onap.portal.domain.db.fn.FnMenuFunctional;
75 import org.onap.portal.domain.db.fn.FnMenuFunctionalRoles;
76 import org.onap.portal.domain.db.fn.FnRole;
77 import org.onap.portal.domain.db.fn.FnRoleFunction;
78 import org.onap.portal.domain.db.fn.FnUser;
79 import org.onap.portal.domain.db.fn.FnUserRole;
80 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
81 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
82 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
83 import org.onap.portal.domain.dto.transport.CentralV2Role;
84 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
85 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
86 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
87 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
89 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
90 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
91 import org.onap.portal.domain.dto.transport.Role;
92 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
93 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
94 import org.onap.portal.exception.DeleteDomainObjectFailedException;
95 import org.onap.portal.exception.SyncUserRolesException;
96 import org.onap.portal.logging.format.EPAppMessagesEnum;
97 import org.onap.portal.logging.logic.EPLogUtil;
98 import org.onap.portal.service.appFunction.EpAppFunctionService;
99 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
100 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
101 import org.onap.portal.service.app.FnAppService;
102 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
103 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
104 import org.onap.portal.service.role.FnRoleService;
105 import org.onap.portal.service.userRole.FnUserRoleService;
106 import org.onap.portal.service.user.FnUserService;
107 import org.onap.portal.utils.EPCommonSystemProperties;
108 import org.onap.portal.utils.EPUserUtils;
109 import org.onap.portal.utils.EcompPortalUtils;
110 import org.onap.portal.utils.PortalConstants;
111 import org.onap.portalsdk.core.domain.RoleFunction;
112 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
113 import org.onap.portalsdk.core.restful.domain.EcompRole;
114 import org.onap.portalsdk.core.util.SystemProperties;
115 import org.springframework.beans.factory.annotation.Autowired;
116 import org.springframework.http.HttpEntity;
117 import org.springframework.http.HttpHeaders;
118 import org.springframework.http.HttpMethod;
119 import org.springframework.http.HttpStatus;
120 import org.springframework.http.ResponseEntity;
121 import org.springframework.stereotype.Service;
122 import org.springframework.transaction.annotation.Transactional;
123 import org.springframework.web.client.HttpClientErrorException;
124 import org.springframework.web.client.RestTemplate;
128 public class AdminRolesService {
130 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
131 private static final Object syncRests = new Object();
132 private final RestTemplate template = new RestTemplate();
134 private Long SYS_ADMIN_ROLE_ID = 38L;
135 private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
136 private final Long ECOMP_APP_ID = 1L;
137 private final String ADMIN_ACCOUNT = "Is account admin for user {}";
139 private final AppsCacheService appsCacheService;
140 private final EntityManager entityManager;
141 private final FnUserService fnUserService;
142 private final FnRoleService fnRoleService;
143 private final FnAppService fnAppService;
144 private final FnMenuFunctionalService fnMenuFunctionalService;
145 private final FnUserRoleService fnUserRoleService;
146 private final EpAppFunctionService epAppFunctionService;
147 private final EcompUserAppRolesService ecompUserAppRolesService;
148 private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
149 private final ApplicationsRestClientService applicationsRestClientService;
150 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
151 private final ExternalAccessRolesService externalAccessRolesService;
152 private final EpUserRolesRequestService epUserRolesRequestService;
155 public AdminRolesService(AppsCacheService appsCacheService,
156 final EntityManager entityManager,
157 final FnUserService fnUserService, FnRoleService fnRoleService,
158 FnAppService fnAppService,
159 FnMenuFunctionalService fnMenuFunctionalService,
160 final FnUserRoleService fnUserRoleService,
161 EpAppFunctionService epAppFunctionService,
162 EcompUserAppRolesService ecompUserAppRolesService,
163 FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
164 ApplicationsRestClientService applicationsRestClientService,
165 EpUserRolesRequestDetService epUserRolesRequestDetService,
166 ExternalAccessRolesService externalAccessRolesService,
167 EpUserRolesRequestService epUserRolesRequestService) {
168 this.appsCacheService = appsCacheService;
169 this.entityManager = entityManager;
170 this.fnUserService = fnUserService;
171 this.fnRoleService = fnRoleService;
172 this.fnAppService = fnAppService;
173 this.fnMenuFunctionalService = fnMenuFunctionalService;
174 this.fnUserRoleService = fnUserRoleService;
175 this.epAppFunctionService = epAppFunctionService;
176 this.ecompUserAppRolesService = ecompUserAppRolesService;
177 this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
178 this.applicationsRestClientService = applicationsRestClientService;
179 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
180 this.externalAccessRolesService = externalAccessRolesService;
181 this.epUserRolesRequestService = epUserRolesRequestService;
184 public boolean isSuperAdmin(final String loginId) {
185 boolean isSuperAdmin;
187 isSuperAdmin = fnUserRoleService
188 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
189 } catch (Exception e) {
190 logger.error("isSuperAdmin exception: " + e.toString());
193 logger.info("isSuperAdmin " + isSuperAdmin);
197 public boolean isAccountAdmin(FnUser user) {
199 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
200 List<Integer> userAdminApps = getAdminAppsForTheUser(user.getId());
201 logger.debug(EELFLoggerDelegate.debugLogger,
202 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
203 user.getOrgUserId(), userAdminApps.size());
205 if (user.getId() != null) {
206 for (FnUserRole userApp : user.getUserApps()) {
207 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
208 userAdminApps.size() > 1)) {
209 logger.debug(EELFLoggerDelegate.debugLogger,
210 "Is account admin for userAdminApps() - for user {}, found Id {}",
211 user.getOrgUserId(), userApp.getRoleId().getId());
216 } catch (Exception e) {
217 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
218 logger.error(EELFLoggerDelegate.errorLogger,
219 "Exception occurred while executing isAccountAdmin operation",
225 public boolean isUser(FnUser user) {
227 FnUser currentUser = fnUserService.getUser(user.getId()).orElseThrow(Exception::new);
228 if (currentUser != null && currentUser.getId() != null) {
229 for (FnUserRole userApp : currentUser.getUserApps()) {
230 if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
231 FnRole role = userApp.getRoleId();
232 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
233 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
234 if (role.getActiveYn()) {
241 } catch (Exception e) {
242 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
243 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
249 public boolean isRoleAdmin(Long userId) {
251 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
252 List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
253 logger.debug(EELFLoggerDelegate.debugLogger,
254 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
255 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
256 Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
257 Set<String> roleFunSet;
258 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
259 .collect(Collectors.toSet());
260 if (!roleFunSet.isEmpty()) {
261 for (String roleFunction : roleFunSet) {
262 String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
263 getRoleFuncListOfPortalSet1.add(type);
267 boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
268 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
269 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
270 checkIfFunctionsExits);
272 return checkIfFunctionsExits;
274 } catch (Exception e) {
275 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
276 logger.error(EELFLoggerDelegate.errorLogger,
277 "Exception occurred while executing isRoleAdmin operation",
283 private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
284 boolean isApplicationAccountAdmin = false;
286 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
287 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
288 if (!userAdminApps.isEmpty()) {
289 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
290 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
293 } catch (Exception e) {
294 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
295 logger.error(EELFLoggerDelegate.errorLogger,
296 "Exception occurred while executing isAccountAdminOfApplication operation", e);
298 logger.debug(EELFLoggerDelegate.debugLogger,
299 "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
301 return isApplicationAccountAdmin;
305 private List<Integer> getAdminAppsForTheUser(final Long userId) {
306 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)";
307 return entityManager.createQuery(query, Integer.class)
308 .setParameter("userId", userId).getResultList();
311 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
312 AppWithRolesForUser newAppRolesForUser) {
313 boolean result = false;
314 boolean epRequestValue = false;
316 String reqMessage = "";
317 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
318 userId = newAppRolesForUser.getOrgUserId().trim();
320 Long appId = newAppRolesForUser.getAppId();
321 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
323 if (userId.length() > 0) {
324 ObjectMapper mapper = new ObjectMapper();
325 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
328 FnApp app = fnAppService.getById(appId);
330 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
332 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
334 boolean checkIfUserIsOnlyRoleAdmin =
335 isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
336 if (checkIfUserIsOnlyRoleAdmin) {
337 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
338 if (!roleInAppForUser.getIsApplied()) {
339 EcompRole ecompRole = new EcompRole();
340 ecompRole.setId(roleInAppForUser.getRoleId());
341 ecompRole.setName(roleInAppForUser.getRoleName());
342 rolesGotDeletedFromApprover.add(ecompRole);
347 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
349 boolean systemUser = newAppRolesForUser.isSystemUser();
351 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
354 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
355 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
356 userRolesInLocalApp);
357 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
358 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
359 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
360 // Apply changes in external Access system
362 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
364 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
366 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
368 systemUser, rolesGotDeletedByApprover, false);
370 } else if (!app.getAuthCentral() && systemUser) {
371 throw new Exception("For non-centralized application we cannot add systemUser");
372 } else { // if centralized app
373 if (app.getAuthCentral()) {
374 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
375 pushRemoteUser(roleInAppForUserList, userId, app, mapper,
376 applicationsRestClientService, false);
379 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
380 roleInAppForUserList);
381 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
383 userRolesInLocalApp);
384 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
385 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
387 // Apply changes in external Access system
388 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
390 epRequestValue, false, rolesGotDeletedFromApprover,
391 checkIfUserIsOnlyRoleAdmin);
393 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
394 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
395 checkIfUserIsOnlyRoleAdmin);
397 // In case if portal is not centralized then follow existing approach
398 else if (!app.getAuthCentral() && app.getId()
399 .equals(PortalConstants.PORTAL_APP_ID)) {
400 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
401 roleInAppForUserList);
402 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
404 userRolesInLocalApp);
405 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
406 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
407 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
408 } else {// remote app
409 FnUser remoteAppUser;
410 if (!app.getAuthCentral() && !app.getId()
411 .equals(PortalConstants.PORTAL_APP_ID)) {
413 remoteAppUser = checkIfRemoteUserExits(userId, app,
414 applicationsRestClientService);
416 if (remoteAppUser == null) {
417 addRemoteUser(roleInAppForUserList, userId, app,
418 mapper, applicationsRestClientService);
420 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
421 roleInAppForUserList, mapper,
422 applicationsRestClientService, appId, userId);
423 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
425 userRolesInRemoteApp);
426 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
427 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
428 epRequestValue, null, false, rolesGotDeletedByApprover, false);
430 // If no roles remain, request app to set user inactive.
431 if (userRolesInRemoteApp.size() == 0) {
432 logger.debug(EELFLoggerDelegate.debugLogger,
433 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
436 postUserToRemoteApp(userId, app,
437 applicationsRestClientService);
442 } catch (Exception e) {
443 String message = String.format(
444 "Failed to create user or update user roles for User %s, AppId %s",
445 userId, Long.toString(appId));
446 logger.error(EELFLoggerDelegate.errorLogger, message, e);
448 reqMessage = e.getMessage();
452 return new ExternalRequestFieldsValidator(result, reqMessage);
456 private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
457 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
459 pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
460 roleInAppForUserList, appRoleIdUsed);
464 private void postUserToRemoteApp(String userId, FnApp app,
465 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
467 getUser(userId, app, applicationsRestClientService);
471 private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
472 throws HTTPException {
473 return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
477 private void pushUserOnRemoteApp(String userId, FnApp app,
478 ApplicationsRestClientService applicationsRestClientService,
479 ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
483 client = fnUserService.loadUserByUsername(userId);
485 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
486 if (client == null) {
487 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
488 logger.error(EELFLoggerDelegate.errorLogger, msg);
489 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
490 if (!userList.isEmpty()) {
491 logger.debug(EELFLoggerDelegate.debugLogger,
492 userList.get(0).getOrgUserId() + " User was found in Portal");
493 client = userList.get(0);
494 client.setUserApps(Collections.EMPTY_SET);
495 client.setIsSystemUser(false);
497 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
498 throw new Exception(msg);
503 client.setLoginId(userId);
504 client.setActiveYn(true);
505 client.setOrgUserId(userId);
507 roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
508 SortedSet<Role> roles = new TreeSet<>();
510 List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
511 List<FnApp> appList = new ArrayList<>();
513 List<CentralV2Role> roleList = new ArrayList<>();
515 List<FnRole> userRoles = new ArrayList<>();
517 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
518 FnRole role = new FnRole();
519 role.setId(roleInappForUser.getRoleId());
520 role.setRoleName(roleInappForUser.getRoleName());
525 List<FnRole> userAppRoles = new ArrayList<>();
526 for (FnRole role : userRoles) {
527 FnRole appRole = getAppRoles.stream()
528 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
530 FnRole epRole = new FnRole();
531 if (appRole != null) {
532 epRole.setId(appRole.getId());
533 epRole.setRoleName(appRole.getRoleName());
535 userAppRoles.add(epRole);
537 userRoles = new ArrayList<>(userAppRoles);
539 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
541 for (CentralV2Role epRole : roleList) {
542 Role role = new Role();
543 FnRole appRole = getAppRoles.stream()
544 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
545 if (appRole != null) {
546 role.setId(appRole.getAppRoleId());
547 role.setRoleName(epRole.getName());
548 role.setFnRoleFunctions(epRole.getRoleFunctions());
552 client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
554 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
555 logger.debug(EELFLoggerDelegate.debugLogger,
556 "about to post a client to remote application, users json = " + userInString);
557 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
560 private FnRole roleToFnRole(Role role) {
561 return FnRole.builder()
563 .roleName(role.getRoleName())
564 .activeYn(role.getActiveYn())
565 .priority(role.getPriority())
566 .fnRoleFunctions(role.getFnRoleFunctions())
567 .childRoles(role.getChildRoles())
568 .parentRoles(role.getParentRoles())
572 private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
573 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
574 throws JsonProcessingException, HTTPException {
575 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
576 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
577 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
579 externalApp = appsCacheService.getApp(appId);
580 String appBaseUri = null;
581 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
582 if (externalApp != null) {
583 appBaseUri = externalApp.getAppRestEndpoint();
585 if (appBaseUri != null && appBaseUri.endsWith("/api")) {
586 for (EcompRole eprole : updatedUserRolesinRemote) {
587 RemoteRoleV1 role = new RemoteRoleV1();
588 role.setId(eprole.getId());
589 role.setName(eprole.getName());
590 updatedUserRolesinRemoteV1.add(role);
592 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
594 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
595 String.format("/user/%s/roles", userId));
596 return updateUserRolesInEcomp;
599 private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
600 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
601 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
602 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
606 private void createNewUserOnRemoteApp(String userId, FnApp app,
607 ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
610 FnUser client = fnUserService.loadUserByUsername(userId);
612 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
614 if (client == null) {
615 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
616 logger.error(EELFLoggerDelegate.errorLogger, msg);
617 throw new Exception(msg);
620 client.setLoginId(userId);
621 client.setActiveYn(true);
624 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
625 logger.debug(EELFLoggerDelegate.debugLogger,
626 "about to post new client to remote application, users json = " + userInString);
627 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
631 private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
632 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
633 if (roleInAppForUser.getIsApplied()) {
640 private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
641 Set<EcompRole> existingUserRoles = new TreeSet<>();
642 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
643 if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
644 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
645 EcompRole ecompRole = new EcompRole();
646 ecompRole.setId(roleInAppForUser.getRoleId());
647 ecompRole.setName(roleInAppForUser.getRoleName());
648 existingUserRoles.add(ecompRole);
651 return existingUserRoles;
654 private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
655 List<EpUserRolesRequest> epRequestIdVal;
657 epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
658 if (epRequestIdVal.size() > 0) {
659 EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
660 epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
661 epAppRolesRequestData.setRequestStatus("O");
662 epAppRolesRequestData.setUserId(user);
663 epUserRolesRequestService.saveOne(epAppRolesRequestData);
664 List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
665 .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
666 if (epUserAppRolesDetailList.size() > 0) {
667 for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
668 epRequestUpdateList.setRequestType("O");
669 epRequestUpdateList.setReqId(epAppRolesRequestData);
670 epRequestUpdateList.setReqId(epAppRolesRequestData);
671 epUserRolesRequestDetService.saveOne(epRequestUpdateList);
673 logger.debug(EELFLoggerDelegate.debugLogger,
674 "User App roles request from User Page is overridden");
678 } catch (Exception e) {
679 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
683 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
684 return constructUsersEcompRoles(roleInAppForUserList);
687 private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
688 Set<EcompRole> existingUserRoles = new TreeSet<>();
689 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
690 if (roleInAppForUser.getIsApplied()) {
691 EcompRole ecompRole = new EcompRole();
692 ecompRole.setId(roleInAppForUser.getRoleId());
693 ecompRole.setName(roleInAppForUser.getRoleName());
694 existingUserRoles.add(ecompRole);
697 return existingUserRoles;
700 public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
701 Set<EcompRole> userRolesInRemoteApp) {
702 RolesInAppForUser result;
703 result = new RolesInAppForUser();
704 result.setAppId(appId);
705 result.setOrgUserId(userId);
707 for (EcompRole role : userRolesInRemoteApp) {
708 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
709 roleInAppForUser.setRoleId(role.getId());
710 roleInAppForUser.setRoleName(role.getName());
711 roleInAppForUser.setIsApplied(true);
712 result.getRoles().add(roleInAppForUser);
717 private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
718 boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
719 boolean isLoggedInUserRoleAdminofApp) throws Exception {
721 List<FnUser> userInfo = checkIfUserExists(orgUserId);
722 if (userInfo.isEmpty()) {
723 createLocalUserIfNecessary(orgUserId, isSystemUser);
726 if (EPCommonSystemProperties
727 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
731 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
735 ObjectMapper mapper = new ObjectMapper();
736 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
737 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
738 ResponseEntity<String> getResponse = externalAccessRolesService
739 .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
741 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
742 String res = getResponse.getBody();
744 JSONArray extRoles = null;
745 if (!res.equals("{}")) {
746 jsonObj = new JSONObject(res);
747 extRoles = jsonObj.getJSONArray("role");
749 ExternalAccessUserRoleDetail userRoleDetail;
750 if (extRoles != null) {
751 for (int i = 0; i < extRoles.length(); i++) {
752 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
753 && !extRoles.getJSONObject(i).getString("name")
754 .equals(app.getAuthNamespace() + ".admin")
755 && !extRoles.getJSONObject(i).getString("name")
756 .equals(app.getAuthNamespace() + ".owner")) {
757 if (extRoles.getJSONObject(i).has("description")) {
758 ExternalRoleDescription desc = new ExternalRoleDescription(
759 extRoles.getJSONObject(i).getString("description"));
760 userRoleDetail = new ExternalAccessUserRoleDetail(
761 extRoles.getJSONObject(i).getString("name"), desc);
762 userRoleDetailList.add(userRoleDetail);
764 userRoleDetail = new ExternalAccessUserRoleDetail(
765 extRoles.getJSONObject(i).getString("name"), null);
766 userRoleDetailList.add(userRoleDetail);
773 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
774 userRoleDetailList, app);
776 List<EcompUserAppRoles> userAppList;
777 // If request coming from portal not from external role approval system then we have to check if user already
778 // have account admin or system admin as GUI will not send these roles
779 if (!isPortalRequest) {
780 FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
781 userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
782 if (!roleInAppUser.isEmpty()) {
783 for (EcompUserAppRoles userApp : userAppList) {
784 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
785 || userApp.getRoleId()
786 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
787 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
788 addSpecialRole.setIsApplied(true);
789 addSpecialRole.setRoleId(userApp.getRoleId());
790 addSpecialRole.setRoleName(userApp.getRoleName());
791 roleInAppUser.add(addSpecialRole);
796 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
797 .collect(Collectors.toList());
798 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
799 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
800 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
801 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
802 "_"), roleInAppUserNew);
804 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
805 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
806 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
809 if (isLoggedInUserRoleAdminofApp) {
810 if (deletedRolesByApprover.size() > 0) {
811 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
812 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
813 for (EcompRole role : deletedRolesByApprover) {
814 if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
815 .equals(role.getName())) {
816 newUpdatedRoles.add(userRole);
820 if (newUpdatedRoles.size() > 0) {
821 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
823 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
824 currentUserRolesToUpdate = new HashMap<>();
829 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
830 currentUserRolesToUpdate = new HashMap<>();
835 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
836 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
837 if (!(currentUserRolesToUpdate
838 .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
839 HttpEntity<String> entity = new HttpEntity<>(headers);
840 logger.debug(EELFLoggerDelegate.debugLogger,
841 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
843 ResponseEntity<String> deleteResponse = template.exchange(
845 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
846 + "userRole/" + name + "/" + userRole.getName(),
847 HttpMethod.DELETE, entity, String.class);
848 logger.debug(EELFLoggerDelegate.debugLogger,
849 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
850 userRole.getName(), deleteResponse.getBody());
853 // Check if user roles does not exists in External Central Auth System add them all
854 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
855 if (!(currentUserRolesInExternalSystem
856 .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
857 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
859 ExternalAccessUser extUser = new ExternalAccessUser(name,
860 app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
861 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
863 String formattedUserRole = mapper.writeValueAsString(extUser);
864 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
865 logger.debug(EELFLoggerDelegate.debugLogger,
866 "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
867 name, addUserRole.getRoleName());
868 ResponseEntity<String> addResponse = template
869 .exchange(SystemProperties
870 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
871 + "userRole", HttpMethod.POST, entity, String.class);
872 logger.debug(EELFLoggerDelegate.debugLogger,
873 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
874 addResponse.getBody(), addUserRole.getRoleName());
875 if (addResponse.getStatusCode().value() != 201
876 && addResponse.getStatusCode().value() != 404) {
877 logger.debug(EELFLoggerDelegate.debugLogger,
878 "Finished POST operation in external system but unable to save user role",
879 addResponse.getBody(),
880 addUserRole.getRoleName());
881 throw new Exception(addResponse.getBody());
885 } catch (HttpClientErrorException e) {
886 logger.error(EELFLoggerDelegate.errorLogger,
887 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
889 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
890 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
892 throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
893 "Please enter the valid systemUser");
895 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
896 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
897 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
899 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
901 } catch (Exception e) {
902 logger.error(EELFLoggerDelegate.errorLogger,
903 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
905 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
910 private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
911 List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
912 Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
913 //Add Account Admin role for partner app to prevent conflict
914 if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
915 FnRole role = new FnRole();
916 role.setRoleName(PortalConstants.ADMIN_ROLE
917 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
918 epRoleList.put(role.getRoleName(), role);
920 userRoleDetailList.removeIf(
921 userRoleDetail -> !epRoleList
922 .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
923 return userRoleDetailList;
926 private List<FnUser> checkIfUserExists(String userParams) {
927 return fnUserService.getUserWithOrgUserId(userParams);
931 private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
932 if (StringUtils.isEmpty(userId)) {
933 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
937 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
938 if (userList.size() == 0) {
941 client = fnUserService.loadUserByUsername(userId);
943 client = new FnUser();
944 client.setOrgUserId(userId);
945 client.setIsSystemUser(true);
946 client.setFirstName(userId.substring(0, userId.indexOf("@")));
948 if (client == null) {
949 String msg = "createLocalUserIfNecessary: cannot create user " + userId
950 + ", because not found in phonebook";
951 logger.error(EELFLoggerDelegate.errorLogger, msg);
953 client.setLoginId(userId);
954 client.setActiveYn(true);
956 fnUserService.saveFnUser(client);
958 } catch (Exception e) {
959 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
964 private FnUser checkIfRemoteUserExits(String userId, FnApp app,
965 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
966 FnUser checkRemoteUser = null;
968 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
969 } catch (HTTPException e) {
970 // Some apps are returning 400 if user is not found.
971 if (e.getResponseCode() == 400) {
972 logger.debug(EELFLoggerDelegate.debugLogger,
973 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
975 } else if (e.getResponseCode() == 404) {
976 logger.debug(EELFLoggerDelegate.debugLogger,
977 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
980 // Other response code, let it come thru.
984 return checkRemoteUser;
987 private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
988 throws HTTPException {
989 if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
990 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
991 if (userList != null && !userList.isEmpty()) {
992 return userList.get(0);
997 return getUser(userId, app, applicationsRestClientService);
1000 private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
1001 boolean externalSystemRequest, String reqType, boolean isSystemUser,
1002 Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
1003 boolean result = false;
1004 String userId = rolesInAppForUser.getOrgUserId();
1005 Long appId = rolesInAppForUser.getAppId();
1006 synchronized (syncRests) {
1007 createLocalUserIfNecessary(userId, isSystemUser);
1009 EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1011 i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1012 RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1013 EcompRole role = new EcompRole();
1014 role.setId(roleInAppForUser.getRoleId());
1015 role.setName(roleInAppForUser.getRoleName());
1016 userAppRoles[i] = role;
1019 EcompRole[] applicationRoles = null;
1021 if (isLoggedInUserRoleAdminOfApp) {
1022 List<EcompRole> roles = Arrays.stream(userAppRoles)
1023 .collect(Collectors.toList());
1024 List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1025 roles.addAll(roles1);
1026 applicationRoles = roles.toArray(new EcompRole[0]);
1029 syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1030 reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1032 } catch (Exception e) {
1033 logger.error(EELFLoggerDelegate.errorLogger,
1034 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1036 if ("DELETE".equals(reqType)) {
1037 throw new Exception(e.getMessage());
1044 private void syncUserRoles(String userId, Long appId,
1045 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1046 EcompRole[] appRoles) throws Exception {
1048 Transaction transaction = null;
1050 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1051 List<FnRole> roleInfo = externalAccessRolesService
1052 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1053 FnRole adminRole = new FnRole();
1054 if (roleInfo.size() > 0) {
1055 adminRole = roleInfo.get(0);
1056 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1059 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1060 if (userList.size() > 0) {
1061 FnUser client = userList.get(0);
1062 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1063 List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1065 .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1066 .setParameter("appId", appId)
1067 .setParameter("userId", client.getId())
1070 if ("DELETE".equals(reqType)) {
1071 for (FnUserRole userAppRoleList : userRoles) {
1072 List<FnRole> rolesList =
1073 (!userAppRoleList.getRoleId().getRoleName()
1074 .equals(adminRole.getRoleName()))
1075 ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1076 (userAppRoleList.getRoleId().getRoleName(), appId)
1077 : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1078 if (!rolesList.isEmpty()) {
1079 checkIfRoleInactive(rolesList.get(0));
1084 if (appRoles != null) {
1085 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1086 List<FnUserRole> finalUserRolesList = new ArrayList<>();
1087 if (checkIfUserisRoleAdmin) {
1088 for (EcompRole role : appRolesList) {
1089 for (FnUserRole userAppRoleList : userRoles) {
1090 if (userAppRoleList.getRoleId().getRoleName()
1091 .equals(role.getName())) {
1092 finalUserRolesList.add(userAppRoleList);
1097 userRoles = new ArrayList<>(finalUserRolesList);
1101 for (FnUserRole userRole : userRoles) {
1102 if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1103 && !PortalConstants.SYS_ADMIN_ROLE_ID
1104 .equals(userRole.getRoleId().getId())
1105 && !extRequestValue) {
1106 syncUserRolesExtension(userRole, appId,
1107 newUserAppRolesMap);
1108 } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1109 || "DELETE".equals(reqType))) {
1110 syncUserRolesExtension(userRole, appId,
1111 newUserAppRolesMap);
1112 } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1113 .equals(userRole.getRoleId().getId())) {
1114 syncUserRolesExtension(userRole, appId,
1115 newUserAppRolesMap);
1119 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1120 if (newRolesToAdd.size() > 0) {
1121 FnApp app = fnAppService.getById(appId);
1123 HashMap<Long, FnRole> rolesMap = new HashMap<>();
1124 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1125 String appIdValue = "";
1126 if (!extRequestValue) {
1127 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1129 @SuppressWarnings("unchecked")
1130 List<FnRole> roles = entityManager
1132 "from " + FnRole.class.getName() + " where appId is null "
1133 + appIdValue).getResultList();
1134 for (FnRole role : roles) {
1136 rolesMap.put(role.getId(), role);
1138 } else { // remote app
1139 @SuppressWarnings("unchecked")
1140 List<FnRole> roles = entityManager
1141 .createQuery("from EPRole where appId=:appId")
1142 .setParameter("appId", appId)
1144 for (FnRole role : roles) {
1145 if (!extRequestValue && app.getAuthCentral()) {
1146 rolesMap.put(role.getId(), role);
1148 rolesMap.put(role.getAppRoleId(), role);
1154 for (EcompRole userRole : newRolesToAdd) {
1155 FnUserRole userApp = new FnUserRole();
1156 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1157 .equals(adminRole.getRoleName())) {
1158 role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1159 userApp.setRoleId(role);
1160 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1161 && !extRequestValue) {
1163 } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1164 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1167 userApp.setRoleId(rolesMap.get(userRole.getId()));
1170 userApp.setUserId(client);
1171 userApp.setFnAppId(app);
1172 fnUserRoleService.saveOne(userApp);
1175 if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1177 * for local app -- hack - always make sure fn_role
1178 * table's app_id is null and not 1 for primary app in
1179 * this case being onap portal app; reason: hibernate
1180 * is rightly setting this to 1 while persisting to
1181 * fn_role as per the mapping but SDK role management
1182 * code expects the app_id to be null as there is no
1183 * concept of App_id in SDK
1185 Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1186 query.executeUpdate();
1190 transaction.commit();
1191 } catch (Exception e) {
1192 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1193 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1194 EcompPortalUtils.rollbackTransaction(transaction,
1195 "Exception occurred in syncUserRoles, Details: " + e.toString());
1196 if ("DELETE".equals(reqType)) {
1197 throw new SyncUserRolesException(e.getMessage());
1202 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1203 HashMap<Long, EcompRole> result = new HashMap<>();
1204 if (ecompRoles != null) {
1205 for (EcompRole ecompRole : ecompRoles) {
1206 if (ecompRole.getId() != null) {
1207 result.put(ecompRole.getId(), ecompRole);
1214 private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1215 HashMap<Long, EcompRole> newUserAppRolesMap) {
1218 if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1219 userAppRoleId = userRole.getRoleId().getId();
1220 } else { // remote app
1221 userAppRoleId = userRole.getId();
1224 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1225 fnUserRoleService.deleteById(userRole.getId());
1227 newUserAppRolesMap.remove(userAppRoleId);
1231 private Role fnRoleToRole(final FnRole role) {
1232 return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null, role.getActiveYn(),
1233 role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1236 @SuppressWarnings("unchecked")
1237 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue, Long userId) {
1238 List<RoleInAppForUser> rolesInAppForUser = null;
1239 FnApp app = fnAppService.getById(appId);
1240 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1242 // for onap portal app, no need to make a remote call
1243 List<Role> roleList = new ArrayList<>();
1244 if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1245 if (app.getAuthCentral()) {
1246 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1247 for (CentralV2Role cenRole : cenRoleList) {
1248 Role role = new Role();
1249 role.setActiveYn(cenRole.isActive());
1250 role.setId(cenRole.getId());
1251 role.setRoleName(cenRole.getName());
1252 role.setPriority(cenRole.getPriority());
1256 Optional<FnUser> user = fnUserService.getUser(userId);
1257 if (user.isPresent()) {
1258 roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole).collect(Collectors.toList());
1261 List<Role> activeRoleList = new ArrayList<>();
1262 for (Role role : roleList) {
1263 if (role.getActiveYn()) {
1264 if (role.getId() != 1) { // prevent portal admin from being added
1265 activeRoleList.add(role);
1266 } else if (extRequestValue) {
1267 activeRoleList.add(role);
1272 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1273 // If localUser does not exists return roles
1274 Set<FnRole> roleSet = null;
1275 FnRole[] roleSetList = null;
1276 if (localUser != null) {
1277 roleSet = localUser.getAppEPRoles(app);
1278 roleSetList = roleSet.toArray(new FnRole[0]);
1280 rolesInAppForUser = fnUserRoleService
1281 .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1282 return rolesInAppForUser;
1285 EcompRole[] appRoles = null;
1286 boolean checkIfUserIsApplicationAccAdmin = false;
1287 List<EcompRole> roles = new ArrayList<>();
1288 if (app.getAuthCentral()) {
1289 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1290 FnApp application = fnAppService.getById(appId);
1291 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1294 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1295 for (FnRole role : applicationRoles) {
1296 List<EpAppFunction> cenRoleFuncList = epAppFunctionService.getAppRoleFunctionList(role.getId(), app.getId());
1297 for (EpAppFunction roleFunc : cenRoleFuncList) {
1299 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1300 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1301 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1302 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1303 String name = roleFunc.getFunctionName();
1305 FnFunction function = new FnFunction();
1306 function.setAction(action);
1307 function.setType(type);
1308 function.setCode(functionCode);
1309 function.setName(name);
1310 role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1313 roleSetWithFunctioncds.add(role);
1318 for (FnRole role1 : roleSetWithFunctioncds) {
1319 EcompRole ecompRole = new EcompRole();
1320 ecompRole.setId(role1.getId());
1321 ecompRole.setName(role1.getRoleName());
1322 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1323 roles.add(ecompRole);
1326 if (checkIfUserIsApplicationAccAdmin) {
1327 appRoles = roles.toArray(new EcompRole[roles.size()]);
1328 logger.debug(EELFLoggerDelegate.debugLogger,
1329 "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1330 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1331 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1332 List<String> roleAdminAppRolesNames = new ArrayList<>();
1334 "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1335 + " where fu.role_id = ep.role_id"
1336 + " and fu.app_id = ep.app_id"
1337 + " and fu.user_id = :userId"
1338 + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1339 + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1342 + " 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"
1343 + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1344 List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1345 .setParameter("userId", userId)
1347 List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1348 .collect(Collectors.toList());
1350 List<EcompRole> userapproverRolesList = new ArrayList<>();
1351 for (String str : getUserApproverRoles) {
1352 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1353 if (epRole != null) {
1354 userapproverRolesList.add(epRole);
1357 for (EcompRole role : userapproverRolesList) {
1359 List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1360 boolean checkIfFunctionsExits = roleFunList.stream()
1361 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1362 if (checkIfFunctionsExits) {
1363 roleAdminAppRoles.add(role);
1364 List<RoleFunction> filteredList = roleFunList.stream()
1365 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1366 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1367 .collect(Collectors.toList()));
1370 for (String name : roleAdminAppRolesNames) {
1371 roles.stream().filter(x -> name.equals(x.getName())).findAny().ifPresent(roleAdminAppRoles::add);
1374 appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1378 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1380 // Test this error case, for generating an internal ONAP Portal
1382 // EcompRole[] appRoles = null;
1383 // If there is an exception in the rest client api, then null will
1385 if (appRoles != null) {
1386 if (!app.getAuthCentral()) {
1387 syncAppRoles(appId, appRoles);
1389 EcompRole[] userAppRoles = null;
1392 if (app.getAuthCentral()) {
1393 List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1394 List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1395 .createNamedQuery("EPUserAppCurrentRoles")
1396 .setParameter("appId", app.getId())
1397 .setParameter("userId", actualUser.get(0).getId())
1399 List<EcompRole> setUserRoles = new ArrayList<>();
1400 for (EPUserAppCurrentRoles role : userAppsRolesList) {
1401 logger.debug(EELFLoggerDelegate.debugLogger,
1402 "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", 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, 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.retrieveByMenuId(menuId);
1573 int numMenuRoles2 = funcMenuRoles2.size();
1574 logger.debug(EELFLoggerDelegate.debugLogger,
1575 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1576 fnMenuFunctionalRolesService.delete(funcMenuRole);
1578 if (numMenuRoles2 == 1) {
1579 // If this is the only role for this menu item, then
1580 // the app and roles will be gone,
1581 // so must null out the url too, to be consistent
1582 logger.debug(EELFLoggerDelegate.debugLogger,
1583 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1584 List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1585 if (funcMenuItems.size() > 0) {
1586 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1587 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1588 funcMenuItem.setUrl("");
1592 boolean isPortalRequest = true;
1593 deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1594 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
1595 fnRoleService.delete(role);
1596 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1599 for (EcompRole role : newRolesToAdd) {
1600 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
1601 FnRole newRole = new FnRole();
1602 // Attention! All roles from remote application supposed to be
1604 newRole.setActiveYn(true);
1605 newRole.setRoleName(role.getName());
1606 newRole.setAppId(appId);
1607 newRole.setAppRoleId(role.getId());
1608 fnRoleService.saveOne(newRole);
1610 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1611 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1612 } catch (Exception e) {
1613 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1614 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1615 throw new Exception(e);
1619 private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1621 Session localSession = entityManager.unwrap(Session.class);
1625 // It should delete only when it portal's roleId
1626 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1627 // Delete from fn_role_function
1628 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1629 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1630 query = localSession.createSQLQuery(sql);
1631 query.executeUpdate();
1632 // Delete from fn_role_composite
1633 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1634 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1635 query = localSession.createSQLQuery(sql);
1636 query.executeUpdate();
1638 // Delete from ep_app_role_function
1639 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1640 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1641 query = localSession.createSQLQuery(sql);
1642 query.executeUpdate();
1643 // Delete from ep_role_notification
1644 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1645 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1646 query = localSession.createSQLQuery(sql);
1647 query.executeUpdate();
1648 // Delete from fn_user_pseudo_role
1649 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1650 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1651 query = localSession.createSQLQuery(sql);
1652 query.executeUpdate();
1653 // Delete form EP_WIDGET_CATALOG_ROLE
1654 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1655 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1656 query = localSession.createSQLQuery(sql);
1657 query.executeUpdate();
1658 // Delete form EP_WIDGET_CATALOG_ROLE
1659 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1660 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1661 query = localSession.createSQLQuery(sql);
1662 query.executeUpdate();
1663 if (!isPortalRequest) {
1664 // Delete form fn_menu_functional_roles
1665 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1666 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1667 query = localSession.createSQLQuery(sql);
1668 query.executeUpdate();
1670 } catch (Exception e) {
1671 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1672 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1676 private void checkIfRoleInactive(FnRole epRole) throws Exception {
1677 if (!epRole.getActiveYn()) {
1678 throw new Exception(epRole.getRoleName() + " role is unavailable");
1682 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1683 boolean result = false;
1684 // No changes if no new roles list or no userId.
1685 if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1686 && newAppsListWithAdminRoles.getAppsRoles() != null) {
1687 synchronized (syncRests) {
1688 List<FnApp> apps = fnAppService.getAppsFullList();
1689 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1690 for (FnApp app : apps) {
1691 enabledApps.put(app.getId(), app);
1693 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1694 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1695 // user Admin role may be added only for enabled apps
1696 if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1697 newAppsWhereUserIsAdmin.add(adminRole);
1701 boolean createNewUser = false;
1702 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1703 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1704 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1705 if (localUserList.size() > 0) {
1706 FnUser tmpUser = localUserList.get(0);
1707 oldAppsWhereUserIsAdmin = fnUserRoleService.retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1708 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1711 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1712 // we create new user only if he has Admin Role for any App
1713 createNewUser = true;
1715 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1716 oldAppsWhereUserIsAdmin);
1724 public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1725 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1726 List<FnUserRole> oldAppsWhereUserIsAdmin) {
1727 if (user != null || createNewUser) {
1728 if (createNewUser) {
1729 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1731 user.setActiveYn(true);
1734 for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1735 // user Admin role may be deleted only for enabled
1737 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1738 fnUserRoleService.saveOne(oldUserApp);
1741 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1742 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1743 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1744 FnUserRole newUserApp = new FnUserRole();
1745 newUserApp.setUserId(user);
1746 newUserApp.setFnAppId(app);
1747 newUserApp.setRoleId(role);
1748 fnUserRoleService.saveOne(newUserApp);
1750 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1751 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1759 public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1760 boolean result = false;
1762 // Reset All admin role for centralized applications
1763 List<FnApp> appList = fnAppService.getCentralizedApps();
1764 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1765 for (FnApp app : appList) {
1767 if (EPCommonSystemProperties
1768 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1769 name = user.getOrgUserId() + SystemProperties
1770 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1772 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1773 HttpEntity<String> entity = new HttpEntity<>(headers);
1774 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1776 ResponseEntity<String> getResponse = template
1777 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1778 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1780 if (getResponse.getBody().equals("{}")) {
1781 String addDesc = "{\"name\":\"" + extRole + "\"}";
1782 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1784 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1786 HttpMethod.POST, roleEntity, String.class);
1789 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1791 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1792 + "userRole/" + name + "/" + extRole,
1793 HttpMethod.DELETE, deleteUserRole, String.class);
1794 } catch (Exception e) {
1795 logger.error(EELFLoggerDelegate.errorLogger,
1796 " Role not found for this user may be it gets deleted before", e);
1799 } catch (Exception e) {
1800 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1801 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1802 app.getAuthNamespace(), e.getMessage());
1804 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1805 app.getAuthNamespace(), e);
1809 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1810 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1812 if (app.getAuthCentral()) {
1813 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1814 HttpEntity<String> entity = new HttpEntity<>(headers);
1816 if (EPCommonSystemProperties
1817 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1818 name = user.getOrgUserId() + SystemProperties
1819 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1821 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1822 ResponseEntity<String> getUserRolesResponse = template.exchange(
1823 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1824 + "userRoles/user/" + name,
1825 HttpMethod.GET, entity, String.class);
1826 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1827 if (!getUserRolesResponse.getBody().equals("{}")) {
1828 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1829 JSONArray extRoles = jsonObj.getJSONArray("userRole");
1830 final Map<String, JSONObject> extUserRoles = new HashMap<>();
1831 for (int i = 0; i < extRoles.length(); i++) {
1832 String userRole = extRoles.getJSONObject(i).getString("role");
1833 if (userRole.startsWith(app.getAuthNamespace() + ".")
1834 && !userRole.equals(app.getAuthNamespace() + ".admin")
1835 && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1837 extUserRoles.put(userRole, extRoles.getJSONObject(i));
1840 if (!extUserRoles.containsKey(extRole)) {
1841 // Assign with new apps user admin
1843 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1844 // Assign user role for an application in external access system
1845 ObjectMapper addUserRoleMapper = new ObjectMapper();
1846 String userRole = addUserRoleMapper.writeValueAsString(extUser);
1847 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1849 SystemProperties.getProperty(
1850 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1851 HttpMethod.POST, addUserRole, String.class);
1852 } catch (Exception e) {
1853 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1860 } catch (Exception e) {
1861 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1862 logger.debug(EELFLoggerDelegate.errorLogger,
1863 "Application name space not found in External system for app {} due to bad rquest name space ",
1864 app.getAuthNamespace(), e.getMessage());
1866 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1867 app.getAuthNamespace(), e);
1872 } catch (Exception e) {
1874 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);