X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=ecomp-portal-BE-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fportalapp%2Fportal%2Fservice%2FUserRolesCommonServiceImpl.java;h=bfc232aaeab3fd602b5cbec5ba0be946562b3b61;hb=83de9db899ebf7ec87220670d6f5cf35a10d087b;hp=aaaf91bd43f6b2bc834a1235add9b138210c255e;hpb=9d730f0c98561e566be9adba12c0b044f5924a9f;p=portal.git diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java index aaaf91bd..bfc232aa 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -114,6 +114,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; @@ -176,10 +177,10 @@ public class UserRolesCommonServiceImpl { * * @param userId */ - protected boolean createLocalUserIfNecessary(String userId) { + protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) { if (StringUtils.isEmpty(userId)) { logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); - return false; + return; } Session localSession = null; Transaction transaction = null; @@ -188,12 +189,19 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); @SuppressWarnings("unchecked") List userList = localSession - .createQuery("from :name where orgUserId=:userId") - .setParameter("name",EPUser.class.getName()) + .createQuery("from EPUser where orgUserId=:userId") .setParameter("userId",userId) .list(); if (userList.size() == 0) { - EPUser client = searchService.searchUserByUserId(userId); + EPUser client = null; + if (!isSystemUser) { + client = searchService.searchUserByUserId(userId); + } else { + client = new EPUser(); + client.setOrgUserId(userId); + client.setSystemUser(true); + client.setFirstName(userId.substring(0,userId.indexOf("@"))); + } if (client == null) { String msg = "createLocalUserIfNecessary: cannot create user " + userId + ", because not found in phonebook"; @@ -205,11 +213,9 @@ public class UserRolesCommonServiceImpl { } } transaction.commit(); - return true; } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e); - return false; } finally { EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser"); } @@ -262,27 +268,39 @@ public class UserRolesCommonServiceImpl { * set to false if request is from users page otherwise true * @throws Exception */ + @SuppressWarnings("unchecked") protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId, - EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception { + EcompRole[] userAppRoles, Boolean extRequestValue, String reqType,boolean checkIfUserisRoleAdmin,EcompRole[] appRoles) throws Exception { Session localSession = null; Transaction transaction = null; String roleActive = null; final Map userAppParams = new HashMap<>(); final Map appParams = new HashMap<>(); HashMap newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); - + List roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + + EPRole adminRole = new EPRole(); + if(roleInfo.size()>0) + { + adminRole = roleInfo.get(0); + logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName()); + } try { localSession = sessionFactory.openSession(); transaction = localSession.beginTransaction(); @SuppressWarnings("unchecked") List userList = localSession - .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + .createQuery("from EPUser where orgUserId=:userId") + .setParameter("userId",userId) + .list(); if (userList.size() > 0) { EPUser client = userList.get(0); roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; @SuppressWarnings("unchecked") - List userRoles = localSession.createQuery("from " + EPUserApp.class.getName() - + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list(); + List userRoles = localSession.createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive) + .setParameter("appId",appId) + .setParameter("userId",client.getId()) + .list(); if ("DELETE".equals(reqType)) { for (EPUserApp userAppRoleList : userRoles) { @@ -290,13 +308,32 @@ public class UserRolesCommonServiceImpl { userAppParams.put("appId", String.valueOf(appId)); appParams.put("appRoleName", userAppRoleList.getRole().getName()); @SuppressWarnings("unchecked") - List rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null); + List rolesList = (!userAppRoleList.getRole().getName().equals(adminRole.getName())) ? (List) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null); if(rolesList.size() > 0 || !rolesList.isEmpty()){ checkIfRoleInactive(rolesList.get(0)); } } } + + if (appRoles != null) { + List appRolesList = Arrays.stream(appRoles).collect(Collectors.toList()); + List finalUserRolesList = new ArrayList<>(); + if (checkIfUserisRoleAdmin) { + for (EcompRole role : appRolesList) { + for (EPUserApp userAppRoleList : userRoles) { + if (userAppRoleList.getRole().getName().equals(role.getName())) + + { + finalUserRolesList.add(userAppRoleList); + } + } + } + userRoles = new ArrayList<>(); + userRoles.addAll(finalUserRolesList); + } + } + for (EPUserApp userRole : userRoles) { if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){ syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap); @@ -308,6 +345,8 @@ public class UserRolesCommonServiceImpl { syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap); } } + + Collection newRolesToAdd = newUserAppRolesMap.values(); if (newRolesToAdd.size() > 0) { EPApp app = (EPApp) localSession.get(EPApp.class, appId); @@ -328,7 +367,9 @@ public class UserRolesCommonServiceImpl { } else { // remote app @SuppressWarnings("unchecked") List roles = localSession - .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + .createQuery("from EPRole where appId=:appId") + .setParameter("appId",appId) + .list(); for (EPRole role : roles) { if (!extRequestValue && app.getCentralAuth()) { rolesMap.put(role.getId(), role); @@ -341,7 +382,7 @@ public class UserRolesCommonServiceImpl { EPRole role = null; for (EcompRole userRole : newRolesToAdd) { EPUserApp userApp = new EPUserApp(); - if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) { + if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(adminRole.getName())) { role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); userApp.setRole(role); } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){ @@ -488,9 +529,12 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); // Attention! All roles from remote application supposed to be // active! + @SuppressWarnings("unchecked") - List currentAppRoles = localSession - .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + List currentAppRoles = localSession.createQuery("from EPRole where appId = :appId") + .setParameter("appId",appId) + .list(); + List obsoleteRoles = new ArrayList(); for (int i = 0; i < currentAppRoles.size(); i++) { EPRole oldAppRole = currentAppRoles.get(i); @@ -528,7 +572,9 @@ public class UserRolesCommonServiceImpl { // Delete from fn_user_role @SuppressWarnings("unchecked") List userRoles = localSession.createQuery( - "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + "from EPUserApp where app.id=:appId and role_id=:roleId") + .setParameter("appId",appId) + .setParameter("roleId",roleId) .list(); logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size()); @@ -543,7 +589,8 @@ public class UserRolesCommonServiceImpl { // Delete from fn_menu_functional_roles @SuppressWarnings("unchecked") List funcMenuRoles = localSession - .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .createQuery("from FunctionalMenuRole where roleId=:roleId") + .setParameter("roleId",roleId) .list(); int numMenuRoles = funcMenuRoles.size(); logger.debug(EELFLoggerDelegate.debugLogger, @@ -555,7 +602,8 @@ public class UserRolesCommonServiceImpl { // so must null out the url too, to be consistent @SuppressWarnings("unchecked") List funcMenuRoles2 = localSession - .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .createQuery("from FunctionalMenuRole where menuId=:menuId") + .setParameter("menuId",menuId) .list(); int numMenuRoles2 = funcMenuRoles2.size(); logger.debug(EELFLoggerDelegate.debugLogger, @@ -569,8 +617,8 @@ public class UserRolesCommonServiceImpl { "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); @SuppressWarnings("unchecked") List funcMenuItems = localSession - .createQuery( - "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId) + .createQuery("from FunctionalMenuItem where menuId=:menuId") + .setParameter("menuId",menuId) .list(); if (funcMenuItems.size() > 0) { logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); @@ -630,6 +678,7 @@ public class UserRolesCommonServiceImpl { result = new RolesInAppForUser(); result.appId = appId; result.orgUserId = userId; + for (EcompRole role : userRolesInRemoteApp) { RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); roleInAppForUser.roleId = role.getId(); @@ -667,7 +716,7 @@ public class UserRolesCommonServiceImpl { * @throws HTTPException */ protected Set postUsersRolesToRemoteApp(List roleInAppForUserList, ObjectMapper mapper, - ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser) throws JsonProcessingException, HTTPException { Set updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); Set updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); @@ -744,13 +793,13 @@ public class UserRolesCommonServiceImpl { * set to false if requests from Users page otherwise true * @return true on success, false otherwise */ - protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception { + protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser,Set rolesDeletedByApprover ,boolean isLoggedInUserRoleAdminOfApp ) throws Exception { boolean result = false; String userId = rolesInAppForUser.orgUserId; Long appId = rolesInAppForUser.appId; synchronized (syncRests) { if (rolesInAppForUser != null) { - createLocalUserIfNecessary(userId); + createLocalUserIfNecessary(userId, isSystemUser); } if (rolesInAppForUser != null) { @@ -763,7 +812,16 @@ public class UserRolesCommonServiceImpl { userAppRoles[i] = role; } try { - syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType); + EcompRole[] applicationRoles = null; + + if(isLoggedInUserRoleAdminOfApp){ + List roles = Arrays.stream(userAppRoles).collect(Collectors.toList()); + List roles1 = rolesDeletedByApprover.stream().collect(Collectors.toList()); + roles.addAll(roles1); + applicationRoles = roles.stream().toArray(n -> new EcompRole[n]); + } + + syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType,isLoggedInUserRoleAdminOfApp,applicationRoles); result = true; } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, @@ -857,22 +915,42 @@ public class UserRolesCommonServiceImpl { return addRemoteUser; } + @SuppressWarnings("unchecked") protected void pushUserOnRemoteApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService, SearchService searchService, ObjectMapper mapper, boolean postOpenSource, List roleInAppForUserList,boolean appRoleIdUsed) throws Exception { - EPUser client = searchService.searchUserByUserId(userId); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + EPUser client = null; + client = searchService.searchUserByUserId(userId); - if (client == null) { - String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook."; - logger.error(EELFLoggerDelegate.errorLogger, msg); - throw new Exception(msg); - } + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + if (client == null) { + String msg = "cannot create user " + userId + ", because he/she cannot be found in directory."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + // throw new Exception(msg); + final Map loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", userId); + List userList = new ArrayList<>(); + userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null); + if (userList.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + userList.get(0).getOrgUserId() + " User was found in Portal"); + client = userList.get(0); + SortedSet userApps = new TreeSet<>(); + client.setEPUserApps(userApps); + client.setSystemUser(false); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal"); + throw new Exception(msg); + } + } + client.setLoginId(userId); - client.setActive(true); + client.setActive(true); + client.setOrgUserId(userId); + + roleInAppForUserList.removeIf(role -> role.isApplied.equals(false)); SortedSet roles = new TreeSet<>(); @@ -973,20 +1051,63 @@ public class UserRolesCommonServiceImpl { boolean epRequestValue = false; String userId = ""; String reqMessage = ""; - if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { - userId = newAppRolesForUser.orgUserId.trim(); + if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) { + userId = newAppRolesForUser.getOrgUserId().trim(); } - Long appId = newAppRolesForUser.appId; - List roleInAppForUserList = newAppRolesForUser.appRoles; - if (userId.length() > 0) { + Long appId = newAppRolesForUser.getAppId(); + List roleInAppForUserList = newAppRolesForUser.getAppRoles(); + + + + if (userId.length() > 0 ) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { EPApp app = appsService.getApp(appId); + + boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user, + app); + Set rolesGotDeletedFromApprover = new TreeSet(); + + boolean checkIfUserisOnlyRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin; + if (checkIfUserisOnlyRoleAdmin) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (!roleInAppForUser.isApplied) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.roleId); + ecompRole.setName(roleInAppForUser.roleName); + rolesGotDeletedFromApprover.add(ecompRole); + } + } + } + applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - // if centralized app + boolean systemUser = newAppRolesForUser.isSystemUser(); + + if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) { + + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + List roleAppUserList = rolesInAppForUser.roles; + Set rolesGotDeletedByApprover = new TreeSet<>(); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Apply changes in external Access system + + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, + epRequestValue, systemUser,rolesGotDeletedByApprover,false); + } + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", + systemUser,rolesGotDeletedByApprover,false); + + }else if (!app.getCentralAuth() && systemUser) + { + throw new Exception("For non-centralized application we cannot add systemUser"); + } + else{ // if centralized app if (app.getCentralAuth()) { if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, @@ -999,11 +1120,12 @@ public class UserRolesCommonServiceImpl { userRolesInLocalApp); List roleAppUserList = rolesInAppForUser.roles; if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Apply changes in external Access system updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, - epRequestValue); + epRequestValue,false,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin); } - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser,rolesGotDeletedFromApprover,checkIfUserisOnlyRoleAdmin); } // In case if portal is not centralized then follow existing approach else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ @@ -1011,7 +1133,8 @@ public class UserRolesCommonServiceImpl { applicationsRestClientService, appId, userId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + Set rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false,rolesGotDeletedByApprover,false); } else{// remote app EPUser remoteAppUser = null; if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ @@ -1022,10 +1145,11 @@ public class UserRolesCommonServiceImpl { remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, appId, userId); + applicationsRestClientService, appId, userId,systemUser); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInRemoteApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + Set rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false,rolesGotDeletedByApprover,false); // If no roles remain, request app to set user inactive. if (userRolesInRemoteApp.size() == 0) { @@ -1037,6 +1161,7 @@ public class UserRolesCommonServiceImpl { } } } + } } catch (Exception e) { /*String message = String.format( "Failed to create user or update user roles for User %s, AppId %s", @@ -1067,7 +1192,7 @@ public class UserRolesCommonServiceImpl { * @param roleInAppUser Contains list of active roles */ @SuppressWarnings("unchecked") - private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List roleInAppUser, boolean isPortalRequest) throws Exception + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List roleInAppUser, boolean isPortalRequest,boolean isSystemUser,Set deletedRolesByApprover,boolean isLoggedInUserRoleAdminofApp) throws Exception { try { // check if user exists @@ -1075,18 +1200,22 @@ public class UserRolesCommonServiceImpl { userParams.put("orgUserIdValue", orgUserId); List userInfo = checkIfUserExists(userParams); if (userInfo.isEmpty()) { - createLocalUserIfNecessary(orgUserId); + createLocalUserIfNecessary(orgUserId, isSystemUser); } String name = ""; if (EPCommonSystemProperties - .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) { name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } else { + name = orgUserId; } ObjectMapper mapper = new ObjectMapper(); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); HttpEntity getUserRolesEntity = new HttpEntity<>(headers); ResponseEntity getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + + List userRoleDetailList = new ArrayList<>(); String res = getResponse.getBody(); JSONObject jsonObj = null; @@ -1118,6 +1247,7 @@ public class UserRolesCommonServiceImpl { List userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app); + List userAppList = new ArrayList<>(); // If request coming from portal not from external role approval system then we have to check if user already // have account admin or system admin as GUI will not send these roles if (!isPortalRequest) { @@ -1127,7 +1257,7 @@ public class UserRolesCommonServiceImpl { final Map params = new HashMap<>(); params.put("appId", app.getId()); params.put("userId", user.getId()); - List userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", + userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", params, null); if (!roleInAppUser.isEmpty()) { for (EcompUserAppRoles userApp : userAppList) { @@ -1144,7 +1274,7 @@ public class UserRolesCommonServiceImpl { } List roleInAppUserNonDupls = roleInAppUser.stream().distinct() .collect(Collectors.toList()); - final Map currentUserRolesToUpdate = new HashMap<>(); + Map currentUserRolesToUpdate = new HashMap<>(); for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) { currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew); } @@ -1152,6 +1282,35 @@ public class UserRolesCommonServiceImpl { for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) { currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole); } + + if (isLoggedInUserRoleAdminofApp) { + if (deletedRolesByApprover.size() > 0) { + List newUpdatedRoles = new ArrayList<>(); + Set roles = new HashSet<>(); + for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { + for (EcompRole role : deletedRolesByApprover) { + if ((userRole.getName().substring(app.getNameSpace().length() + 1)).equals(role.getName())) { + roles.add(role); + newUpdatedRoles.add(userRole); + } + } + } + if (newUpdatedRoles.size() > 0) { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + userRoleListMatchingInExtAuthAndLocal.addAll(newUpdatedRoles); + } else { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + currentUserRolesToUpdate = new HashMap<>(); + + } + + } else { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + currentUserRolesToUpdate = new HashMap<>(); + + } + } + // Check if user roles does not exists in local but still there in External Central Auth System delete them all for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { if (!(currentUserRolesToUpdate @@ -1173,7 +1332,7 @@ public class UserRolesCommonServiceImpl { for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { if (!(currentUserRolesInExternalSystem .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) { - ExternalAccessUser extUser = new ExternalAccessUser(name, + ExternalAccessUser extUser = new ExternalAccessUser(name, app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); String formattedUserRole = mapper.writeValueAsString(extUser); HttpEntity entity = new HttpEntity<>(formattedUserRole, headers); @@ -1193,7 +1352,23 @@ public class UserRolesCommonServiceImpl { } } } - } catch (Exception e) { + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", + app.getId(), e); + if (e.getStatusCode() == HttpStatus.FORBIDDEN) { + logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId); + throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser"); + } + if (e.getStatusCode() == HttpStatus.NOT_FOUND) { + logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role"); + throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role"); + } + EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); + throw e; + } + + catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e); EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); throw e; @@ -1487,13 +1662,15 @@ public class UserRolesCommonServiceImpl { RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInLocalApp); List roleAppUserList = rolesInAppForUser.roles; + Set rolesGotDeletedByApprover = new TreeSet<>(); + if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { // Apply changes in external Access system - updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest); + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false,rolesGotDeletedByApprover,false); } logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false); } // If local application is not centralized else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ @@ -1501,7 +1678,9 @@ public class UserRolesCommonServiceImpl { applicationsRestClientService, app.getId(), orgUserId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + Set rolesGotDeletedByApprover = new TreeSet<>(); + + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false,rolesGotDeletedByApprover,false); } else {// remote app // If adding just account admin role don't do remote application user call if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) { @@ -1514,15 +1693,17 @@ public class UserRolesCommonServiceImpl { } Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, app.getId(), orgUserId); + applicationsRestClientService, app.getId(), orgUserId,false); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + Set rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, - reqType); + reqType,false,rolesGotDeletedByApprover,false); // If no roles remain, request app to set user inactive. /* * if (userRolesInRemoteApp.size() == 0) { @@ -1544,8 +1725,10 @@ public class UserRolesCommonServiceImpl { userRolesInRemoteApp); logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + Set rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, - reqType); + reqType,false,rolesGotDeletedByApprover,false); } if(!result){ reqMessage = "Failed to save the user app role(s)"; @@ -1617,7 +1800,15 @@ public class UserRolesCommonServiceImpl { roleInAppForUserList); throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application"); } else { - ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId(); + + List roleInfo = externalAccessRolesService.getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + EPRole adminRole = new EPRole(); + if(roleInfo.size()>0) + { + adminRole = roleInfo.get(0); + logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getName()); + } + ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getName())) ? existingAppRole.getId() : existingAppRole.getAppRoleId(); ecompRole.roleName = roleInAppForUser.getRoleName(); ecompRole.isApplied = true; existingUserRoles.add(ecompRole); @@ -1729,6 +1920,7 @@ public class UserRolesCommonServiceImpl { } EcompRole[] appRoles = null; + boolean checkIfUserisApplicationAccAdmin = false; List roles = new ArrayList<>(); if (app.getCentralAuth()) { final Map appParams = new HashMap<>(); @@ -1737,7 +1929,7 @@ public class UserRolesCommonServiceImpl { appParams, null); EPApp application = appService.getApp(appId); - boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user, + checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user, application); List rolesetwithfunctioncds = new ArrayList(); @@ -1871,19 +2063,23 @@ public class UserRolesCommonServiceImpl { EcompRole epRole = appRolesList.stream() .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null); List roleFunList = new ArrayList<>(); - if(epRole.getRoleFunctions().size()>0) - roleFunList.addAll(epRole.getRoleFunctions()); - boolean checkIfFunctionsExits = roleFunList.stream().anyMatch( - roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver")); - if (checkIfFunctionsExits) { - finalUserAppRolesList.add(role); - List filteredList = roleFunList.stream() - .filter(x -> "Approver".equalsIgnoreCase(x.getType())) - .collect(Collectors.toList()); - roleNames = filteredList.stream().map(RoleFunction::getCode) - .collect(Collectors.toList()); + + if (epRole != null) { + if (epRole.getRoleFunctions().size() > 0) + roleFunList.addAll(epRole.getRoleFunctions()); + boolean checkIfFunctionsExits = roleFunList.stream().anyMatch( + roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver")); + if (checkIfFunctionsExits) { + finalUserAppRolesList.add(role); + List filteredList = roleFunList.stream() + .filter(x -> "Approver".equalsIgnoreCase(x.getType())) + .collect(Collectors.toList()); + roleNames = filteredList.stream().map(RoleFunction::getCode) + .collect(Collectors.toList()); + }else{ + roleNames.add(epRole.getName()); + } } - for (String name : roleNames) { EcompRole ecompRole = appRolesList.stream() .filter(x -> name.equals(x.getName())).findAny().orElse(null); @@ -1948,9 +2144,12 @@ public class UserRolesCommonServiceImpl { } EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]); + + boolean checkIfUserisRoleAdmin = adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin; + // If the remote application isn't down we MUST sync user // roles here in case we have this user here! - syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null); + syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null,checkIfUserisRoleAdmin,appRoles); } catch (Exception e) { // TODO: we may need to check if user exists, maybe remote // app is down. @@ -1989,17 +2188,18 @@ public class UserRolesCommonServiceImpl { List appRole= null; try { logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined"); - boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId()); + boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, + userAppRolesData.getAppId(), user.getId()); logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result); - params.put("appId", userAppRolesData.appId); + params.put("appId", userAppRolesData.getAppId()); EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest(); epAppRolesRequestData.setCreatedDate(new Date()); epAppRolesRequestData.setUpdatedDate(new Date()); epAppRolesRequestData.setUserId(user.getId()); - epAppRolesRequestData.setAppId(userAppRolesData.appId); + epAppRolesRequestData.setAppId(userAppRolesData.getAppId()); epAppRolesRequestData.setRequestStatus("P"); - List appRoleIdList = userAppRolesData.appRoles; + List appRoleIdList = userAppRolesData.getAppRoles(); Set appRoleDetails = new LinkedHashSet(); dataAccessService.saveDomainObject(epAppRolesRequestData, null); for (RoleInAppForUser userAppRoles : appRoleIdList) {