X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=ecomp-portal-BE-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fopenecomp%2Fportalapp%2Fportal%2Fservice%2FUserRolesCommonServiceImpl.java;h=d7aac633b2fe8b4f68bb5d9303f040097dd78dcc;hb=fc325ed92de8f32b1b59db484ddd3f30fc21f30a;hp=588092100674620169a1f7fd806ed52e72924587;hpb=a0b9152f19c4f8dbd925635129d75af9785a1d4a;p=portal.git diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java index 58809210..d7aac633 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -31,16 +31,18 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; +import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.cxf.transport.http.HTTPException; -import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; +import org.json.JSONArray; +import org.json.JSONObject; import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser; import org.openecomp.portalapp.portal.domain.EPApp; @@ -48,15 +50,20 @@ import org.openecomp.portalapp.portal.domain.EPRole; import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.domain.EPUserApp; import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles; +import org.openecomp.portalapp.portal.domain.EPUserAppRoles; import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest; import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail; -import org.openecomp.portalapp.portal.domain.EpUserAppRoles; import org.openecomp.portalapp.portal.domain.ExternalSystemAccess; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles; +import org.openecomp.portalapp.portal.transport.EcompUserAppRoles; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; +import org.openecomp.portalapp.portal.transport.ExternalAccessUserRoleDetail; import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.openecomp.portalapp.portal.transport.ExternalRoleDescription; import org.openecomp.portalapp.portal.transport.FieldsValidator; import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; @@ -74,6 +81,11 @@ import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.service.RoleService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -87,7 +99,7 @@ public class UserRolesCommonServiceImpl { private static final Object syncRests = new Object(); @Autowired - private DataAccessService dataAccessService; + private DataAccessService dataAccessService; @Autowired private SessionFactory sessionFactory; @Autowired @@ -99,7 +111,12 @@ public class UserRolesCommonServiceImpl { @Autowired private EPRoleService epRoleService; @Autowired - private RoleService roleService; + private RoleService roleService; + + @Autowired + private ExternalAccessRolesService externalAccessRolesService; + + RestTemplate template = new RestTemplate(); /** * @@ -255,12 +272,10 @@ public class UserRolesCommonServiceImpl { EPApp app = (EPApp) localSession.get(EPApp.class, appId); HashMap rolesMap = new HashMap(); - if (appId == PortalConstants.PORTAL_APP_ID) { // local app - String appIdValue = null; + if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app + String appIdValue = ""; if(!extRequestValue){ - appIdValue = "and id != " + PortalConstants.PORTAL_APP_ID; - }else{ - appIdValue = ""; + appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID; } @SuppressWarnings("unchecked") List roles = localSession @@ -274,19 +289,27 @@ public class UserRolesCommonServiceImpl { List roles = localSession .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); for (EPRole role : roles) { - rolesMap.put(role.getAppRoleId(), role); + if (!extRequestValue && app.getCentralAuth()) { + rolesMap.put(role.getId(), role); + } else { + rolesMap.put(role.getAppRoleId(), role); + } } } + EPRole role = null; for (EcompRole userRole : newRolesToAdd) { EPUserApp userApp = new EPUserApp(); if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) { 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){ + } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){ continue; - } else { - userApp.setRole(rolesMap.get(userRole.getId())); + }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){ + continue; + } + else { + userApp.setRole(rolesMap.get(userRole.getId())); } userApp.setUserId(client.getId()); @@ -305,10 +328,10 @@ public class UserRolesCommonServiceImpl { * code expects the app_id to be null as there is no * concept of App_id in SDK */ + localSession.flush(); SQLQuery sqlQuery = localSession .createSQLQuery("update fn_role set app_id = null where app_id = 1 "); sqlQuery.executeUpdate(); - } } @@ -412,7 +435,6 @@ public class UserRolesCommonServiceImpl { protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception { logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); HashMap newRolesMap = hashMapFromEcompRoles(appRoles); - boolean result = false; Session localSession = null; Transaction transaction = null; @@ -444,21 +466,10 @@ public class UserRolesCommonServiceImpl { } } Collection newRolesToAdd = newRolesMap.values(); - for (EcompRole role : newRolesToAdd) { - logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString()); - EPRole newRole = new EPRole(); - // Attention! All roles from remote application supposed to be - // active! - newRole.setActive(true); - newRole.setName(role.getName()); - newRole.setAppId(appId); - newRole.setAppRoleId(role.getId()); - localSession.save(newRole); - } if (obsoleteRoles.size() > 0) { - logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete"); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete"); for (EPRole role : obsoleteRoles) { - logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString()); Long roleId = role.getId(); // delete obsolete roles here // Must delete all records with foreign key constraints on @@ -474,13 +485,13 @@ public class UserRolesCommonServiceImpl { "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) .list(); - logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size()); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size()); for (EPUserApp userRole : userRoles) { logger.debug(EELFLoggerDelegate.debugLogger, - "about to delete userRole: " + userRole.toString()); + "syncAppRoles: about to delete userRole: " + userRole.toString()); localSession.delete(userRole); logger.debug(EELFLoggerDelegate.debugLogger, - "finished deleting userRole: " + userRole.toString()); + "syncAppRoles: finished deleting userRole: " + userRole.toString()); } // Delete from fn_menu_functional_roles @@ -490,7 +501,7 @@ public class UserRolesCommonServiceImpl { .list(); int numMenuRoles = funcMenuRoles.size(); logger.debug(EELFLoggerDelegate.debugLogger, - "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); for (FunctionalMenuRole funcMenuRole : funcMenuRoles) { Long menuId = funcMenuRole.menuId; // If this is the only role for this menu item, then the @@ -502,14 +513,14 @@ public class UserRolesCommonServiceImpl { .list(); int numMenuRoles2 = funcMenuRoles2.size(); logger.debug(EELFLoggerDelegate.debugLogger, - "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); localSession.delete(funcMenuRole); if (numMenuRoles2 == 1) { // If this is the only role for this menu item, then // the app and roles will be gone, // so must null out the url too, to be consistent logger.debug(EELFLoggerDelegate.debugLogger, - "There is exactly 1 menu item for this role, so emptying the url"); + "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); @SuppressWarnings("unchecked") List funcMenuItems = localSession .createQuery( @@ -523,54 +534,40 @@ public class UserRolesCommonServiceImpl { } } } - - // Delete from fn_role_function - String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - Query query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - // Delete from ep_role_notification - sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - // Delete from fn_role_composite - sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" - + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - // Delete from fn_user_pseudo_role - sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); + externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString()); localSession.delete(role); - logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role"); } } - logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString()); + EPRole newRole = new EPRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActive(true); + newRole.setName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + localSession.save(newRole); + } + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction"); transaction.commit(); - logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); - result = true; + logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction"); } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); EcompPortalUtils.rollbackTransaction(transaction, - "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + "syncAppRoles: Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + throw new Exception(e); } finally { localSession.close(); - if (!result) { - throw new Exception( - "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'."); - } } } + + + + /** * Called when updating the list of roles for the user * @@ -691,8 +688,8 @@ public class UserRolesCommonServiceImpl { } if (rolesInAppForUser != null) { - EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()]; - for (int i = 0; i < rolesInAppForUser.roles.size(); i++) { + EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()]; + for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) { RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i); EcompRole role = new EcompRole(); role.setId(roleInAppForUser.roleId); @@ -759,6 +756,69 @@ public class UserRolesCommonServiceImpl { return rolesList; } + /** + * It adds new user for remote application + * + * @param roleInAppForUserList + * @param remoteAppUser + * @param userId + * @param app + * @param mapper + * @param searchService + * @param applicationsRestClientService + * @return + * @throws Exception + */ + private EPUser addRemoteUser(List roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{ + EPUser addRemoteUser = null; + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + + createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app)); + // If we succeed, we know that the new user was + // persisted on remote app. + addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); + if (addRemoteUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId()); + // return null; + } + } + return addRemoteUser; + } + + /** + * It checks whether the remote user exists or not + * if exits returns user object else null + * + * @param userId + * @param app + * @param applicationsRestClientService + * @return + * @throws HTTPException + */ + private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{ + EPUser checkRemoteUser = null; + try { + checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", + e); + } else if(e.getResponseCode() == 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing", + e); + } else { + // Other response code, let it come thru. + throw e; + } + } + return checkRemoteUser; + } + + /* * (non-Javadoc) * @@ -783,58 +843,59 @@ public class UserRolesCommonServiceImpl { EPApp app = appsService.getApp(appId); applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - // if local app - if (appId == PortalConstants.PORTAL_APP_ID) { - // EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); + // if centralized app + if (app.getCentralAuth()) { + // We should add If user does not exist in remote application + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + EPUser remoteAppUser = null; + remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService); + + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, + applicationsRestClientService); + } + } + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, applicationsRestClientService, appId, userId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); - - } else {// remote app + List roleAppUserList = rolesInAppForUser.roles; + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, epRequestValue); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + } + // In case if portal is not centralized then follow existing approach + else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + } else{// remote app EPUser remoteAppUser = null; - try { - remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService); - } catch (HTTPException e) { - // Some apps are returning 400 if user is not found. - if (e.getResponseCode() == 400) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", - e); - } else { - // Other response code, let it come thru. - throw e; - } - } - if (remoteAppUser == null) { - if (remoteUserShouldBeCreated(roleInAppForUserList)) { - - createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app)); - // If we succeed, we know that the new user was - // persisted on remote app. - remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService); - if (remoteAppUser == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Failed to persist new user: " + userId + " in remote app. appId = " + appId); - // return null; - } + if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + + remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService); + + if (remoteAppUser == null) { + remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } - } - if (remoteAppUser != null) { - Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, appId, userId); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, - userRolesInRemoteApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + if (remoteAppUser != null) { + Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInRemoteApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); - // If no roles remain, request app to set user inactive. - if (userRolesInRemoteApp.size() == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app, - userId); - remoteAppUser.setActive(false); - postUserToRemoteApp(userId, user, app, applicationsRestClientService); + // If no roles remain, request app to set user inactive. + if (userRolesInRemoteApp.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app, + userId); + remoteAppUser.setActive(false); + postUserToRemoteApp(userId, user, app, applicationsRestClientService); + } } } } @@ -849,7 +910,155 @@ public class UserRolesCommonServiceImpl { } return result; } - + /** + * It adds user roles in External system and also make data consistent in both local and in External System + * + * @param app details + * @param orgUserId + * @param roleInAppUser Contains list of active roles + */ + @SuppressWarnings("unchecked") + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List roleInAppUser, boolean isPortalRequest) + { + try { + // check if user exists + final Map userParams = new HashMap<>(); + userParams.put("orgUserIdValue", orgUserId); + List userInfo = checkIfUserExists(userParams); + if (userInfo.isEmpty()) { + createLocalUserIfNecessary(orgUserId); + } + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = orgUserId + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity getUserRolesEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if (getResponse.getStatusCode().value() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}", + getResponse.getBody()); + + } + List userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj = null; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + ExternalAccessUserRoleDetail userRoleDetail = null; + if (extRoles != null) { + for (int i = 0; i < extRoles.length(); i++) { + if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".") + && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin") + && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) { + ObjectMapper descMapper = new ObjectMapper(); + if (extRoles.getJSONObject(i).has("description")) { + ExternalRoleDescription desc = descMapper.readValue( + extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class); + userRoleDetail = new ExternalAccessUserRoleDetail( + extRoles.getJSONObject(i).getString("name"), desc); + userRoleDetailList.add(userRoleDetail); + } else { + userRoleDetail = new ExternalAccessUserRoleDetail( + extRoles.getJSONObject(i).getString("name"), null); + userRoleDetailList.add(userRoleDetail); + } + + } + } + } + // 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) { + final Map loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", orgUserId); + EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0); + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + params.put("userId", user.getId()); + List userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", + params, null); + if (!roleInAppUser.isEmpty()) { + for (EcompUserAppRoles userApp : userAppList) { + if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID) + || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { + RoleInAppForUser addSpecialRole = new RoleInAppForUser(); + addSpecialRole.setIsApplied(true); + addSpecialRole.setRoleId(userApp.getRoleId()); + addSpecialRole.setRoleName(userApp.getRoleName()); + roleInAppUser.add(addSpecialRole); + } + } + } + } + List roleInAppUserNonDupls = roleInAppUser.stream().distinct() + .collect(Collectors.toList()); + final Map currentUserRolesToUpdate = new HashMap<>(); + for (RoleInAppForUser roleInAppUserNew : roleInAppUser) { + currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName(), roleInAppUserNew); + } + final Map currentUserRolesInExternalSystem = new HashMap<>(); + for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleDetailList) { + currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole); + } + // Check if roles does not exists in local but still there in External Central Auth System delete them all + for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) { + if (!(currentUserRolesToUpdate + .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1).replaceAll("_", " ")) + || currentUserRolesToUpdate + .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) { + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}", + userRole); + ResponseEntity deleteResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + userRole.getName(), + HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}", + userRole, deleteResponse.getBody()); + } + } + // Check if user roles does not exists in External Central Auth System add them all + for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { + if (!(currentUserRolesInExternalSystem + .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")))) { + ExternalAccessUser extUser = new ExternalAccessUser(name, + app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(" ", "_")); + String formattedUserRole = mapper.writeValueAsString(extUser); + HttpEntity entity = new HttpEntity<>(formattedUserRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system and adding user role", + addUserRole.getRoleName()); + ResponseEntity addResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}", + getResponse.getBody(), addUserRole.getRoleName()); + if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Finished POST operation in external system but unable to save user role", getResponse.getBody(), + addUserRole.getRoleName()); + throw new Exception(addResponse.getBody()); + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e); + } + + } + /** * * @param userId @@ -1066,60 +1275,89 @@ public class UserRolesCommonServiceImpl { .executeNamedQuery("userAppRolesRequestList", params, null); epRequestIdSize = epRequestId.size(); } - if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + + //If Non-Centralized app make sure you sync app roles before assigning to user + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()){ EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles"); syncAppRoles(sessionFactory, app.getId(), appRoles); } - List roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(), app.getId(), app.getMlAppName()); - // if local app - if (app.getId() == PortalConstants.PORTAL_APP_ID) { - // EPUser localUser = getUserFromApp(orgUserId, app, applicationsRestClientService); + List userRoleList = null; + if(!userInfo.isEmpty()){ + final Map appParams = new HashMap<>(); + appParams.put("userId", userId.getId()); + appParams.put("appId", app.getId()); + userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null); + } + // Check if list contains just account admin role + boolean checkIfAdminRoleExists = false; + if (reqType.equals("DELETE")) { + checkIfAdminRoleExists = userRoleList.stream() + .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); + } else { + checkIfAdminRoleExists = roleInAppForUserList.stream() + .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); + } + // if Centralized app + if (app.getCentralAuth()) { + // We should add If user does not exist in remote application + try { + // If adding just account admin role dont make remote application user call + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists + && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) { + EPUser remoteAppUser = null; + remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, + applicationsRestClientService); + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, + applicationsRestClientService); + reqMessage = "Saved Successfully"; + } + } + } catch (Exception e) { + reqMessage = e.getMessage(); + logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e); + throw new Exception(reqMessage); + } Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, applicationsRestClientService, app.getId(), orgUserId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInLocalApp); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", - logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + List roleAppUserList = rolesInAppForUser.roles; + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest); + logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, + newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + } + // If local application is not centralized + else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, app.getId(), orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), + userRolesInLocalApp); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); } else {// remote app + // If adding just account admin role don't do remote application user call + if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){ EPUser remoteAppUser = null; - try { - remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService); - } catch (HTTPException e) { - // Some apps are returning 400 if user is not found. - if (e.getResponseCode() == 400) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", - e); - } else { - // Other response code, let it come thru. - throw e; - } - } + remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService); if (remoteAppUser == null) { - createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper, - isAppUpgradeVersion(app)); - // If we succeed, we know that the new user was - // persisted on remote app. - remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService); - if (remoteAppUser == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId - + " in remote app. appId = " + app.getId()); - // return null; - } + remoteAppUser = addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService); reqMessage = "Saved Successfully"; } - if (remoteAppUser != null) { + if (remoteAppUser != null) { Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, - mapper, applicationsRestClientService, app.getId(), orgUserId); - + mapper, applicationsRestClientService, app.getId(), orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", - logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", + logMessage, newAppRolesForUser.getApplicationName(), + newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, + reqType); // If no roles remain, request app to set user inactive. /*if (userRolesInRemoteApp.size() == 0) { logger.debug(EELFLoggerDelegate.debugLogger, @@ -1129,7 +1367,20 @@ public class UserRolesCommonServiceImpl { remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService); }*/ + } + } else { + // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote + if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){ + reqMessage = "Saved Successfully"; + } + Set userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), + userRolesInRemoteApp); + logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", + logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, + reqType); } if(!result){ reqMessage = "Failed to save the user app role(s)"; @@ -1138,10 +1389,9 @@ public class UserRolesCommonServiceImpl { updateStatus = "C"; applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0)); } - } } catch (Exception e) { - String message = String.format("Failed to create user or update user roles for User %s, AppId %s", + String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s", orgUserId, appName); logger.error(EELFLoggerDelegate.errorLogger, message, e); result = false; @@ -1268,23 +1518,16 @@ public class UserRolesCommonServiceImpl { * @see org.openecomp.portalapp.portal.service.UserRolesService# * getAppRolesForUser(java.lang.Long, java.lang.String) */ + @SuppressWarnings("unchecked") public List getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) { List rolesInAppForUser = null; - List userInfo = null; + EPApp app = appsService.getApp(appId); try { - // for ecomp portal app, no need to make a remote call if (appId == PortalConstants.PORTAL_APP_ID) { - final Map userParams = new HashMap<>(); - userParams.put("orgUserIdValue", userId); - userInfo = checkIfUserExists(userParams); - if(userInfo.size() == 0 || userInfo.isEmpty()) - { - createLocalUserIfNecessary(userId); - } - List roleList = roleService.getAvailableRoles(); + List roleList = roleService.getAvailableRoles(userId); List activeRoleList = new ArrayList(); for(Role role: roleList) { if(role.getActive()) { @@ -1296,28 +1539,68 @@ public class UserRolesCommonServiceImpl { } } - - EPApp app = appsService.getApp(appId); - EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); - Set roleSet = localUser.getAppEPRoles(app); - rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSet.toArray(new EPRole[0]), extRequestValue); + EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); + // If localUser does not exists return roles + Set roleSet = null; + EPRole[] roleSetList = null; + if(localUser != null){ + roleSet = localUser.getAppEPRoles(app); + roleSetList = roleSet.toArray(new EPRole[0]); + } + rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue); return rolesInAppForUser; } - - EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); - + + EcompRole[] appRoles = null; + List roles = new ArrayList<>(); + if(app.getCentralAuth()){ + //Sync application roles from External Access System + externalAccessRolesService.syncApplicationRolesWithEcompDB(app); + List applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);; + for(EPRole role : applicationRoles){ + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getId()); + ecompRole.setName(role.getName()); + roles.add(ecompRole); + } + appRoles = roles.toArray(new EcompRole[roles.size()]); + } else{ + appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + } // Test this error case, for generating an internal Ecomp Portal // error // EcompRole[] appRoles = null; // If there is an exception in the rest client api, then null will // be returned. if (appRoles != null) { + if(!app.getCentralAuth()) { syncAppRoles(sessionFactory, appId, appRoles); + } EcompRole[] userAppRoles = null; try { try { - userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, - String.format("/user/%s/roles", userId)); + if(app.getCentralAuth()){ + final Map params = new HashMap<>(); + final Map userParams = new HashMap<>(); + params.put("orgUserIdValue", userId); + List user = dataAccessService.executeNamedQuery("epUserAppId", params, null); + userParams.put("appId", app.getId()); + userParams.put("userId", user.get(0).getId()); + List userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null); + List setUserRoles = new ArrayList<>(); + for(EPUserAppCurrentRoles role : userAppsRolesList){ + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getRoleId()); + ecompRole.setName(role.getRoleName()); + setUserRoles.add(ecompRole); + } + userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]); + rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles); + return rolesInAppForUser; + }else{ + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", userId)); + } } catch (HTTPException e) { // Some apps are returning 400 if user is not found. if (e.getResponseCode() == 400) { @@ -1390,7 +1673,7 @@ public class UserRolesCommonServiceImpl { public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) { FieldsValidator fieldsValidator = new FieldsValidator(); final Map params = new HashMap<>(); - EpUserAppRoles appRole= new EpUserAppRoles(); + EPUserAppRoles appRole= new EPUserAppRoles(); 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()); @@ -1409,7 +1692,7 @@ public class UserRolesCommonServiceImpl { Boolean isAppliedVal = userAppRoles.isApplied; params.put("appRoleId", userAppRoles.roleId); if (isAppliedVal) { - appRole = (EpUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0); + appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0); EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail(); epAppRoleDetail.setReqRoleId(appRole.getRoleId()); epAppRoleDetail.setReqType("P");