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.transport.AppNameIdIsAdmin;
82 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
83 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
84 import org.onap.portal.domain.dto.transport.CentralV2Role;
85 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
86 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
87 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
88 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
89 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
90 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
91 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
92 import org.onap.portal.domain.dto.transport.Role;
93 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
94 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
95 import org.onap.portal.exception.DeleteDomainObjectFailedException;
96 import org.onap.portal.exception.RoleFunctionException;
97 import org.onap.portal.exception.SyncUserRolesException;
98 import org.onap.portal.logging.format.EPAppMessagesEnum;
99 import org.onap.portal.logging.logic.EPLogUtil;
100 import org.onap.portal.service.appFunction.EpAppFunctionService;
101 import org.onap.portal.service.roleFunction.FnRoleFunctionService;
102 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
103 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
104 import org.onap.portal.service.app.FnAppService;
105 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
106 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
107 import org.onap.portal.service.role.FnRoleService;
108 import org.onap.portal.service.userRole.FnUserRoleService;
109 import org.onap.portal.service.user.FnUserService;
110 import org.onap.portal.utils.EPCommonSystemProperties;
111 import org.onap.portal.utils.EPUserUtils;
112 import org.onap.portal.utils.EcompPortalUtils;
113 import org.onap.portal.utils.PortalConstants;
114 import org.onap.portalsdk.core.domain.RoleFunction;
115 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
116 import org.onap.portalsdk.core.restful.domain.EcompRole;
117 import org.onap.portalsdk.core.util.SystemProperties;
118 import org.springframework.beans.factory.annotation.Autowired;
119 import org.springframework.http.HttpEntity;
120 import org.springframework.http.HttpHeaders;
121 import org.springframework.http.HttpMethod;
122 import org.springframework.http.HttpStatus;
123 import org.springframework.http.ResponseEntity;
124 import org.springframework.stereotype.Service;
125 import org.springframework.transaction.annotation.Transactional;
126 import org.springframework.web.client.HttpClientErrorException;
127 import org.springframework.web.client.RestTemplate;
131 public class AdminRolesService {
133 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
134 private static final Object syncRests = new Object();
135 private final RestTemplate template = new RestTemplate();
137 private Long SYS_ADMIN_ROLE_ID = 38L;
138 private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
139 private final Long ECOMP_APP_ID = 1L;
140 private final String ADMIN_ACCOUNT = "Is account admin for user {}";
142 private final AppsCacheService appsCacheService;
143 private final EntityManager entityManager;
144 private final FnUserService fnUserService;
145 private final FnRoleService fnRoleService;
146 private final FnAppService fnAppService;
147 private final FnRoleFunctionService fnRoleFunctionService;
148 private final FnMenuFunctionalService fnMenuFunctionalService;
149 private final FnUserRoleService fnUserRoleService;
150 private final EpAppFunctionService epAppFunctionService;
151 private final EcompUserAppRolesService ecompUserAppRolesService;
152 private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
153 private final ApplicationsRestClientService applicationsRestClientService;
154 private final EpUserRolesRequestDetService epUserRolesRequestDetService;
155 private final ExternalAccessRolesService externalAccessRolesService;
156 private final EpUserRolesRequestService epUserRolesRequestService;
159 public AdminRolesService(AppsCacheService appsCacheService,
160 final EntityManager entityManager,
161 final FnUserService fnUserService, FnRoleService fnRoleService,
162 FnAppService fnAppService,
163 FnRoleFunctionService fnRoleFunctionService, FnMenuFunctionalService fnMenuFunctionalService,
164 final FnUserRoleService fnUserRoleService,
165 EpAppFunctionService epAppFunctionService,
166 EcompUserAppRolesService ecompUserAppRolesService,
167 FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
168 ApplicationsRestClientService applicationsRestClientService,
169 EpUserRolesRequestDetService epUserRolesRequestDetService,
170 ExternalAccessRolesService externalAccessRolesService,
171 EpUserRolesRequestService epUserRolesRequestService) {
172 this.appsCacheService = appsCacheService;
173 this.entityManager = entityManager;
174 this.fnUserService = fnUserService;
175 this.fnRoleService = fnRoleService;
176 this.fnAppService = fnAppService;
177 this.fnRoleFunctionService = fnRoleFunctionService;
178 this.fnMenuFunctionalService = fnMenuFunctionalService;
179 this.fnUserRoleService = fnUserRoleService;
180 this.epAppFunctionService = epAppFunctionService;
181 this.ecompUserAppRolesService = ecompUserAppRolesService;
182 this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
183 this.applicationsRestClientService = applicationsRestClientService;
184 this.epUserRolesRequestDetService = epUserRolesRequestDetService;
185 this.externalAccessRolesService = externalAccessRolesService;
186 this.epUserRolesRequestService = epUserRolesRequestService;
189 public boolean isSuperAdmin(final String loginId) {
190 boolean isSuperAdmin;
192 isSuperAdmin = fnUserRoleService
193 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
194 } catch (Exception e) {
195 logger.error("isSuperAdmin exception: " + e.toString());
198 logger.info("isSuperAdmin " + isSuperAdmin);
202 public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
204 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
205 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
206 logger.debug(EELFLoggerDelegate.debugLogger,
207 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
208 orgUserId, userAdminApps.size());
210 for (FnUserRole userApp : userApps) {
211 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
212 userAdminApps.size() > 1)) {
213 logger.debug(EELFLoggerDelegate.debugLogger,
214 "Is account admin for userAdminApps() - for user {}, found Id {}",
215 orgUserId, userApp.getRoleId().getId());
219 } catch (Exception e) {
220 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
221 logger.error(EELFLoggerDelegate.errorLogger,
222 "Exception occurred while executing isAccountAdmin operation",
228 public boolean isUser(final long userId) {
230 FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
231 if (currentUser != null && currentUser.getId() != null) {
232 for (FnUserRole userApp : currentUser.getUserApps()) {
233 if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
234 FnRole role = userApp.getRoleId();
235 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
236 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
237 if (role.getActiveYn()) {
244 } catch (Exception e) {
245 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
246 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
252 public boolean isRoleAdmin(Long userId) {
254 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
255 List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
256 logger.debug(EELFLoggerDelegate.debugLogger,
257 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
258 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
259 Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
260 Set<String> roleFunSet;
261 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
262 .collect(Collectors.toSet());
263 if (!roleFunSet.isEmpty()) {
264 for (String roleFunction : roleFunSet) {
265 String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
266 getRoleFuncListOfPortalSet1.add(type);
270 boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
271 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
272 logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
273 checkIfFunctionsExits);
275 return checkIfFunctionsExits;
277 } catch (Exception e) {
278 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
279 logger.error(EELFLoggerDelegate.errorLogger,
280 "Exception occurred while executing isRoleAdmin operation",
286 private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
287 boolean isApplicationAccountAdmin = false;
289 logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
290 List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
291 if (!userAdminApps.isEmpty()) {
292 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
293 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
296 } catch (Exception e) {
297 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
298 logger.error(EELFLoggerDelegate.errorLogger,
299 "Exception occurred while executing isAccountAdminOfApplication operation", e);
301 logger.debug(EELFLoggerDelegate.debugLogger,
302 "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
304 return isApplicationAccountAdmin;
308 private List<Integer> getAdminAppsForTheUser(final Long userId) {
309 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)";
310 return entityManager.createQuery(query, Integer.class)
311 .setParameter("userId", userId).getResultList();
314 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
315 AppWithRolesForUser newAppRolesForUser) {
316 boolean result = false;
317 boolean epRequestValue = false;
319 String reqMessage = "";
320 if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
321 userId = newAppRolesForUser.getOrgUserId().trim();
323 Long appId = newAppRolesForUser.getAppId();
324 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
326 if (userId.length() > 0) {
327 ObjectMapper mapper = new ObjectMapper();
328 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
331 FnApp app = fnAppService.getById(appId);
333 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
335 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
337 boolean checkIfUserIsOnlyRoleAdmin =
338 isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
339 if (checkIfUserIsOnlyRoleAdmin) {
340 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
341 if (!roleInAppForUser.getIsApplied()) {
342 EcompRole ecompRole = new EcompRole();
343 ecompRole.setId(roleInAppForUser.getRoleId());
344 ecompRole.setName(roleInAppForUser.getRoleName());
345 rolesGotDeletedFromApprover.add(ecompRole);
350 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
352 boolean systemUser = newAppRolesForUser.isSystemUser();
354 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
357 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
358 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
359 userRolesInLocalApp);
360 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
361 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
362 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
363 // Apply changes in external Access system
365 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
367 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
369 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
371 systemUser, rolesGotDeletedByApprover, false);
373 } else if (!app.getAuthCentral() && systemUser) {
374 throw new Exception("For non-centralized application we cannot add systemUser");
375 } else { // if centralized app
376 if (app.getAuthCentral()) {
377 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
378 pushRemoteUser(roleInAppForUserList, userId, app, mapper,
379 applicationsRestClientService, false);
382 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
383 roleInAppForUserList);
384 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
386 userRolesInLocalApp);
387 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
388 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
390 // Apply changes in external Access system
391 updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
393 epRequestValue, false, rolesGotDeletedFromApprover,
394 checkIfUserIsOnlyRoleAdmin);
396 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
397 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
398 checkIfUserIsOnlyRoleAdmin);
400 // In case if portal is not centralized then follow existing approach
401 else if (!app.getAuthCentral() && app.getId()
402 .equals(PortalConstants.PORTAL_APP_ID)) {
403 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
404 roleInAppForUserList);
405 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
407 userRolesInLocalApp);
408 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
409 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
410 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
411 } else {// remote app
412 FnUser remoteAppUser;
413 if (!app.getAuthCentral() && !app.getId()
414 .equals(PortalConstants.PORTAL_APP_ID)) {
416 remoteAppUser = checkIfRemoteUserExits(userId, app,
417 applicationsRestClientService);
419 if (remoteAppUser == null) {
420 addRemoteUser(roleInAppForUserList, userId, app,
421 mapper, applicationsRestClientService);
423 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
424 roleInAppForUserList, mapper,
425 applicationsRestClientService, appId, userId);
426 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
428 userRolesInRemoteApp);
429 Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
430 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
431 epRequestValue, null, false, rolesGotDeletedByApprover, false);
433 // If no roles remain, request app to set user inactive.
434 if (userRolesInRemoteApp.size() == 0) {
435 logger.debug(EELFLoggerDelegate.debugLogger,
436 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
439 postUserToRemoteApp(userId, app,
440 applicationsRestClientService);
445 } catch (Exception e) {
446 String message = String.format(
447 "Failed to create user or update user roles for User %s, AppId %s",
448 userId, Long.toString(appId));
449 logger.error(EELFLoggerDelegate.errorLogger, message, e);
451 reqMessage = e.getMessage();
454 return new ExternalRequestFieldsValidator(result, reqMessage);
458 private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
459 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
461 pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
462 roleInAppForUserList, appRoleIdUsed);
466 private void postUserToRemoteApp(String userId, FnApp app,
467 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
469 getUser(userId, app, applicationsRestClientService);
473 private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
474 throws HTTPException {
475 return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
479 private void pushUserOnRemoteApp(String userId, FnApp app,
480 ApplicationsRestClientService applicationsRestClientService,
481 ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
485 client = fnUserService.loadUserByUsername(userId);
487 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
488 if (client == null) {
489 String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
490 logger.error(EELFLoggerDelegate.errorLogger, msg);
491 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
492 if (!userList.isEmpty()) {
493 logger.debug(EELFLoggerDelegate.debugLogger,
494 userList.get(0).getOrgUserId() + " User was found in Portal");
495 client = userList.get(0);
496 client.setUserApps(Collections.EMPTY_SET);
497 client.setIsSystemUser(false);
499 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
500 throw new Exception(msg);
505 client.setLoginId(userId);
506 client.setActiveYn(true);
507 client.setOrgUserId(userId);
509 roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
510 SortedSet<Role> roles = new TreeSet<>();
512 List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
513 List<FnApp> appList = new ArrayList<>();
515 List<CentralV2Role> roleList = new ArrayList<>();
517 List<FnRole> userRoles = new ArrayList<>();
519 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
520 FnRole role = new FnRole();
521 role.setId(roleInappForUser.getRoleId());
522 role.setRoleName(roleInappForUser.getRoleName());
527 List<FnRole> userAppRoles = new ArrayList<>();
528 for (FnRole role : userRoles) {
529 FnRole appRole = getAppRoles.stream()
530 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
532 FnRole epRole = new FnRole();
533 if (appRole != null) {
534 epRole.setId(appRole.getId());
535 epRole.setRoleName(appRole.getRoleName());
537 userAppRoles.add(epRole);
539 userRoles = new ArrayList<>(userAppRoles);
541 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
543 for (CentralV2Role epRole : roleList) {
544 Role role = new Role();
545 FnRole appRole = getAppRoles.stream()
546 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
547 List<FnRoleFunction> fnRoleFunctions = new ArrayList<>();
548 for (DomainVo vo: epRole.getRoleFunctions()){
549 Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
550 roleFunction.ifPresent(fnRoleFunctions::add);
552 if (appRole != null) {
553 role.setId(appRole.getAppRoleId());
554 role.setRoleName(epRole.getName());
555 role.setFnRoleFunctions(new HashSet<>(fnRoleFunctions));
559 client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
561 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
562 logger.debug(EELFLoggerDelegate.debugLogger,
563 "about to post a client to remote application, users json = " + userInString);
564 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
567 private FnRole roleToFnRole(Role role) {
568 return FnRole.builder()
570 .roleName(role.getRoleName())
571 .activeYn(role.getActiveYn())
572 .priority(role.getPriority())
573 .fnRoleFunctions(role.getFnRoleFunctions())
574 .childRoles(role.getChildRoles())
575 .parentRoles(role.getParentRoles())
579 private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
580 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
581 throws JsonProcessingException, HTTPException {
582 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
583 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
584 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
586 externalApp = appsCacheService.getApp(appId);
587 String appBaseUri = null;
588 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
589 if (externalApp != null) {
590 appBaseUri = externalApp.getAppRestEndpoint();
592 if (appBaseUri != null && appBaseUri.endsWith("/api")) {
593 for (EcompRole eprole : updatedUserRolesinRemote) {
594 RemoteRoleV1 role = new RemoteRoleV1();
595 role.setId(eprole.getId());
596 role.setName(eprole.getName());
597 updatedUserRolesinRemoteV1.add(role);
599 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
601 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
602 String.format("/user/%s/roles", userId));
603 return updateUserRolesInEcomp;
606 private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
607 ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
608 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
609 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
613 private void createNewUserOnRemoteApp(String userId, FnApp app,
614 ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
617 FnUser client = fnUserService.loadUserByUsername(userId);
619 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
621 if (client == null) {
622 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
623 logger.error(EELFLoggerDelegate.errorLogger, msg);
624 throw new Exception(msg);
627 client.setLoginId(userId);
628 client.setActiveYn(true);
631 userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
632 logger.debug(EELFLoggerDelegate.debugLogger,
633 "about to post new client to remote application, users json = " + userInString);
634 applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
638 private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
639 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
640 if (roleInAppForUser.getIsApplied()) {
647 private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
648 Set<EcompRole> existingUserRoles = new TreeSet<>();
649 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
650 if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
651 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
652 EcompRole ecompRole = new EcompRole();
653 ecompRole.setId(roleInAppForUser.getRoleId());
654 ecompRole.setName(roleInAppForUser.getRoleName());
655 existingUserRoles.add(ecompRole);
658 return existingUserRoles;
661 private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
662 List<EpUserRolesRequest> epRequestIdVal;
664 epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
665 if (epRequestIdVal.size() > 0) {
666 EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
667 epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
668 epAppRolesRequestData.setRequestStatus("O");
669 epAppRolesRequestData.setUserId(user);
670 epUserRolesRequestService.saveOne(epAppRolesRequestData);
671 List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
672 .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
673 if (epUserAppRolesDetailList.size() > 0) {
674 for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
675 epRequestUpdateList.setRequestType("O");
676 epRequestUpdateList.setReqId(epAppRolesRequestData);
677 epRequestUpdateList.setReqId(epAppRolesRequestData);
678 epUserRolesRequestDetService.saveOne(epRequestUpdateList);
680 logger.debug(EELFLoggerDelegate.debugLogger,
681 "User App roles request from User Page is overridden");
685 } catch (Exception e) {
686 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
690 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
691 return constructUsersEcompRoles(roleInAppForUserList);
694 private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
695 Set<EcompRole> existingUserRoles = new TreeSet<>();
696 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
697 if (roleInAppForUser.getIsApplied()) {
698 EcompRole ecompRole = new EcompRole();
699 ecompRole.setId(roleInAppForUser.getRoleId());
700 ecompRole.setName(roleInAppForUser.getRoleName());
701 existingUserRoles.add(ecompRole);
704 return existingUserRoles;
707 public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
708 Set<EcompRole> userRolesInRemoteApp) {
709 RolesInAppForUser result;
710 result = new RolesInAppForUser();
711 result.setAppId(appId);
712 result.setOrgUserId(userId);
714 for (EcompRole role : userRolesInRemoteApp) {
715 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
716 roleInAppForUser.setRoleId(role.getId());
717 roleInAppForUser.setRoleName(role.getName());
718 roleInAppForUser.setIsApplied(true);
719 result.getRoles().add(roleInAppForUser);
724 private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
725 boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
726 boolean isLoggedInUserRoleAdminofApp) throws Exception {
728 List<FnUser> userInfo = checkIfUserExists(orgUserId);
729 if (userInfo.isEmpty()) {
730 createLocalUserIfNecessary(orgUserId, isSystemUser);
733 if (EPCommonSystemProperties
734 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
738 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
742 ObjectMapper mapper = new ObjectMapper();
743 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
744 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
745 ResponseEntity<String> getResponse = externalAccessRolesService
746 .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
748 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
749 String res = getResponse.getBody();
751 JSONArray extRoles = null;
752 if (!res.equals("{}")) {
753 jsonObj = new JSONObject(res);
754 extRoles = jsonObj.getJSONArray("role");
756 ExternalAccessUserRoleDetail userRoleDetail;
757 if (extRoles != null) {
758 for (int i = 0; i < extRoles.length(); i++) {
759 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
760 && !extRoles.getJSONObject(i).getString("name")
761 .equals(app.getAuthNamespace() + ".admin")
762 && !extRoles.getJSONObject(i).getString("name")
763 .equals(app.getAuthNamespace() + ".owner")) {
764 if (extRoles.getJSONObject(i).has("description")) {
765 ExternalRoleDescription desc = new ExternalRoleDescription(
766 extRoles.getJSONObject(i).getString("description"));
767 userRoleDetail = new ExternalAccessUserRoleDetail(
768 extRoles.getJSONObject(i).getString("name"), desc);
769 userRoleDetailList.add(userRoleDetail);
771 userRoleDetail = new ExternalAccessUserRoleDetail(
772 extRoles.getJSONObject(i).getString("name"), null);
773 userRoleDetailList.add(userRoleDetail);
780 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
781 userRoleDetailList, app);
783 List<EcompUserAppRoles> userAppList;
784 // If request coming from portal not from external role approval system then we have to check if user already
785 // have account admin or system admin as GUI will not send these roles
786 if (!isPortalRequest) {
787 FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
788 userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
789 if (!roleInAppUser.isEmpty()) {
790 for (EcompUserAppRoles userApp : userAppList) {
791 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
792 || userApp.getRoleId()
793 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
794 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
795 addSpecialRole.setIsApplied(true);
796 addSpecialRole.setRoleId(userApp.getRoleId());
797 addSpecialRole.setRoleName(userApp.getRoleName());
798 roleInAppUser.add(addSpecialRole);
803 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
804 .collect(Collectors.toList());
805 Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
806 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
807 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
808 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
809 "_"), roleInAppUserNew);
811 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
812 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
813 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
816 if (isLoggedInUserRoleAdminofApp) {
817 if (deletedRolesByApprover.size() > 0) {
818 List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
819 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
820 for (EcompRole role : deletedRolesByApprover) {
821 if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
822 .equals(role.getName())) {
823 newUpdatedRoles.add(userRole);
827 if (newUpdatedRoles.size() > 0) {
828 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
830 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
831 currentUserRolesToUpdate = new HashMap<>();
836 userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
837 currentUserRolesToUpdate = new HashMap<>();
842 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
843 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
844 if (!(currentUserRolesToUpdate
845 .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
846 HttpEntity<String> entity = new HttpEntity<>(headers);
847 logger.debug(EELFLoggerDelegate.debugLogger,
848 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
850 ResponseEntity<String> deleteResponse = template.exchange(
852 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
853 + "userRole/" + name + "/" + userRole.getName(),
854 HttpMethod.DELETE, entity, String.class);
855 logger.debug(EELFLoggerDelegate.debugLogger,
856 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
857 userRole.getName(), deleteResponse.getBody());
860 // Check if user roles does not exists in External Central Auth System add them all
861 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
862 if (!(currentUserRolesInExternalSystem
863 .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
864 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
866 ExternalAccessUser extUser = new ExternalAccessUser(name,
867 app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
868 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
870 String formattedUserRole = mapper.writeValueAsString(extUser);
871 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
872 logger.debug(EELFLoggerDelegate.debugLogger,
873 "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
874 name, addUserRole.getRoleName());
875 ResponseEntity<String> addResponse = template
876 .exchange(SystemProperties
877 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
878 + "userRole", HttpMethod.POST, entity, String.class);
879 logger.debug(EELFLoggerDelegate.debugLogger,
880 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
881 addResponse.getBody(), addUserRole.getRoleName());
882 if (addResponse.getStatusCode().value() != 201
883 && addResponse.getStatusCode().value() != 404) {
884 logger.debug(EELFLoggerDelegate.debugLogger,
885 "Finished POST operation in external system but unable to save user role",
886 addResponse.getBody(),
887 addUserRole.getRoleName());
888 throw new Exception(addResponse.getBody());
892 } catch (HttpClientErrorException e) {
893 logger.error(EELFLoggerDelegate.errorLogger,
894 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
896 if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
897 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
899 throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
900 "Please enter the valid systemUser");
902 if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
903 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
904 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
906 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
908 } catch (Exception e) {
909 logger.error(EELFLoggerDelegate.errorLogger,
910 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
912 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
917 private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
918 List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
919 Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
920 //Add Account Admin role for partner app to prevent conflict
921 if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
922 FnRole role = new FnRole();
923 role.setRoleName(PortalConstants.ADMIN_ROLE
924 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
925 epRoleList.put(role.getRoleName(), role);
927 userRoleDetailList.removeIf(
928 userRoleDetail -> !epRoleList
929 .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
930 return userRoleDetailList;
933 private List<FnUser> checkIfUserExists(String userParams) {
934 return fnUserService.getUserWithOrgUserId(userParams);
938 private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
939 if (StringUtils.isEmpty(userId)) {
940 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
944 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
945 if (userList.size() == 0) {
948 client = fnUserService.loadUserByUsername(userId);
950 client = new FnUser();
951 client.setOrgUserId(userId);
952 client.setIsSystemUser(true);
953 client.setFirstName(userId.substring(0, userId.indexOf("@")));
955 if (client == null) {
956 String msg = "createLocalUserIfNecessary: cannot create user " + userId
957 + ", because not found in phonebook";
958 logger.error(EELFLoggerDelegate.errorLogger, msg);
960 client.setLoginId(userId);
961 client.setActiveYn(true);
963 fnUserService.saveFnUser(client);
965 } catch (Exception e) {
966 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
971 private FnUser checkIfRemoteUserExits(String userId, FnApp app,
972 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
973 FnUser checkRemoteUser = null;
975 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
976 } catch (HTTPException e) {
977 // Some apps are returning 400 if user is not found.
978 if (e.getResponseCode() == 400) {
979 logger.debug(EELFLoggerDelegate.debugLogger,
980 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
982 } else if (e.getResponseCode() == 404) {
983 logger.debug(EELFLoggerDelegate.debugLogger,
984 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
987 // Other response code, let it come thru.
991 return checkRemoteUser;
994 private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
995 throws HTTPException {
996 if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
997 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
998 if (userList != null && !userList.isEmpty()) {
999 return userList.get(0);
1004 return getUser(userId, app, applicationsRestClientService);
1007 private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
1008 boolean externalSystemRequest, String reqType, boolean isSystemUser,
1009 Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
1010 boolean result = false;
1011 String userId = rolesInAppForUser.getOrgUserId();
1012 Long appId = rolesInAppForUser.getAppId();
1013 synchronized (syncRests) {
1014 createLocalUserIfNecessary(userId, isSystemUser);
1016 EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1018 i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1019 RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1020 EcompRole role = new EcompRole();
1021 role.setId(roleInAppForUser.getRoleId());
1022 role.setName(roleInAppForUser.getRoleName());
1023 userAppRoles[i] = role;
1026 EcompRole[] applicationRoles = null;
1028 if (isLoggedInUserRoleAdminOfApp) {
1029 List<EcompRole> roles = Arrays.stream(userAppRoles)
1030 .collect(Collectors.toList());
1031 List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1032 roles.addAll(roles1);
1033 applicationRoles = roles.toArray(new EcompRole[0]);
1036 syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1037 reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1039 } catch (Exception e) {
1040 logger.error(EELFLoggerDelegate.errorLogger,
1041 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1043 if ("DELETE".equals(reqType)) {
1044 throw new Exception(e.getMessage());
1051 private void syncUserRoles(String userId, Long appId,
1052 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1053 EcompRole[] appRoles) throws Exception {
1055 Transaction transaction = null;
1057 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1058 List<FnRole> roleInfo = externalAccessRolesService
1059 .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1060 FnRole adminRole = new FnRole();
1061 if (roleInfo.size() > 0) {
1062 adminRole = roleInfo.get(0);
1063 logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1066 List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1067 if (userList.size() > 0) {
1068 FnUser client = userList.get(0);
1069 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1070 List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1072 .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1073 .setParameter("appId", appId)
1074 .setParameter("userId", client.getId())
1077 if ("DELETE".equals(reqType)) {
1078 for (FnUserRole userAppRoleList : userRoles) {
1079 List<FnRole> rolesList =
1080 (!userAppRoleList.getRoleId().getRoleName()
1081 .equals(adminRole.getRoleName()))
1082 ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1083 (userAppRoleList.getRoleId().getRoleName(), appId)
1084 : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1085 if (!rolesList.isEmpty()) {
1086 checkIfRoleInactive(rolesList.get(0));
1091 if (appRoles != null) {
1092 List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1093 List<FnUserRole> finalUserRolesList = new ArrayList<>();
1094 if (checkIfUserisRoleAdmin) {
1095 for (EcompRole role : appRolesList) {
1096 for (FnUserRole userAppRoleList : userRoles) {
1097 if (userAppRoleList.getRoleId().getRoleName()
1098 .equals(role.getName())) {
1099 finalUserRolesList.add(userAppRoleList);
1104 userRoles = new ArrayList<>(finalUserRolesList);
1108 for (FnUserRole userRole : userRoles) {
1109 if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1110 && !PortalConstants.SYS_ADMIN_ROLE_ID
1111 .equals(userRole.getRoleId().getId())
1112 && !extRequestValue) {
1113 syncUserRolesExtension(userRole, appId,
1114 newUserAppRolesMap);
1115 } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1116 || "DELETE".equals(reqType))) {
1117 syncUserRolesExtension(userRole, appId,
1118 newUserAppRolesMap);
1119 } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1120 .equals(userRole.getRoleId().getId())) {
1121 syncUserRolesExtension(userRole, appId,
1122 newUserAppRolesMap);
1126 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1127 if (newRolesToAdd.size() > 0) {
1128 FnApp app = fnAppService.getById(appId);
1130 HashMap<Long, FnRole> rolesMap = new HashMap<>();
1131 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1132 String appIdValue = "";
1133 if (!extRequestValue) {
1134 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1136 @SuppressWarnings("unchecked")
1137 List<FnRole> roles = entityManager
1139 "from " + FnRole.class.getName() + " where appId is null "
1140 + appIdValue).getResultList();
1141 for (FnRole role : roles) {
1143 rolesMap.put(role.getId(), role);
1145 } else { // remote app
1146 @SuppressWarnings("unchecked")
1147 List<FnRole> roles = entityManager
1148 .createQuery("from EPRole where appId=:appId")
1149 .setParameter("appId", appId)
1151 for (FnRole role : roles) {
1152 if (!extRequestValue && app.getAuthCentral()) {
1153 rolesMap.put(role.getId(), role);
1155 rolesMap.put(role.getAppRoleId(), role);
1161 for (EcompRole userRole : newRolesToAdd) {
1162 FnUserRole userApp = new FnUserRole();
1163 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1164 .equals(adminRole.getRoleName())) {
1165 role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1166 userApp.setRoleId(role);
1167 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1168 && !extRequestValue) {
1170 } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1171 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1174 userApp.setRoleId(rolesMap.get(userRole.getId()));
1177 userApp.setUserId(client);
1178 userApp.setFnAppId(app);
1179 fnUserRoleService.saveOne(userApp);
1182 if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1184 * for local app -- hack - always make sure fn_role
1185 * table's app_id is null and not 1 for primary app in
1186 * this case being onap portal app; reason: hibernate
1187 * is rightly setting this to 1 while persisting to
1188 * fn_role as per the mapping but SDK role management
1189 * code expects the app_id to be null as there is no
1190 * concept of App_id in SDK
1192 Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1193 query.executeUpdate();
1197 transaction.commit();
1198 } catch (Exception e) {
1199 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1200 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1201 EcompPortalUtils.rollbackTransaction(transaction,
1202 "Exception occurred in syncUserRoles, Details: " + e.toString());
1203 if ("DELETE".equals(reqType)) {
1204 throw new SyncUserRolesException(e.getMessage());
1209 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1210 HashMap<Long, EcompRole> result = new HashMap<>();
1211 if (ecompRoles != null) {
1212 for (EcompRole ecompRole : ecompRoles) {
1213 if (ecompRole.getId() != null) {
1214 result.put(ecompRole.getId(), ecompRole);
1221 private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1222 HashMap<Long, EcompRole> newUserAppRolesMap) {
1225 if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1226 userAppRoleId = userRole.getRoleId().getId();
1227 } else { // remote app
1228 userAppRoleId = userRole.getId();
1231 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1232 fnUserRoleService.deleteById(userRole.getId());
1234 newUserAppRolesMap.remove(userAppRoleId);
1238 private Role fnRoleToRole(final FnRole role) {
1239 return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null,
1241 role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1244 @SuppressWarnings("unchecked")
1245 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue,
1247 List<RoleInAppForUser> rolesInAppForUser = null;
1248 FnApp app = fnAppService.getById(appId);
1249 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1251 // for onap portal app, no need to make a remote call
1252 List<Role> roleList = new ArrayList<>();
1253 if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1254 if (app.getAuthCentral()) {
1255 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1256 for (CentralV2Role cenRole : cenRoleList) {
1257 Role role = new Role();
1258 role.setActiveYn(cenRole.isActive());
1259 role.setId(cenRole.getId());
1260 role.setRoleName(cenRole.getName());
1261 role.setPriority(cenRole.getPriority());
1265 Optional<FnUser> user = fnUserService.getUser(userId);
1266 if (user.isPresent()) {
1267 roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole)
1268 .collect(Collectors.toList());
1271 List<Role> activeRoleList = new ArrayList<>();
1272 for (Role role : roleList) {
1273 if (role.getActiveYn()) {
1274 if (role.getId() != 1) { // prevent portal admin from being added
1275 activeRoleList.add(role);
1276 } else if (extRequestValue) {
1277 activeRoleList.add(role);
1282 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1283 // If localUser does not exists return roles
1284 Set<FnRole> roleSet = null;
1285 FnRole[] roleSetList = null;
1286 if (localUser != null) {
1287 roleSet = localUser.getAppEPRoles(app);
1288 roleSetList = roleSet.toArray(new FnRole[0]);
1290 rolesInAppForUser = fnUserRoleService
1291 .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1292 return rolesInAppForUser;
1295 EcompRole[] appRoles = null;
1296 boolean checkIfUserIsApplicationAccAdmin = false;
1297 List<EcompRole> roles = new ArrayList<>();
1298 if (app.getAuthCentral()) {
1299 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1300 FnApp application = fnAppService.getById(appId);
1301 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1304 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1305 for (FnRole role : applicationRoles) {
1306 List<EpAppFunction> cenRoleFuncList = epAppFunctionService
1307 .getAppRoleFunctionList(role.getId(), app.getId());
1308 for (EpAppFunction roleFunc : cenRoleFuncList) {
1310 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1311 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1312 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1313 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1314 String name = roleFunc.getFunctionName();
1316 FnFunction function = new FnFunction();
1317 function.setAction(action);
1318 function.setType(type);
1319 function.setCode(functionCode);
1320 function.setName(name);
1321 role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1324 roleSetWithFunctioncds.add(role);
1329 for (FnRole role1 : roleSetWithFunctioncds) {
1330 EcompRole ecompRole = new EcompRole();
1331 ecompRole.setId(role1.getId());
1332 ecompRole.setName(role1.getRoleName());
1333 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1334 roles.add(ecompRole);
1337 if (checkIfUserIsApplicationAccAdmin) {
1338 appRoles = roles.toArray(new EcompRole[roles.size()]);
1339 logger.debug(EELFLoggerDelegate.debugLogger,
1340 "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}",
1342 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1343 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1344 List<String> roleAdminAppRolesNames = new ArrayList<>();
1346 "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1347 + " where fu.role_id = ep.role_id"
1348 + " and fu.app_id = ep.app_id"
1349 + " and fu.user_id = :userId"
1350 + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1351 + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1354 + " 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"
1355 + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1356 List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1357 .setParameter("userId", userId)
1359 List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1360 .collect(Collectors.toList());
1362 List<EcompRole> userapproverRolesList = new ArrayList<>();
1363 for (String str : getUserApproverRoles) {
1364 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1365 if (epRole != null) {
1366 userapproverRolesList.add(epRole);
1369 for (EcompRole role : userapproverRolesList) {
1371 List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1372 boolean checkIfFunctionsExits = roleFunList.stream()
1373 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1374 if (checkIfFunctionsExits) {
1375 roleAdminAppRoles.add(role);
1376 List<RoleFunction> filteredList = roleFunList.stream()
1377 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1378 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1379 .collect(Collectors.toList()));
1382 for (String name : roleAdminAppRolesNames) {
1383 roles.stream().filter(x -> name.equals(x.getName())).findAny()
1384 .ifPresent(roleAdminAppRoles::add);
1387 appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1391 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1393 // Test this error case, for generating an internal ONAP Portal
1395 // EcompRole[] appRoles = null;
1396 // If there is an exception in the rest client api, then null will
1398 if (appRoles != null) {
1399 if (!app.getAuthCentral()) {
1400 syncAppRoles(appId, appRoles);
1402 EcompRole[] userAppRoles = null;
1405 if (app.getAuthCentral()) {
1406 List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1407 List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1408 .createNamedQuery("EPUserAppCurrentRoles")
1409 .setParameter("appId", app.getId())
1410 .setParameter("userId", actualUser.get(0).getId())
1412 List<EcompRole> setUserRoles = new ArrayList<>();
1413 for (EPUserAppCurrentRoles role : userAppsRolesList) {
1414 logger.debug(EELFLoggerDelegate.debugLogger,
1415 "In getAppRolesForUser() - userAppsRolesList get userRolename = {}",
1416 role.getRoleName());
1417 EcompRole ecompRole = new EcompRole();
1418 ecompRole.setId(role.getRoleId());
1419 ecompRole.setName(role.getRoleName());
1420 setUserRoles.add(ecompRole);
1423 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1424 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1426 if (!checkIfUserisAccAdmin) {
1427 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1428 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1430 List<String> roleNames = new ArrayList<>();
1431 for (EcompRole role : setUserRoles) {
1432 EcompRole epRole = appRolesList.stream()
1433 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1434 List<RoleFunction> roleFunList = new ArrayList<>();
1436 if (epRole != null) {
1437 if (epRole.getRoleFunctions().size() > 0) {
1438 roleFunList.addAll(epRole.getRoleFunctions());
1440 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1441 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1442 if (checkIfFunctionsExits) {
1443 finalUserAppRolesList.add(role);
1444 List<RoleFunction> filteredList = roleFunList.stream()
1445 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1446 .collect(Collectors.toList());
1447 roleNames = filteredList.stream().map(RoleFunction::getCode)
1448 .collect(Collectors.toList());
1450 roleNames.add(epRole.getName());
1453 for (String name : roleNames) {
1454 EcompRole ecompRole = appRolesList.stream()
1455 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1456 if (ecompRole != null) {
1457 finalUserAppRolesList.add(ecompRole);
1461 for (String name : roleNames) {
1462 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1463 role -> role.getRoleName().equalsIgnoreCase(name));
1464 if (checkIfFunctionsExits) {
1465 appRolesList.stream().filter(x -> name.equals(x.getName()))
1466 .findAny().ifPresent(setUserRoles::add);
1469 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1472 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1473 String.format("/user/%s/roles", userId));
1475 } catch (HTTPException e) {
1476 // Some apps are returning 400 if user is not found.
1477 if (e.getResponseCode() == 400) {
1478 logger.debug(EELFLoggerDelegate.debugLogger,
1479 "getAppRolesForUser caught exception with response code 400; continuing", e);
1481 // Other response code, let it come thru.
1485 if (userAppRoles == null) {
1486 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1487 EcompPortalUtils.setExternalAppResponseCode(200);
1488 String message = String.format(
1489 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1490 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1491 + "Overriding to 200 until framework SDK returns a useful response.",
1492 Long.toString(appId), userId);
1493 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1497 HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1498 ArrayList<EcompRole> activeRoles = new ArrayList<>();
1499 if (userAppRoles != null) {
1500 for (EcompRole userAppRole : userAppRoles) {
1501 if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1502 EcompRole role = new EcompRole();
1503 role.setId(userAppRole.getId());
1504 role.setName(userAppRole.getName());
1505 activeRoles.add(role);
1509 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1511 boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1513 // If the remote application isn't down we MUST sync user
1514 // roles here in case we have this user here!
1515 syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null,
1516 checkIfUserisRoleAdmin,
1518 } catch (Exception e) {
1519 // TODO: we may need to check if user exists, maybe remote
1521 String message = String.format(
1522 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1523 Long.toString(appId));
1524 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1525 userAppRoles = new EcompRole[0];
1527 rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1529 } catch (Exception e) {
1530 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1531 Long.toString(appId));
1532 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1534 return rolesInAppForUser;
1537 private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1538 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1539 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1541 List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1543 List<FnRole> obsoleteRoles = new ArrayList<>();
1544 for (FnRole oldAppRole : currentAppRoles) {
1545 if (oldAppRole.getAppRoleId() != null) {
1547 role = newRolesMap.get(oldAppRole.getAppRoleId());
1549 if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1550 oldAppRole.setRoleName(role.getName());
1552 oldAppRole.setActiveYn(true);
1553 newRolesMap.remove(oldAppRole.getAppRoleId());
1555 obsoleteRoles.add(oldAppRole);
1558 obsoleteRoles.add(oldAppRole);
1561 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1562 if (obsoleteRoles.size() > 0) {
1563 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1564 for (FnRole role : obsoleteRoles) {
1565 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1566 Long roleId = role.getId();
1567 List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1569 logger.debug(EELFLoggerDelegate.debugLogger,
1570 "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1571 for (FnUserRole userRole : userRoles) {
1572 logger.debug(EELFLoggerDelegate.debugLogger,
1573 "syncAppRoles: about to delete userRole: " + userRole.toString());
1574 fnUserRoleService.deleteById(userRole.getId());
1575 logger.debug(EELFLoggerDelegate.debugLogger,
1576 "syncAppRoles: finished deleting userRole: " + userRole.toString());
1578 List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1579 int numMenuRoles = funcMenuRoles.size();
1580 logger.debug(EELFLoggerDelegate.debugLogger,
1581 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1582 for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1583 Long menuId = funcMenuRole.getMenuId().getMenuId();
1584 // If this is the only role for this menu item, then the
1585 // app and roles will be gone,
1586 // so must null out the url too, to be consistent
1587 List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService
1588 .retrieveByMenuId(menuId);
1589 int numMenuRoles2 = funcMenuRoles2.size();
1590 logger.debug(EELFLoggerDelegate.debugLogger,
1591 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1592 fnMenuFunctionalRolesService.delete(funcMenuRole);
1594 if (numMenuRoles2 == 1) {
1595 // If this is the only role for this menu item, then
1596 // the app and roles will be gone,
1597 // so must null out the url too, to be consistent
1598 logger.debug(EELFLoggerDelegate.debugLogger,
1599 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1600 List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1601 if (funcMenuItems.size() > 0) {
1602 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1603 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1604 funcMenuItem.setUrl("");
1608 boolean isPortalRequest = true;
1609 deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1610 logger.debug(EELFLoggerDelegate.debugLogger,
1611 "syncAppRoles: about to delete the role: " + role.toString());
1612 fnRoleService.delete(role);
1613 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1616 for (EcompRole role : newRolesToAdd) {
1617 logger.debug(EELFLoggerDelegate.debugLogger,
1618 "syncAppRoles: about to add missing role: " + role.toString());
1619 FnRole newRole = new FnRole();
1620 // Attention! All roles from remote application supposed to be
1622 newRole.setActiveYn(true);
1623 newRole.setRoleName(role.getName());
1624 newRole.setAppId(appId);
1625 newRole.setAppRoleId(role.getId());
1626 fnRoleService.saveOne(newRole);
1628 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1629 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1630 } catch (Exception e) {
1631 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1632 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1633 throw new Exception(e);
1637 private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1639 Session localSession = entityManager.unwrap(Session.class);
1643 // It should delete only when it portal's roleId
1644 if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1645 // Delete from fn_role_function
1646 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1647 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1648 query = localSession.createSQLQuery(sql);
1649 query.executeUpdate();
1650 // Delete from fn_role_composite
1651 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1652 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1653 query = localSession.createSQLQuery(sql);
1654 query.executeUpdate();
1656 // Delete from ep_app_role_function
1657 sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1658 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1659 query = localSession.createSQLQuery(sql);
1660 query.executeUpdate();
1661 // Delete from ep_role_notification
1662 sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1663 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1664 query = localSession.createSQLQuery(sql);
1665 query.executeUpdate();
1666 // Delete from fn_user_pseudo_role
1667 sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1668 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1669 query = localSession.createSQLQuery(sql);
1670 query.executeUpdate();
1671 // Delete form EP_WIDGET_CATALOG_ROLE
1672 sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1673 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1674 query = localSession.createSQLQuery(sql);
1675 query.executeUpdate();
1676 // Delete form EP_WIDGET_CATALOG_ROLE
1677 sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1678 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1679 query = localSession.createSQLQuery(sql);
1680 query.executeUpdate();
1681 if (!isPortalRequest) {
1682 // Delete form fn_menu_functional_roles
1683 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1684 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1685 query = localSession.createSQLQuery(sql);
1686 query.executeUpdate();
1688 } catch (Exception e) {
1689 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1690 throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1694 private void checkIfRoleInactive(FnRole epRole) throws Exception {
1695 if (!epRole.getActiveYn()) {
1696 throw new Exception(epRole.getRoleName() + " role is unavailable");
1700 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1701 boolean result = false;
1702 // No changes if no new roles list or no userId.
1703 if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1704 && newAppsListWithAdminRoles.getAppsRoles() != null) {
1705 synchronized (syncRests) {
1706 List<FnApp> apps = fnAppService.getAppsFullList();
1707 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1708 for (FnApp app : apps) {
1709 enabledApps.put(app.getId(), app);
1711 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1712 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1713 // user Admin role may be added only for enabled apps
1714 if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1715 newAppsWhereUserIsAdmin.add(adminRole);
1719 boolean createNewUser = false;
1720 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1721 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1722 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1723 if (localUserList.size() > 0) {
1724 FnUser tmpUser = localUserList.get(0);
1725 oldAppsWhereUserIsAdmin = fnUserRoleService
1726 .retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1727 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1730 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1731 // we create new user only if he has Admin Role for any App
1732 createNewUser = true;
1734 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1735 oldAppsWhereUserIsAdmin);
1743 public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1744 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1745 List<FnUserRole> oldAppsWhereUserIsAdmin) {
1746 if (user != null || createNewUser) {
1747 if (createNewUser) {
1748 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1750 user.setActiveYn(true);
1753 for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1754 // user Admin role may be deleted only for enabled
1756 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1757 fnUserRoleService.saveOne(oldUserApp);
1760 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1761 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1762 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1763 FnUserRole newUserApp = new FnUserRole();
1764 newUserApp.setUserId(user);
1765 newUserApp.setFnAppId(app);
1766 newUserApp.setRoleId(role);
1767 fnUserRoleService.saveOne(newUserApp);
1769 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1770 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1777 public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1778 boolean result = false;
1780 // Reset All admin role for centralized applications
1781 List<FnApp> appList = fnAppService.getCentralizedApps();
1782 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1783 for (FnApp app : appList) {
1785 if (EPCommonSystemProperties
1786 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1787 name = user.getOrgUserId() + SystemProperties
1788 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1790 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1791 HttpEntity<String> entity = new HttpEntity<>(headers);
1792 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1794 ResponseEntity<String> getResponse = template
1795 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1796 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1798 if (getResponse.getBody().equals("{}")) {
1799 String addDesc = "{\"name\":\"" + extRole + "\"}";
1800 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1802 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1804 HttpMethod.POST, roleEntity, String.class);
1807 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1809 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1810 + "userRole/" + name + "/" + extRole,
1811 HttpMethod.DELETE, deleteUserRole, String.class);
1812 } catch (Exception e) {
1813 logger.error(EELFLoggerDelegate.errorLogger,
1814 " Role not found for this user may be it gets deleted before", e);
1817 } catch (Exception e) {
1818 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1819 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1820 app.getAuthNamespace(), e.getMessage());
1822 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1823 app.getAuthNamespace(), e);
1827 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1828 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1830 if (app.getAuthCentral()) {
1831 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1832 HttpEntity<String> entity = new HttpEntity<>(headers);
1834 if (EPCommonSystemProperties
1835 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1836 name = user.getOrgUserId() + SystemProperties
1837 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1839 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1840 ResponseEntity<String> getUserRolesResponse = template.exchange(
1841 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1842 + "userRoles/user/" + name,
1843 HttpMethod.GET, entity, String.class);
1844 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1845 if (!getUserRolesResponse.getBody().equals("{}")) {
1846 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1847 JSONArray extRoles = jsonObj.getJSONArray("userRole");
1848 final Map<String, JSONObject> extUserRoles = new HashMap<>();
1849 for (int i = 0; i < extRoles.length(); i++) {
1850 String userRole = extRoles.getJSONObject(i).getString("role");
1851 if (userRole.startsWith(app.getAuthNamespace() + ".")
1852 && !userRole.equals(app.getAuthNamespace() + ".admin")
1853 && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1855 extUserRoles.put(userRole, extRoles.getJSONObject(i));
1858 if (!extUserRoles.containsKey(extRole)) {
1859 // Assign with new apps user admin
1861 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1862 // Assign user role for an application in external access system
1863 ObjectMapper addUserRoleMapper = new ObjectMapper();
1864 String userRole = addUserRoleMapper.writeValueAsString(extUser);
1865 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1867 SystemProperties.getProperty(
1868 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1869 HttpMethod.POST, addUserRole, String.class);
1870 } catch (Exception e) {
1871 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1878 } catch (Exception e) {
1879 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1880 logger.debug(EELFLoggerDelegate.errorLogger,
1881 "Application name space not found in External system for app {} due to bad rquest name space ",
1882 app.getAuthNamespace(), e.getMessage());
1884 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1885 app.getAuthNamespace(), e);
1890 } catch (Exception e) {
1892 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
1897 public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
1898 final String getAllAppsFunctionsOfUser =
1899 "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"
1900 + " where fu.role_id = ep.role_id \n"
1901 + " and fu.app_id = ep.app_id\n"
1902 + " and fu.user_id =:userId\n"
1903 + " and ea.function_cd = ep.function_cd\n"
1904 + " and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1))\n"
1905 + " and fr.role_id = fu.role_id and fr.active_yn='Y' \n"
1907 + " select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f\n"
1908 + " where role_id = 999\n"
1909 + " and app_r_f.function_cd = a_f.function_cd\n"
1912 + " 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"
1913 + " and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'\n"
1915 List getRoleFuncListOfPortal = entityManager.createNativeQuery(getAllAppsFunctionsOfUser)
1916 .setParameter("userId", OrgUserId).getResultList();
1917 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
1918 Set<String> roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
1919 .collect(Collectors.toSet());
1920 if (!roleFunSet.isEmpty()) {
1921 for (String roleFunction : roleFunSet) {
1922 String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
1923 getRoleFuncListOfPortalSet.remove(roleFunction);
1924 getRoleFuncListOfPortalSet.add(roleFun);
1928 Set<String> finalRoleFunctionSet = new HashSet<>();
1929 for (String roleFn : getRoleFuncListOfPortalSet) {
1930 finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
1933 return finalRoleFunctionSet;