diff options
Diffstat (limited to 'ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service')
13 files changed, 2781 insertions, 182 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java index 20daa4fc..b5bccfe3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java @@ -22,6 +22,7 @@ package org.openecomp.portalapp.portal.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.annotation.PostConstruct; @@ -29,14 +30,8 @@ import org.apache.cxf.common.util.StringUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.SystemProperties; +import org.json.JSONArray; +import org.json.JSONObject; import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPRole; import org.openecomp.portalapp.portal.domain.EPUser; @@ -48,8 +43,24 @@ import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; @Service("adminRolesService") @Transactional @@ -72,7 +83,9 @@ public class AdminRolesServiceImpl implements AdminRolesService { SearchService searchService; @Autowired EPAppService appsService; - + + RestTemplate template = new RestTemplate(); + @PostConstruct private void init() { try { @@ -208,7 +221,9 @@ public class AdminRolesServiceImpl implements AdminRolesService { localSession.save(EPUserApp.class.getName(), newUserApp); } transaction.commit(); - result = true; + + // Add user admin role for list of centralized applications in external system + result = addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin); } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e); @@ -234,6 +249,129 @@ public class AdminRolesServiceImpl implements AdminRolesService { } @SuppressWarnings("unchecked") + private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) { + boolean result = false; + try { + // Reset All admin role for centralized applications + List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (EPApp app : appList) { + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = user.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + try { + ResponseEntity<String> getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/" + extRole, HttpMethod.GET, entity, String.class); + + if (getResponse.getBody().equals("{}")) { + String addDesc = "{\"name\":\"" + extRole + "\"}"; + HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role", + HttpMethod.POST, roleEntity, String.class); + } else { + try { + HttpEntity<String> deleteUserRole = new HttpEntity<>(headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + extRole, + HttpMethod.DELETE, deleteUserRole, String.class); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Role not found for this user may be it gets deleted before", e); + } + } + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}", + app.getNameSpace(), e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}", + app.getNameSpace(), e); + } + } + } + // Add admin role in external application + // application + for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { + EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id); + try { + if (app.getCentralAuth()) { + String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + HttpEntity<String> entity = new HttpEntity<>(headers); + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = user.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> getUserRolesResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRoles/user/" + name, + HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + if (!getUserRolesResponse.getBody().equals("{}")) { + JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody()); + JSONArray extRoles = jsonObj.getJSONArray("userRole"); + final Map<String, JSONObject> extUserRoles = new HashMap<>(); + for (int i = 0; i < extRoles.length(); i++) { + String userRole = extRoles.getJSONObject(i).getString("role"); + if (userRole.startsWith(app.getNameSpace() + ".") + && !userRole.equals(app.getNameSpace() + ".admin") + && !userRole.equals(app.getNameSpace() + ".owner")) { + + extUserRoles.put(userRole, extRoles.getJSONObject(i)); + } + } + if (!extUserRoles.containsKey(extRole)) { + // Assign with new apps user admin + try { + ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); + // Assign user role for an application in external access system + ObjectMapper addUserRoleMapper = new ObjectMapper(); + String userRole = addUserRoleMapper.writeValueAsString(extUser); + HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, addUserRole, String.class); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e); + } + + } + } + } + result = true; + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.errorLogger, + "Application name space not found in External system for app {} due to bad rquest name space ", app.getNameSpace(), + e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}", + app.getNameSpace(), e); + result = false; + } + } + } + } catch (Exception e) { + result = false; + logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e); + } + return result; + } + + @SuppressWarnings("unchecked") @Override public boolean isSuperAdmin(EPUser user) { if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) { @@ -318,7 +456,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { @EPMetricsLog public List<EPRole> getRolesByApp(EPUser user, Long appId) { List<EPRole> list = new ArrayList<>(); - String sql = "SELECT * FROM FN_ROLE WHERE APP_ID = " + appId; + String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId; @SuppressWarnings("unchecked") List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null); for (EPRole role: roles) { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java index f38b921a..6a0da9ba 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java @@ -44,6 +44,8 @@ import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel; import org.openecomp.portalapp.portal.domain.AppsResponse; import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail; import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference; import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference; import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference; @@ -180,6 +182,8 @@ public class EPAppCommonServiceImpl implements EPAppService { ecompApp.setUebKey(app.getUebKey()); ecompApp.setUebSecret(app.getUebSecret()); ecompApp.setEnabled(app.getEnabled()); + ecompApp.setCentralAuth(app.getCentralAuth()); + ecompApp.setNameSpace(app.getNameSpace()); ecompApp.setRestrictedApp(app.isRestrictedApp()); ecompAppList.add(ecompApp); } @@ -322,15 +326,10 @@ public class EPAppCommonServiceImpl implements EPAppService { @Override public UserRoles getUserProfile(String loginId) { - String format = "SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.org_user_id, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole " - + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " - + "INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID " - + "WHERE user.org_user_id = \"%s\" and (userrole.app_id = 1 or role.role_id = " + ACCOUNT_ADMIN_ROLE_ID - + ") "; - String sql = String.format(format, loginId); - logQuery(sql); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", loginId); @SuppressWarnings("unchecked") - List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserRole.class, null); + List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null); ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList); if (usersRolesList == null || usersRolesList.size() < 1) return null; @@ -382,9 +381,11 @@ public class EPAppCommonServiceImpl implements EPAppService { public List<LocalRole> getAppRoles(Long appId) { String sql = ""; if (isRestrictedApp(appId)) { - sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'"; - } else { - sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where APP_ID = '" + appId + "'"; + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'"; + }else if(appId == 1){ + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL"; + }else{ + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'"; } logQuery(sql); @SuppressWarnings("unchecked") @@ -475,8 +476,8 @@ public class EPAppCommonServiceImpl implements EPAppService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(com.att - * .fusionapp.ecomp.portal.domain.EPUser) + * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog( + * org.openecomp.portalapp.portal.domain.EPUser) */ @Override public List<AppCatalogItem> getUserAppCatalog(EPUser user) { @@ -721,6 +722,7 @@ public class EPAppCommonServiceImpl implements EPAppService { return fieldsValidator; } + @SuppressWarnings("unchecked") @Override public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) { FieldsValidator fieldsValidator = new FieldsValidator(); @@ -728,6 +730,16 @@ public class EPAppCommonServiceImpl implements EPAppService { fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN); return fieldsValidator; } + final Map<String, Long> params = new HashMap<>(); + params.put("app_id", appid); + List<EPUserAppRolesRequest> EPUserAppRolesRequestList= new ArrayList<>(); + EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null); + for(int i=0;i<EPUserAppRolesRequestList.size();i++) + { + dataAccessService.deleteDomainObjects(EPUserAppRolesRequestDetail.class , "req_id=" + EPUserAppRolesRequestList.get(i).getId(),null); + + } + Boolean result = false; Session localSession = null; Transaction transaction = null; @@ -1123,6 +1135,8 @@ public class EPAppCommonServiceImpl implements EPAppService { onboardingApp.uebTopicName = app.getUebTopicName(); onboardingApp.uebKey = app.getUebKey(); onboardingApp.uebSecret = app.getUebSecret(); + onboardingApp.isCentralAuth = app.getCentralAuth(); + onboardingApp.nameSpace = app.getNameSpace(); onboardingApp.setRestrictedApp(app.isRestrictedApp()); // if (app.getThumbnail() != null) // onboardingApp.thumbnail = new @@ -1152,6 +1166,8 @@ public class EPAppCommonServiceImpl implements EPAppService { app.setUebTopicName(onboardingApp.uebTopicName); app.setUebKey(onboardingApp.uebKey); app.setUebSecret(onboardingApp.uebSecret); + app.setCentralAuth(onboardingApp.isCentralAuth); + app.setNameSpace(onboardingApp.nameSpace); app.setRestrictedApp(onboardingApp.restrictedApp); if (!StringUtils.isEmpty(onboardingApp.thumbnail)) { logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty"); @@ -1424,5 +1440,42 @@ public class EPAppCommonServiceImpl implements EPAppService { public List<EPApp> getUserRemoteApps(String id) { throw new RuntimeException(" Cannot be called from parent class"); } + + @Override + public UserRoles getUserProfileForLeftMenu(String loginId) { + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", loginId); + @SuppressWarnings("unchecked") + List<UserRole> userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null); + ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList); + if (usersRolesList == null || usersRolesList.size() < 1) + return null; + + return usersRolesList.get(0); + } + + + @Override + public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) { + // Check database. + UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId()); + // If no roles are defined, treat this user as a guest. + if (user.isGuest() || userAndRoles == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest", + user.getLoginId()); + UserRole userRole = new UserRole(); + userRole.setUser_Id(user.getId()); + userRole.setOrgUserId(user.getLoginId()); + userRole.setFirstName(user.getFirstName()); + userRole.setLastName(user.getLastName()); + userRole.setRoleId(-1L); + userRole.setRoleName("Guest"); + userRole.setUser_Id(-1L); + userAndRoles = new UserRoles(userRole); + } + + return userAndRoles; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java index 1e12dd52..3ab12983 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java @@ -97,7 +97,7 @@ public interface EPAppService { * the user has a defined role for that app. * * @param user - * EPUser object with the user's ATT UID + * EPUser object with the user's Org User ID * @return the user's list of applications, which may be empty. */ List<EPApp> getUserApps(EPUser user); @@ -109,7 +109,7 @@ public interface EPAppService { * applications which the user has chosen to show. * * @param user - * EPUser object with the user's ATT UID + * EPUser object with the user's Org User ID * @return the user's personalized list of applications, which may be empty. */ List<EPApp> getPersAdminApps(EPUser user); @@ -122,7 +122,7 @@ public interface EPAppService { * result. * * @param user - * EPUser object with the user's ATT UID + * EPUser object with the user's Org User ID * @return the user's personalized list of applications, which may be empty. */ List<EPApp> getPersUserApps(EPUser user); @@ -210,4 +210,8 @@ public interface EPAppService { void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp); + UserRoles getUserProfileNormalizedForLeftMenu(EPUser user); + + UserRoles getUserProfileForLeftMenu(String loginId); + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java index 9158e990..f24ab87f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java @@ -73,7 +73,7 @@ public class EPLeftMenuServiceImpl implements EPLeftMenuService { // be revised as Account Administrator may become obsolete try { if (user != null) { - UserRoles uRoles = appService.getUserProfileNormalized(user); + UserRoles uRoles = appService.getUserProfileNormalizedForLeftMenu(user); if (uRoles.getRoles().contains("Account Administrator")) loadAccAdminNavMap(defaultNavMap); } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionService.java new file mode 100644 index 00000000..66a9ccc2 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionService.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalsdk.core.domain.RoleFunction; + +public interface EPRoleFunctionService { + /** + * Builds a set of role functions and sets a session attribute with it. + * + * @param request + * HttpServletRequest + * @return Set of role functions that was built. + */ + public List<RoleFunction> getRoleFunctions(); + + + /** + * Builds a set of role functions of user + * + * @param request + * HttpServletRequest + * @return Set of role functions that was built. + */ + public Set getRoleFunctions(HttpServletRequest request, EPUser user); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImpl.java new file mode 100644 index 00000000..d41100ff --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImpl.java @@ -0,0 +1,70 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + + +@Transactional +public class EPRoleFunctionServiceCentralizedImpl implements EPRoleFunctionService{ + + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings({ "unchecked"}) + @Override + public List<RoleFunction> getRoleFunctions() { + List<CentralRoleFunction> getRoleFuncList = null; + List<RoleFunction> getRoleFuncListOfPortal = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", (long) 1); + //Sync all functions from external system into Ecomp portal DB + getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); + for(CentralRoleFunction roleFunction : getRoleFuncList) + { + RoleFunction roleFun = new RoleFunction(); + roleFun.setCode(roleFunction.getCode()); + roleFun.setName(roleFunction.getName()); + getRoleFuncListOfPortal.add(roleFun); + } + return getRoleFuncListOfPortal; + } + + @SuppressWarnings("unchecked") + @Override + public Set getRoleFunctions(HttpServletRequest request, EPUser user) { + HttpSession session = request.getSession(); + String userId = user.getId().toString(); + final Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + @SuppressWarnings("unchecked") + List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getRoleFunctionsOfUser", params, null); + Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal); + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), + getRoleFuncListOfPortalSet); + return getRoleFuncListOfPortalSet; + + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImpl.java new file mode 100644 index 00000000..f36aa544 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImpl.java @@ -0,0 +1,79 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class EPRoleFunctionServiceImpl implements EPRoleFunctionService { + @Autowired + private DataAccessService dataAccessService; + + + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("unchecked") + @Override + public List<RoleFunction> getRoleFunctions() { + return getDataAccessService().getList(RoleFunction.class, null); + } + + @SuppressWarnings("unchecked") + @Override + public Set getRoleFunctions(HttpServletRequest request, EPUser user) { + HashSet roleFunctions = null; + + HttpSession session = request.getSession(); + roleFunctions = (HashSet) session + .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); + + if (roleFunctions == null) { + HashMap roles = EPUserUtils.getRoles(request); + roleFunctions = new HashSet(); + + Iterator i = roles.keySet().iterator(); + + while (i.hasNext()) { + Long roleKey = (Long) i.next(); + EPRole role = (EPRole) roles.get(roleKey); + + Iterator j = role.getRoleFunctions().iterator(); + + while (j.hasNext()) { + RoleFunction function = (RoleFunction) j.next(); + roleFunctions.add(function.getCode()); + } + } + + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), + roleFunctions); + } + + return roleFunctions; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java new file mode 100644 index 00000000..e57d4fa5 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java @@ -0,0 +1,190 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.hibernate.Session; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; + +public interface ExternalAccessRolesService { + + /** + * It gets all application roles + * + * @param appId + * @param extRequestValue + * @return List + * @throws Exception + */ + public List<EPRole> getAppRoles(Long appId, Boolean extRequestValue) throws Exception; + + /** + * It returns application details + * + * @param uebkey + * @return List + * @throws Exception + */ + public List<EPApp> getApp(String uebkey) throws Exception; + + /** + * Adds role in the external access system if fails throws exception + * + * @param addRoles + * @param UE + * @return boolean + * @throws Exception + */ + public boolean addRole(Role addRoles, String uebkey) throws Exception; + + /** + * Updates role in the external access system otherwise throws exception + * + * @param updateRole + * @param uebkey + * @return boolean + * @throws Exception + */ + void updateRole(Role updateRole, EPApp app) throws Exception; + + /** + * It returns complete user information including application roles permissions + * + * @param loginId + * @param uebkey + * @return String + * @throws Exception + */ + String getUser(String loginId, String uebkey) throws Exception; + + /** + * It returns list of all role functions + * @param string + * @return List + * @throws Exception + */ + List<CentralRoleFunction> getRoleFuncList(String string) throws Exception; + + /** + * It return list of role provided by the app uebkey and roleId + * + * @param roleId + * @param uebkey + * @return CentralRole + * @throws Exception + */ + CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception; + + /** + * It returns the CentralRoleFunction object + * + * @param functionCode + * @param uebkey + * @return CentralRoleFunction + * @throws Exception + */ + public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception; + + /** + * It saves role function in the DB + * + * @param domainCentralRoleFunction + * @param requestedApp + * @throws Exception + */ + public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp requestedApp) throws Exception; + + /** + * It deletes role function in the DB + * + * @param code + * @param string + */ + public void deleteCentralRoleFunction(String code, String string); + + /** + * It gets all roles the applications + * + * @param uebkey + * @return List + * @throws Exception + */ + public List<CentralRole> getRolesForApp(String uebkey) throws Exception; + + /** + * It saves role function in the DB + * + * @param saveRole + * @param uebkey + * @throws Exception + */ + void saveRoleForApplication(Role saveRole, String uebkey) throws Exception; + + /** + * It deletes role in the DB + * + * @param code + * @param uebkey + * @throws Exception + */ + void deleteRoleForApplication(String code, String uebkey) throws Exception; + + /** + * It gets all active roles for single application + * + * @param uebkey + * @return List + * @throws Exception + */ + List<CentralRole> getActiveRoles(String uebkey) throws Exception; + + /** + * It deletes user related roles for an application in the table + * @param roleId + * @param uebkey + * @param LoginId + * @return + * @throws Exception + */ + public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception; + + /** + * It sync new functions codes and names from and updates role functions from external access system + * + * @param app + * @throws Exception + */ + public void syncRoleFunctionFromExternalAccessSystem(EPApp app) throws Exception; + + public Integer bulkUploadFunctions(String uebkey) throws Exception; + + public Integer bulkUploadRoles(String uebkey) throws Exception; + + public void bulkUploadPartnerFunctions(String header, List<RoleFunction> upload) throws Exception; + + public void bulkUploadPartnerRoles(String header, List<Role> upload) throws Exception; + + Integer bulkUploadRolesFunctions(String uebkey) throws Exception; + + /** + * SyncApplicationRolesWithEcompDB sync the roles and rolefunctions to the ecomp DB from AAF + * @param app + * @throws Exception + */ + + void SyncApplicationRolesWithEcompDB(EPApp app) throws Exception; + + public Integer bulkUploadUserRoles(String uebkey) throws Exception; + + void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception; + + public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception; + + List<String> getMenuFunctionsList(String uebkey) throws Exception; + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java new file mode 100644 index 00000000..17d9ceb0 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -0,0 +1,1678 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPAppRoleFunction; +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.ExternalRoleDetails; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction; +import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles; +import org.openecomp.portalapp.portal.transport.CentralApp; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalapp.portal.transport.CentralUser; +import org.openecomp.portalapp.portal.transport.CentralUserApp; +import org.openecomp.portalapp.portal.transport.ExternalAccessPerms; +import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail; +import org.openecomp.portalapp.portal.transport.ExternalAccessRole; +import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; +import org.openecomp.portalapp.portal.transport.ExternalRoleDescription; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; + +@Service("externalAccessRolesService") +@EnableAspectJAutoProxy +@EPMetricsLog +public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + private SessionFactory sessionFactory; + + + RestTemplate template = new RestTemplate(); + + @SuppressWarnings("unchecked") + public List<EPRole> getAppRoles(Long appId, Boolean extRequestValue) throws Exception { + List<EPRole> applicationRoles = null; + String filter = null; + try { + if (appId == 1) { + filter = " where app_id is null"; + } else { + filter = " where app_id = " + appId; + } + applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles is failed", e); + throw new Exception(e.getMessage()); + } + return applicationRoles; + } + + @SuppressWarnings("unchecked") + @Override + public List<EPApp> getApp(String uebkey) throws Exception { + List<EPApp> app = null; + try { + app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getApp is failed", e); + throw new Exception(e.getMessage()); + } + return app; + } + + public String getSingleAppRole(String addRole, EPApp app) throws Exception { + String response = ""; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + response = template + .exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" + + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"), + HttpMethod.GET, entity, String.class) + .getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + + return response; + } + + @Override + public boolean addRole(Role addRole, String uebkey) throws Exception { + boolean response = false; + ResponseEntity<String> addResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + EPApp app = getApp(uebkey).get(0); + String newRole = createNewRoleInExternalSystem(addRole, app); + HttpEntity<String> entity = new HttpEntity<>(newRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() == 201) { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + if (addResponse.getStatusCode().value() == 406) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system but something went wrong!"); + throw new Exception("Failed to create role"); + } + return response; + } + + @Override + public void updateRole(Role addRole, EPApp app) throws Exception { + boolean addResponse = updateRoleInExternalSystem(addRole, app); + if (!addResponse) { + throw new Exception("Failed to update a role"); + } + } + + private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception { + ResponseEntity<String> delResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(delRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + delResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true", + HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + return delResponse; + } + + @SuppressWarnings("unchecked") + private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception { + boolean response = false; + ObjectMapper mapper = new ObjectMapper(); + ResponseEntity<String> deleteResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + List<EPRole> epRoleList = null; + epRoleList = dataAccessService.getList(EPRole.class, + " where role_id = " + updateExtRole.getId(), null, null); + String appRole = getSingleAppRole(epRoleList.get(0).getName(), app); + if (!appRole.equals("{}")) { + JSONObject jsonObj = new JSONObject(appRole); + JSONArray extRole = jsonObj.getJSONArray("role"); + if (!extRole.getJSONObject(0).has("description")) { + String roleName = extRole.getJSONObject(0).getString("name"); + String delRoleKey = "{\"name\":\"" + roleName + "\"}"; + deleteResponse = deleteRoleInExternalSystem(delRoleKey); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role in external access system!"); + } + addRole(updateExtRole, app.getUebKey()); + } else { + String desc = extRole.getJSONObject(0).getString("description"); + String name = extRole.getJSONObject(0).getString("name"); + List<ExternalAccessPerms> list = null; + if (extRole.getJSONObject(0).has("perms")) { + JSONArray perms = extRole.getJSONObject(0).getJSONArray("perms"); + ObjectMapper permsMapper = new ObjectMapper(); + list = permsMapper.readValue(perms.toString(), TypeFactory.defaultInstance() + .constructCollectionType(List.class, ExternalAccessPerms.class)); + } + ObjectMapper roleMapper = new ObjectMapper(); + ExternalRoleDescription sysRoleList = roleMapper.readValue(desc, ExternalRoleDescription.class); + // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts + Boolean existingRoleActive; + boolean res; + // check role active status + existingRoleActive = new Boolean(sysRoleList.getActive()); + res = existingRoleActive.equals(updateExtRole.getActive()); + if (!sysRoleList.getName().equals(updateExtRole.getName())) { + String deleteRoleKey = "{\"name\":\"" + name + "\"}"; + deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role in external access system!"); + } + response = addRole(updateExtRole, app.getUebKey()); + ObjectMapper addPermsMapper = new ObjectMapper(); + response = addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app); + } + ExternalAccessRole updateRole = new ExternalAccessRole(); + if (!res || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority())) || + sysRoleList.getId().equals("null")) { + String updateDesc = ""; + List<EPRole> getRole = dataAccessService.getList(EPRole.class, + " where role_name = '" + updateExtRole.getName() + "'", null, null); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName() + + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\"" + + updateExtRole.getPriority() + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}"; + + } else { + updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName() + + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\"" + + updateExtRole.getPriority() + "\",\"appId\":\"" + app.getId() + "\",\"appRoleId\":\"" + + getRole.get(0).getAppRoleId() + "\"}"; + + } + updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); + updateRole.setDescription(updateDesc); + String updateRoleDesc = mapper.writeValueAsString(updateRole); + HttpEntity<String> entity = new HttpEntity<>(updateRoleDesc, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.PUT, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); + Map<String, RoleFunction> updateRoleFunc = new HashMap<>(); + for (RoleFunction addPerm : roleFunctionListNew) { + updateRoleFunc.put(addPerm.getCode(), addPerm); + } + final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>(); + // Update permissions in the ExternalAccess System + ObjectMapper permMapper = new ObjectMapper(); + if (list != null) { + for (ExternalAccessPerms perm : list) { + if (!updateRoleFunc.containsKey(perm.getInstance())) { + removePermForRole(perm, permMapper, name, headers); + } + extRolePermMap.put(perm.getInstance(), perm); + } + } + response = true; + if (!roleFunctionListNew.isEmpty() || roleFunctionListNew.size() > 0) { + for (RoleFunction roleFunc : roleFunctionListNew) { + if (!extRolePermMap.containsKey(roleFunc.getCode())) { + String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url"; + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), + "*"); + extRolePerms = new ExternalAccessRolePerms(extPerms, + app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201) { + response = false; + logger.debug(EELFLoggerDelegate.debugLogger, + "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + } + } + } + } + } else { + // It seems like role exists in local DB but not in External Access system + addRole(updateExtRole, app.getUebKey()); + List<RoleFunction> roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole); + response = true; + if (!roleFunctionListUpdate.isEmpty() || roleFunctionListUpdate.size() > 0) { + ObjectMapper addPermsMapper = new ObjectMapper(); + addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app); + } + } + return response; + } + + private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app) throws Exception { + boolean response = false; + ExternalAccessRolePerms extAddRolePerms = null; + ExternalAccessPerms extAddPerms = null; + List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (RoleFunction roleFunc : roleFunctionListAdd) { + String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url"; + extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), + "*"); + extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, + app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); + String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201) { + response = false; + logger.debug(EELFLoggerDelegate.debugLogger, + "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + } + return response; + } + + @SuppressWarnings("unchecked") + private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole){ + Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions(); + List<RoleFunction> roleFunctionList = new ArrayList<>(); + ObjectMapper roleFuncMapper = new ObjectMapper(); + Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class); + roleFunctionList.add(roleFunction); + } + return roleFunctionList.stream().distinct().collect(Collectors.toList()); + } + + private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper,String name, HttpHeaders headers) throws Exception { + ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name); + String permDetails = permMapper.writeValueAsString(extAccessRolePerms); + HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> deletePermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/"+name+"/perm", HttpMethod.DELETE, deleteEntity, String.class); + if (deletePermResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role function"); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + + private boolean addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception { + boolean response = false; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + ObjectMapper mapper = new ObjectMapper(); + String addNewRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + String addDesc = null; + addDesc = "{\"id\":\"" + newRole.get(0).getId() + "\",\"name\":\"" + newRole.get(0).getName() + "\",\"active\":\"" + + newRole.get(0).getActive() + "\",\"priority\":\"" +newRole.get(0).getPriority() + "\",\"appId\":\"" + + newRole.get(0).getAppId() + "\",\"appRoleId\":\"" + newRole.get(0).getAppRoleId() + "\"}"; + + extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_")); + extRole.setDescription(addDesc); + addNewRole = mapper.writeValueAsString(extRole); + HttpEntity<String> deleteEntity = new HttpEntity<>(addNewRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role", HttpMethod.POST, deleteEntity, String.class); + if (addNewRoleInExternalSystem.getStatusCode().value() != 201) { + throw new Exception("Failed to add Role in External System"); + } else{ + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + response = true; + } + return response; + } + + @SuppressWarnings("unchecked") + private String createNewRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + String addNewRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + List<EPRole> role = null; + String addDesc = null; + if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + role = dataAccessService.getList(EPRole.class, + " where role_id = " + addRole.getId(), null, null); + addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\"" + + role.get(0).getActive() + "\",\"priority\":\"" + role.get(0).getPriority() + + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}"; + } else{ + role = dataAccessService.getList(EPRole.class, + " where app_role_id = " + addRole.getId(), null, null); + addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\"" + + role.get(0).getActive() + "\",\"priority\":\"" + addRole.getPriority() + "\",\"appId\":\"" + + app.getId() + "\",\"appRoleId\":\"" + role.get(0).getAppRoleId() + "\"}"; + } + extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_")); + extRole.setDescription(addDesc); + addNewRole = mapper.writeValueAsString(extRole); + return addNewRole; + } + + @SuppressWarnings("unchecked") + @Transactional + private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { + boolean result = false; + List<EPRole> applicationRoles = null; + EPRole epRole = null; + Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions(); + List<RoleFunction> roleFunctionListNew = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFunction); + } + List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList()); + try { + if (addRoleInDB.getId() == null) { // check if it is new role + checkIfRoleExitsInExternalSystem(addRoleInDB, app); + EPRole epRoleNew = new EPRole(); + epRoleNew.setActive(addRoleInDB.getActive()); + epRoleNew.setName(addRoleInDB.getName()); + epRoleNew.setPriority(addRoleInDB.getPriority()); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleNew.setAppId(null); + } else { + epRoleNew.setAppId(app.getId()); + } + dataAccessService.saveDomainObject(epRoleNew, null); + List <EPRole> getRoleCreated = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + List<EPRole> roleCreated = dataAccessService.getList(EPRole.class, + " where role_name = '" + addRoleInDB.getName() +"'", null, null); + EPRole epUpdateRole = roleCreated.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + getRoleCreated = dataAccessService.getList(EPRole.class, + " where role_name = '" + addRoleInDB.getName() +"'", null, null); + } else{ + getRoleCreated = dataAccessService.getList(EPRole.class, + " where role_name = '" + addRoleInDB.getName() +"'", null, null); + } + // Add role in External Access system + boolean response = addNewRoleInExternalSystem(getRoleCreated, app); + + if (!response) { + throw new Exception("Failed to add role!"); + } + } else { // if role already exists then update it + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + applicationRoles = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null); + } else { + applicationRoles = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null); + } + if(applicationRoles.isEmpty() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + applicationRoles = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_id = " + addRoleInDB.getId(), null, null); + } + updateRoleInExternalSystem(addRoleInDB, app); + deleteRoleFunction(app, applicationRoles); + if (applicationRoles.size() > 0 || !applicationRoles.isEmpty()) { + epRole = applicationRoles.get(0); + epRole.setName(addRoleInDB.getName()); + epRole.setPriority(addRoleInDB.getPriority()); + epRole.setActive(addRoleInDB.getActive()); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRole.setAppId(null); + epRole.setAppRoleId(null); + } else if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && applicationRoles.get(0).getAppRoleId() == null){ + epRole.setAppRoleId(epRole.getId()); + } + dataAccessService.saveDomainObject(epRole, null); + } + + saveRoleFunction(listWithoutDuplicates, app, applicationRoles); + } + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e); + throw new Exception(e.getMessage()); + } + return result; + } + + private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String roleName = app.getNameSpace()+"."+checkRole.getName().replaceAll(" ", "_"); + HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> checkRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/"+roleName, HttpMethod.GET, checkRoleEntity, String.class); + if(!checkRoleInExternalSystem.getBody().equals("{}")){ + logger.debug("Role already exists in external system ", checkRoleInExternalSystem.getBody()); + throw new Exception("Role already exists in external system"); + } + } + + private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles) throws Exception { + for (RoleFunction roleFunc : roleFunctionListNew) { + EPAppRoleFunction appRoleFunc = new EPAppRoleFunction(); + appRoleFunc.setAppId(app.getId()); + appRoleFunc.setRoleId(applicationRoles.get(0).getId()); + appRoleFunc.setCode(roleFunc.getCode()); + dataAccessService.saveDomainObject(appRoleFunc, null); + } + } + + @SuppressWarnings("unchecked") + private void deleteRoleFunction(EPApp app, List<EPRole> role) { + List<EPAppRoleFunction> appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class, + " where app_id = " + app.getId() + " and role_id = " + role.get(0).getId(), null, null); + if (!appRoleFunctionList.isEmpty() || appRoleFunctionList.size() > 0) { + for (EPAppRoleFunction approleFunction : appRoleFunctionList) { + dataAccessService.deleteDomainObject(approleFunction, null); + } + } + } + + @SuppressWarnings("unchecked") + public String getUser(String loginId, String uebkey) throws Exception { + final Map<String, String> params = new HashMap<>(); + List<EPUser> userList = null; + CentralUser cenUser = null; + EPApp app = null; + String result = null; + try { + params.put("orgUserIdValue", loginId); + List<EPApp> appList = (List<EPApp>) getApp(uebkey); + if (appList.size() > 0) { + app = appList.get(0); + userList = (List<EPUser>) dataAccessService.getList(EPUser.class, + " where org_user_id = '" + loginId + "'", null, null); + if (userList.size() > 0) { + EPUser user = userList.get(0); + ObjectMapper mapper = new ObjectMapper(); + Set<EPUserApp> userAppSet = user.getEPUserApps(); + cenUser = createEPUser(user, userAppSet, app); + result = mapper.writeValueAsString(cenUser); + } else if (userList.size() == 0) { + throw new Exception("User not found"); + } + } else { + throw new Exception("Application not found"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUser is failed", e); + throw new Exception(e.getMessage()); + } + return result; + } + + @Override + public List<CentralRole> getRolesForApp(String uebkey) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getRolesForApp"); + List<CentralRole> roleList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + try { + List<EPApp> app = getApp(uebkey); + List<EPRole> appRolesList = getAppRoles(app.get(0).getId(), null); + createCentralRoleObject(app, appRolesList, roleList, params); + } catch (Exception e) { + throw new Exception("getRolesForApp Failed", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Finished getRolesForApp"); + return roleList; + } + + @SuppressWarnings("unchecked") + @Override + public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<CentralRoleFunction> getRoleFuncList = null; + final Map<String, Long> params = new HashMap<>(); + params.put("appId", app.getId()); + //Sync all functions from external system into Ecomp portal DB + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into syncRoleFunctionFromExternalAccessSystem"); + syncRoleFunctionFromExternalAccessSystem(app); + logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem"); + getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); + return getRoleFuncList; + } + + @SuppressWarnings("unchecked") + public CentralUser createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception { + + final Map<String, Long> params = new HashMap<>(); + CentralUser userAppList = new CentralUser(); + CentralUser user1 = null; + try { + userAppList.userApps = new TreeSet<CentralUserApp>(); + for (EPUserApp userApp : userAppSet) { + if (userApp.getRole().getActive()) { + EPApp epApp = userApp.getApp(); + String globalRole = userApp.getRole().getName().toLowerCase(); + if (((epApp.getId().equals(app.getId())) + && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))) + || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) + && (globalRole.startsWith("global_")))) { + CentralUserApp cua = new CentralUserApp(); + cua.setUserId(null); + CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(), + epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(), + epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(), + epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(), + epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(), + String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()), + epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(), + epApp.getUebTopicName()); + cua.setApp(cenApp); + params.put("roleId", userApp.getRole().getId()); + params.put("appId", userApp.getApp().getId()); + List<CentralRoleFunction> appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>(); + for (CentralRoleFunction roleFunc : appRoleFunctionList) { + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), + roleFunc.getCode(), roleFunc.getName(), null, null); + roleFunctionSet.add(cenRoleFunc); + } + CentralRole cenRole = new CentralRole(userApp.getRole().getAppRoleId(), + userApp.getRole().getCreated(), userApp.getRole().getModified(), + userApp.getRole().getCreatedId(), userApp.getRole().getModifiedId(), + userApp.getRole().getRowNum(), userApp.getRole().getName(), + userApp.getRole().getActive(), userApp.getRole().getPriority(), roleFunctionSet, null, + null); + cua.setRole(cenRole); + + userAppList.userApps.add(cua); + } + } + } + + user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(), + userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(), + userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(), + userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(), + userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(), + userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(), + userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(), + userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(), + userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(), + userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(), + userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(), + userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(), + userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(), + userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(), + userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createEPUser failed", e); + throw new Exception(e.getMessage()); + } + + return user1; + } + + @SuppressWarnings("unchecked") + @Override + public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception { + final Map<String, Long> params = new HashMap<>(); + List<CentralRole> roleList = new ArrayList<>(); + CentralRole cenRole = new CentralRole(); + List<EPRole> roleInfo = null; + List<EPApp> app = null; + try { + app = getApp(uebkey); + if (app.isEmpty() || app.size() == 0) { + throw new Exception("Application not found"); + } + String filter = null; + if (app.get(0).getId() == PortalConstants.PORTAL_APP_ID) { + filter = " where role_id = " + roleId + " and app_id is null "; + } else { + filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId(); + + } + roleInfo = dataAccessService.getList(EPRole.class, filter, null, null); + roleList = createCentralRoleObject(app, roleInfo, roleList, params); + if (roleList.isEmpty()) { + return cenRole; + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e); + throw new Exception(e.getMessage()); + + } + return roleList.get(0); + } + + @SuppressWarnings("unchecked") + private List<CentralRole> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo, + List<CentralRole> roleList, Map<String, Long> params) { + for (EPRole role : roleInfo) { + params.put("roleId", role.getId()); + params.put("appId", app.get(0).getId()); + List<CentralRoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList", + params, null); + SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<CentralRoleFunction>(); + for (CentralRoleFunction roleFunc : cenRoleFuncList) { + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(), + roleFunc.getName(), null, null); + roleFunctionSet.add(cenRoleFunc); + } + SortedSet<CentralRole> childRoles = new TreeSet<CentralRole>(); + CentralRole cenRole = null; + if (role.getAppRoleId() == null) { + cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), + role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(), + roleFunctionSet, childRoles, null); + } else { + cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(), + role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), + role.getPriority(), roleFunctionSet, childRoles, null); + } + roleList.add(cenRole); + } + return roleList; + } + + @SuppressWarnings("unchecked") + @Override + public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception { + CentralRoleFunction roleFunc = null; + EPApp app = getApp(uebkey).get(0); + List<CentralRoleFunction> getRoleFuncList = null; + final Map<String, String> params = new HashMap<>(); + try { + params.put("functionCode", functionCode); + params.put("appId", String.valueOf(app.getId())); + getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null); + if (getRoleFuncList.isEmpty() | getRoleFuncList.size() == 0) { + return roleFunc; + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e); + throw new Exception("getRoleFunction failed"); + } + return getRoleFuncList.get(0); + } + + @Override + public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { + try { + addRoleFunctionInExternalSystem(domainCentralRoleFunction, app); + dataAccessService.saveDomainObject(domainCentralRoleFunction, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction failed", e); + throw new Exception(e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + ObjectMapper mapper = new ObjectMapper(); + final Map<String, String> params = new HashMap<>(); + params.put("functionCd", domainCentralRoleFunction.getCode()); + params.put("appId", String.valueOf(app.getId())); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params, + null); + String roleFuncName = null; + if (!appRoleFunc.isEmpty()) { + roleFuncName = appRoleFunc.get(0).getCode(); + } else { + roleFuncName = domainCentralRoleFunction.getCode(); + } + String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + HttpEntity<String> getSinglePermEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> getResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/" + + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*", + HttpMethod.GET, getSinglePermEntity, String.class); + if (getResponse.getStatusCode().value() != 200) { + throw new Exception(getResponse.getBody()); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + String res = getResponse.getBody(); + if (res.equals("{}")) { + try{ + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e); + } + } else { + try{ + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.PUT, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e); + + } + } + } + + @Override + @Transactional + public void deleteCentralRoleFunction(String code, String uebkey) { + try { + EPApp app = getApp(uebkey).get(0); + final Map<String, String> params = new HashMap<>(); + params.put("functionCd", code); + params.put("appId", String.valueOf(app.getId())); + CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null).get(0); + deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app); + //Delete role function dependecy records + deleteAppRoleFunctions(code, app); + dataAccessService.deleteDomainObject(domainCentralRoleFunction, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction failed", e); + } + } + + private void deleteAppRoleFunctions(String code, EPApp app) { + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = "+app.getId()+" and function_cd = '"+ code +"'", null); + } + + private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + try{ + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm?force=true", + HttpMethod.DELETE, entity, String.class); + } catch(Exception e){ + if(e.getMessage().equalsIgnoreCase("404 Not Found")){ + logger.debug(EELFLoggerDelegate.debugLogger, " It seems like function is already deleted in external central auth system but exists in local DB", e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to delete functions in External System", e); + } + } + } + + @Override + public void saveRoleForApplication(Role saveRole, String uebkey) throws Exception { + try { + EPApp app = getApp(uebkey).get(0); + addRoleInEcompDB(saveRole, app); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e); + throw new Exception(e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + @Override + public void deleteRoleForApplication(String deleteRole, String uebkey) throws Exception { + Session localSession = null; + Transaction transaction = null; + boolean result = false; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + + List<EPRole> epRoleList = null; + ResponseEntity<String> deleteResponse = null; + EPApp app = getApp(uebkey).get(0); + if(app.getId() == 1) + { + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id is null " + "and role_name = '" + deleteRole +"'", null, null); + } + else{ + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_name = '" + deleteRole +"'", null, null); + } + // Delete app role functions before deleting role + deleteRoleFunction(app, epRoleList); + if(app.getId() == 1) + { + // Delete fn_user_ role + dataAccessService.deleteDomainObjects(EPUserApp.class, + " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + + deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId()); + } + // Delete Role in External System + String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}"; + deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role in external access system!"); + } + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + dataAccessService.deleteDomainObject(epRoleList.get(0), null); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication failed", e); + throw new Exception(e.getMessage()); + }finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in deleteRoleForApplication while closing database session for role: '" + deleteRole + "'."); + } + } + } + + private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> getResponse = template + .exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" + + LoginId + + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"), + HttpMethod.GET, entity, String.class); + if (getResponse.getStatusCode().value() != 200) { + throw new Exception(getResponse.getBody()); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + String res = getResponse.getBody(); + if (!res.equals("{}")) { + HttpEntity<String> userRoleentity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> deleteResponse = template + .exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + LoginId + + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"), + HttpMethod.DELETE, userRoleentity, String.class); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete user role"); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + } + + @SuppressWarnings("unchecked") + @Override + public List<CentralRole> getActiveRoles(String uebkey) throws Exception { + List<CentralRole> roleList = new ArrayList<>(); + try { + List<EPApp> app = getApp(uebkey); + final Map<String, Long> params = new HashMap<>(); + // check if portal + Long appId = null; + if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + appId = app.get(0).getId(); + } + List<EPRole> epRole = dataAccessService.getList(EPRole.class, + " where app_id = " + appId + " and active_yn = 'Y'", null, null); + roleList = createCentralRoleObject(app, epRole, roleList, params); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e); + throw new Exception(e.getMessage()); + } + return roleList; + + } + + @SuppressWarnings("unchecked") + @Override + public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + EPApp app = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + List<EPRole> epRoleList = null; + app = getApp(uebkey).get(0); + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and app_role_id = " + roleId, null, null); + if(epRoleList.isEmpty()){ + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_id = " + roleId, null, null); + } + // Delete User Role in External System before deleting role + deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId); + // Delete user app roles + dataAccessService.deleteDomainObjects(EPUserApp.class, + " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + + deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "deleteDependcyRoleRecord rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncAppRoles while closing database session for role: '" + app.getId() + "'."); + } + } + } + + @SuppressWarnings("unchecked") + @Transactional + public void syncRoleFunctionFromExternalAccessSystem(EPApp app){ + try{ + ResponseEntity<String> response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res); + JSONObject jsonObj = new JSONObject(res); + JSONArray extPerms = jsonObj.getJSONArray("perm"); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) { + extPerms.remove(i); + i--; + } + } + ExternalAccessPermsDetail permDetails = null; + List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>(); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).has("roles")) { + ObjectMapper rolesListMapper = new ObjectMapper(); + JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); + List<String> list = rolesListMapper.readValue(resRoles.toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"), + list, extPerms.getJSONObject(i).getString("description")); + permsDetailList.add(permDetails); + } else { + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString("description")); + permsDetailList.add(permDetails); + } + } + + final Map<String, Long> params = new HashMap<>(); + final Map<String, CentralRoleFunction> roleFuncMap = new HashMap<>(); + params.put("appId", app.getId()); + List<CentralRoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, + null); + if (appFunctions.size() > 0) { + for (CentralRoleFunction roleFunc : appFunctions) { + roleFuncMap.put(roleFunc.getCode(), roleFunc); + } + } + // delete all application role functions + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null); + + // Add if new functions and app role functions were added in Externalsystem + for (ExternalAccessPermsDetail permsDetail : permsDetailList) { + if (!roleFuncMap.containsKey(permsDetail.getInstance())) { + CentralRoleFunction addFunction = new CentralRoleFunction(); + addFunction.setAppId(app.getId()); + addFunction.setCode(permsDetail.getInstance()); + addFunction.setName(permsDetail.getDescription()); + dataAccessService.saveDomainObject(addFunction, null); + } + List<EPRole> epRolesList = null; + List<String> roles = permsDetail.getRoles(); + if (roles != null) { + for (String roleList : roles) { + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'", + null, null); + } else { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'", + null, null); + } + if(epRolesList.isEmpty()){ + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1) + + "'", + null, null); + } else { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1)+"'", + null, null); + } + } + // save all application role functions + if (epRolesList.size() > 0 || !epRolesList.isEmpty()) { + EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); + addAppRoleFunc.setAppId(app.getId()); + addAppRoleFunc.setCode(permsDetail.getInstance()); + addAppRoleFunc.setRoleId(epRolesList.get(0).getId()); + dataAccessService.saveDomainObject(addAppRoleFunc, null); + } + } + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem"); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed syncRoleFunctionFromExternalAccessSystem", e); + + } + } + + @SuppressWarnings("unchecked") + public Integer bulkUploadFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<RoleFunction> roleFuncList = null; + roleFuncList = dataAccessService.getList(RoleFunction.class, null); + CentralRoleFunction cenRoleFunc = null; + Integer functionsAdded = 0; + try { + for (RoleFunction roleFunc : roleFuncList) { + cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName()); + addRoleFunctionInExternalSystem(cenRoleFunc, app); + functionsAdded++; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e.getMessage(), e); + } + return functionsAdded; + } + + public Integer bulkUploadRoles(String uebkey) throws Exception { + List<EPApp> app = getApp(uebkey); + List<EPRole> roles = getAppRoles(app.get(0).getId(), null); + List<CentralRole> cenRoleList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + Integer rolesListAdded = 0; + try { + cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); + String roleList = mapper.writeValueAsString(cenRoleList); + List<Role> roleObjectList = mapper.readValue(roleList, + TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); + for (Role role : roleObjectList) { + addRoleInExternalSystem(role, app.get(0)); + rolesListAdded++; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + throw new Exception(e.getMessage()); + } + return rolesListAdded; + } + + private void addRoleInExternalSystem(Role role, EPApp app) throws Exception { + String addRoleNew = createNewRoleInExternalSystem(role, app); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try{ + HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + } catch(Exception e){ + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, "Role already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleInExternalSystem", e.getMessage()); + } + } + } + + @SuppressWarnings("unchecked") + public Integer bulkUploadRolesFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<EPRole> roles = getAppRoles(app.getId(), null); + final Map<String, Long> params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null); + if(!appRoleFunc.isEmpty()){ + for(BulkUploadRoleFunction addRoleFunc : appRoleFunc){ + addRoleFunctionsInExternalSystem(addRoleFunc, role, app); + roleFunctions++; + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions failed", e); + } + return roleFunctions; + } + + private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app){ + String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + ObjectMapper mapper = new ObjectMapper(); + try{ + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", addRoleFunc.getFunctionName()); + extRolePerms = new ExternalAccessRolePerms(extPerms, + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", HttpMethod.POST, entity, String.class); + } catch(Exception e){ + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, "RoleFunction already exits but does not break functionality",e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", e.getMessage()); + } + } + } + + @Override + public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception { + EPApp app = getApp(uebkey).get(0); + CentralRoleFunction cenRoleFunc = null; + for (RoleFunction roleFunction : roleFunctionsList) { + cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName()); + addRoleFunctionInExternalSystem(cenRoleFunc, app); + } + } + + @Override + public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception { + EPApp app = getApp(uebkey).get(0); + for (Role role : roleList) { + addRoleInExternalSystem(role, app); + } + } + + @SuppressWarnings("unchecked") + @Override + public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception { + EPApp app = getApp(uebkey).get(0); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (Role role : roleList) { + try { + Set<RoleFunction> roleFunctionList = role.getRoleFunctions(); + List<RoleFunction> roleFunctionListNew = new ArrayList<>(); + ObjectMapper roleFunctionsMapper = new ObjectMapper(); + Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFunction); + } + List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct() + .collect(Collectors.toList()); + for (RoleFunction roleFunction : listWithoutDuplicates) { + String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url"; + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + ObjectMapper mapper = new ObjectMapper(); + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(), + "*"); + extRolePerms = new ExternalAccessRolePerms(extPerms, + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", HttpMethod.PUT, entity, String.class); + } + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "RoleFunction already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", + e.getMessage()); + } + } + + } + } + + @SuppressWarnings("unchecked") + @Transactional + public void SyncApplicationRolesWithEcompDB(EPApp app){ + try{ + ResponseEntity<String> response = null; + List<EPRole> finalRoleList = new ArrayList<>(); + ExternalRoleDescription ApplicationRole = new ExternalRoleDescription(); + ExternalAccessPerms externalAccessPerms = null; + List<String> functionCodelist = new ArrayList<>(); + List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res); + JSONObject jsonObj = new JSONObject(res); + JSONArray extRole = jsonObj.getJSONArray("role"); + for (int i = 0; i < extRole.length(); i++) { + if (extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin") + || extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner") + ) { + extRole.remove(i); + i--; + } + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get("name").equals(app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))){ + extRole.remove(i); + i--; + } + } + List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>(); + for (int i = 0; i < extRole.length(); i++) { + ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); + EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); + JSONObject Role = (JSONObject) extRole.get(i); + if(!extRole.getJSONObject(i).has("description")) + { + ApplicationRole.setActive("true"); + ApplicationRole.setAppId("null"); + ApplicationRole.setPriority("null"); + ApplicationRole.setAppRoleId("null"); + String roleName =extRole.getJSONObject(i).getString("name"); + ApplicationRole.setName(roleName.substring(app.getNameSpace().length()+1)); + } + else { + String desc = extRole.getJSONObject(i).getString("description"); + ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class); + } + + + SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>(); + if (extRole.getJSONObject(i).has("perms")) { + JSONArray extPerm = (JSONArray) Role.get("perms"); + for (int j = 0; j < extPerm.length(); j++) { + JSONObject perms = extPerm.getJSONObject(j); + externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), perms.getString("instance"), + perms.getString("action")); + ePAppRoleFunction.setCode(externalAccessPerms.getInstance()); + functionCodelist.add(ePAppRoleFunction.getCode()); + externalAccessPermsOfRole.add(externalAccessPerms); + } + } + + if (ApplicationRole.getActive().equals("null")) { + externalRoleDetail.setActive(false); + } else { + externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString())); + } + externalRoleDetail.setName(ApplicationRole.getName()); + + if (ApplicationRole.getAppId().equals("null") && app.getId() == 1) { + externalRoleDetail.setAppId(null); + } else if(ApplicationRole.getAppId().equals("null")){ + externalRoleDetail.setAppId(app.getId()); + }else { + externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString())); + } + + if (ApplicationRole.getPriority().equals("null")) { + externalRoleDetail.setPriority(null); + } else { + externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString())); + } + + if (ApplicationRole.getAppRoleId().equals("null") && app.getId() == 1) { + externalRoleDetail.setAppRoleId(null); + } + + if (!externalAccessPermsOfRole.isEmpty() || externalAccessPermsOfRole.size() > 0) { + for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) { + EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); + apRoleFunction.setAppId(app.getId()); + apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); + apRoleFunction.setCode(externalpermission.getInstance()); + applicationRoleFunctionList.add(apRoleFunction); + } + } + externalRoleDetailsList.add(externalRoleDetail); + } + + for (ExternalRoleDetails externalRole : externalRoleDetailsList) { + EPRole ecompRole = new EPRole(); + ecompRole = convertExternalRoleDetailstoEpRole(externalRole); + finalRoleList.add(ecompRole); + } + + List<EPRole> applicationRolesList = new ArrayList<>(); + applicationRolesList = getAppRoles(app.getId(), null); + List<String> applicationRoleIdList = new ArrayList<>(); + for (EPRole applicationRole : applicationRolesList) { + applicationRoleIdList.add(applicationRole.getName()); + } + + List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>(); + for (EPRole aafRole : finalRoleList) { + if (!applicationRoleIdList.contains(aafRole.getName())) { + roleListToBeAddInEcompDB.add(aafRole); + } + } + + // Check if roles exits in external Access system and make it inactive + final Map<String, EPRole> checkRolesInactive = new HashMap<>(); + for(EPRole extrole : finalRoleList){ + checkRolesInactive.put(extrole.getName(), extrole); + } + for (EPRole role : applicationRolesList) { + final Map<String, String> extRoleParams = new HashMap<>(); + List<EPRole> roleList = new ArrayList<>(); + extRoleParams.put("appRoleName", role.getName()); + if (!checkRolesInactive.containsKey(role.getName())) { + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null); + } else { + extRoleParams.put("appId", app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null); + } + EPRole updateRoleInactive = roleList.get(0); + updateRoleInactive.setActive(false); + dataAccessService.saveDomainObject(updateRoleInactive, null); + } + } + + for (EPRole roleItem : finalRoleList) { + final Map<String, String> roleParams = new HashMap<>(); + List<EPRole> currentList = new ArrayList<>(); + roleParams.put("appRoleName", roleItem.getName()); + if (app.getId() == 1) { + currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null); + } else { + roleParams.put("appId", app.getId().toString()); + currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null); + } + + if (!currentList.isEmpty()) { + Boolean aafRoleActive; + Boolean localRoleActive; + boolean result; + aafRoleActive = Boolean.valueOf(roleItem.getActive()); + localRoleActive = Boolean.valueOf(currentList.get(0).getActive()); + result = aafRoleActive.equals(localRoleActive); + EPRole updateRole = currentList.get(0); + + if (!result) { + updateRole.setActive(roleItem.getActive()); + dataAccessService.saveDomainObject(updateRole, null); + } + if (roleItem.getPriority() != null + && !currentList.get(0).getPriority().equals(roleItem.getPriority())) { + updateRole.setPriority(roleItem.getPriority()); + dataAccessService.saveDomainObject(updateRole, null); + } + } + } + + EPRole roleToBeAddedInEcompDB = new EPRole(); + for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { + roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); + if(app.getId() == 1) + { + roleToBeAddedInEcompDB.setAppRoleId(null); + } + dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); + List <EPRole> getRoleCreatedInSync = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getRoleCreatedInSync = dataAccessService.getList(EPRole.class, + " where role_name = '" + roleToBeAddedInEcompDB.getName() +"'", null, null); + EPRole epUpdateRole = getRoleCreatedInSync.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + } + List<EPRole> roleList = new ArrayList<>(); + final Map<String, String> params = new HashMap<>(); + + params.put("appRoleName", roleToBeAddedInEcompDB.getName()); + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null); + } else { + params.put("appId", app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null); + } + EPRole role = roleList.get(0); + Role aaFrole = new Role(); + aaFrole.setId(role.getId()); + aaFrole.setActive(role.getActive()); + aaFrole.setPriority(role.getPriority()); + aaFrole.setName(role.getName()); + updateRoleInExternalSystem(aaFrole, app); + } + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null); + for (EPAppRoleFunction rolefun : applicationRoleFunctionList) { + dataAccessService.saveDomainObject(rolefun, null); + } + + logger.debug(EELFLoggerDelegate.debugLogger, "Finished SyncApplicationRolesWithEcompDB"); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e); + } + } + + public EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { + EPRole role = new EPRole(); + role.setActive(externalRoleDetails.isActive()); + role.setAppId(externalRoleDetails.getAppId()); + role.setAppRoleId(externalRoleDetails.getAppRoleId()); + role.setName(externalRoleDetails.getName()); + role.setPriority(externalRoleDetails.getPriority()); + return role; + } + + @SuppressWarnings("unchecked") + @Override + public Integer bulkUploadUserRoles(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + List<BulkUploadUserRoles> userRolesList = null; + Integer userRolesAdded = 0; + if (app.getCentralAuth()) { + userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null); + for (BulkUploadUserRoles userRolesUpload : userRolesList) { + addUserRoleInExternalSystem(userRolesUpload); + userRolesAdded++; + } + } + return userRolesAdded; + } + + private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload){ + try{ + String name = ""; + ObjectMapper mapper = new ObjectMapper(); + if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = userRolesUpload.getOrgUserId() + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ExternalAccessUser extUser = new ExternalAccessUser(name, + userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_")); + String userRole = mapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, entity, String.class); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, "UserRole already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addUserRoleInExternalSystem", e.getMessage()); + } + } + } + + @Override + public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception { + try { + // 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_app_role_function + sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + 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(); + + //Delete form EP_WIDGET_CATALOG_ROLE + sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + //Delete form EP_WIDGET_CATALOG_ROLE + sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + //Delete form fn_menu_functional_roles + sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord failed " , e); + throw new Exception("delete Failed"+ e.getMessage()); + } + + } + + + @SuppressWarnings("unchecked") + @Override + public List<String> getMenuFunctionsList(String uebkey) throws Exception { + List<String> appMenuFunctionsList = null; + try{ + EPApp app = getApp(uebkey).get(0); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed getMenuFunctionsList", e); + return appMenuFunctionsList; + } + return appMenuFunctionsList; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java index 0963f048..5979fe82 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java @@ -29,25 +29,34 @@ import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; import org.openecomp.portalapp.portal.transport.FieldsValidator; import org.openecomp.portalapp.portal.transport.PortalAdmin; import org.openecomp.portalapp.portal.transport.PortalAdminUserRole; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; @Service("portalAdminService") @org.springframework.context.annotation.Configuration @EnableAspectJAutoProxy @EPMetricsLog -public class PortalAdminServiceImpl implements PortalAdminService { +public class PortalAdminServiceImpl implements PortalAdminService { private String SYS_ADMIN_ROLE_ID = "1"; private String ECOMP_APP_ID = "1"; @@ -60,7 +69,11 @@ public class PortalAdminServiceImpl implements PortalAdminService { private DataAccessService dataAccessService; @Autowired SearchService searchService; - + @Autowired + private EPAppService epAppService; + + RestTemplate template = new RestTemplate(); + @PostConstruct private void init() { SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID); @@ -130,7 +143,8 @@ public class PortalAdminServiceImpl implements PortalAdminService { } transaction.commit(); - result = true; + // Add role in the external central auth system + result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE); } catch (Exception e) { EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e); logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); @@ -147,6 +161,42 @@ public class PortalAdminServiceImpl implements PortalAdminService { } return fieldsValidator; } + + private boolean addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole){ + boolean result = false; + try{ + String name = ""; + if (EPCommonSystemProperties.containsProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = loginId + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID); + String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_"); + ObjectMapper addUserRoleMapper = new ObjectMapper(); + ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); + String userRole = addUserRoleMapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + + HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", + HttpMethod.POST, addUserRole, String.class); + result = true; + } catch (Exception e) { + // This happens only if role already exists in external central access system but not in local DB thats where we logging here + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + result = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e); + result = false; + } + } + return result; + } public FieldsValidator deletePortalAdmin(Long userId) { FieldsValidator fieldsValidator = new FieldsValidator(); @@ -161,7 +211,7 @@ public class PortalAdminServiceImpl implements PortalAdminService { dataAccessService.deleteDomainObjects(PortalAdminUserRole.class, "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null); transaction.commit(); - result = true; + result = deletePortalAdminInExternalCentralAuth(userId, PortalConstants.PORTAL_ADMIN_ROLE); } catch (Exception e) { EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e); logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); @@ -177,6 +227,40 @@ public class PortalAdminServiceImpl implements PortalAdminService { return fieldsValidator; } + + @SuppressWarnings("unchecked") + private boolean deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole){ + boolean result = false; + try{ + String name = ""; + List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where user_id = " + userId, + null, null); + if (EPCommonSystemProperties.containsProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = localUserList.get(0).getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID); + String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_"); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> addUserRole = new HttpEntity<>(headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/"+name+"/"+extRole, + HttpMethod.DELETE, addUserRole, String.class); + result = true; + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found", e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e); + result = false; + } + } + return result; + } + private void logQuery(String sql) { logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java index 1b1b6069..b222d189 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java @@ -108,7 +108,7 @@ public class SharedContextServiceImpl implements SharedContextService { * (non-Javadoc) * * @see org.openecomp.portalsdk.core.service.SharedContextService# - * saveSharedContext(com. att.fusion.core.domain.SharedContext) + * saveSharedContext(org.openecomp.portalapp.portal.domain.SharedContext) */ @Override public void saveSharedContext(SharedContext context) { @@ -119,7 +119,7 @@ public class SharedContextServiceImpl implements SharedContextService { * (non-Javadoc) * * @see org.openecomp.portalsdk.core.service.SharedContextService# - * deleteSharedContext(com. att.fusion.core.domain.SharedContext) + * deleteSharedContext(org.openecomp.portalapp.portal.domain.SharedContext) */ @Override public void deleteSharedContext(SharedContext context) { 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..1315c5e9 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<Long, EPRole> rolesMap = new HashMap<Long, EPRole>(); - 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<EPRole> roles = localSession @@ -274,19 +289,27 @@ public class UserRolesCommonServiceImpl { List<EPRole> 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(); - } } @@ -523,32 +546,7 @@ 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(); - + externalAccessRolesService.deleteRoleDependeciesRecord(localSession, roleId); logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); localSession.delete(role); logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); @@ -571,6 +569,10 @@ public class UserRolesCommonServiceImpl { } } + + + + /** * Called when updating the list of roles for the user * @@ -691,8 +693,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 +761,67 @@ 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 + * @throws Exception + */ + private void addRemoteUser(List<RoleInAppForUser> 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; + } + } + } + + /** + * 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 +846,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<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, applicationsRestClientService, appId, userId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); - - } else {// remote app + List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles; + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList); + 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<EcompRole> 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) { + addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } - } - if (remoteAppUser != null) { - Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, appId, userId); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, - userRolesInRemoteApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + if (remoteAppUser != null) { + Set<EcompRole> 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 +913,147 @@ public class UserRolesCommonServiceImpl { } return result; } - + + @SuppressWarnings("unchecked") + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser) + { + try{ + //check if user exists + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", orgUserId); + List<EPUser> userInfo = checkIfUserExists(userParams); + if (userInfo.size() == 0 || userInfo.isEmpty()) { + createLocalUserIfNecessary(orgUserId); + } + final Map<String, String> loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", orgUserId); + EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0); + 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<String> getUserRolesEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity<String> 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, "Connected to external system and received user roles: ", getResponse.getBody()); + + } + List<ExternalAccessUserRoleDetail> 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); + } + + } + } + } + for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) { + HttpEntity<String> entity = new HttpEntity<>(headers); + template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + userRole.getName(), HttpMethod.DELETE, entity, String.class); + } + final Map<String, RoleInAppForUser> roleInAppUserMap = new HashMap<>(); + for(RoleInAppForUser roleInAppUserNew: roleInAppUser){ + roleInAppUserMap.put(roleInAppUserNew.getRoleName(), roleInAppUserNew); + } + final Map<String, Long> params = new HashMap<>(); + params.put("appId", app.getId()); + params.put("userId", user.getId()); + List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", params, null); + // Check if incoming request has sys admin or account admin, if exists add in external system + if (!roleInAppUser.isEmpty()) { + for (EcompUserAppRoles userApp : userAppList) { + if ((userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID) + || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !roleInAppUserMap.containsKey(userApp.getRoleName())) { + RoleInAppForUser addSpecialRole = new RoleInAppForUser(); + addSpecialRole.setIsApplied(true); + addSpecialRole.setRoleId(userApp.getRoleId()); + addSpecialRole.setRoleName(userApp.getRoleName()); + roleInAppUser.add(addSpecialRole); + } + } + } + List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct().collect(Collectors.toList()); + for (RoleInAppForUser addRole : roleInAppUserNonDupls) { + ExternalAccessUser extUser = null; + if ((addRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) + && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + try{ + String extRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ","_"); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity<String> getRoleResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"+extRole, + HttpMethod.GET, entity, String.class); + String extAdminRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + if(getRoleResponse.getBody().equals("{}")){ + String addDesc = "{\"name\":\"" +extAdminRole+ "\"}"; + HttpEntity<String> roleEntity = new HttpEntity<>(addDesc,headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, roleEntity, String.class); + } + extUser = new ExternalAccessUser(name, + app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_")); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add admin role for application {} ",app.getId(),e); + continue; + } + } else { + extUser = new ExternalAccessUser(name, + app.getNameSpace() + "." + addRole.getRoleName().replaceAll(" ", "_")); + } + // Assign user role for an application in external access system + String userRole = mapper.writeValueAsString(extUser); + HttpEntity<String> entity = new HttpEntity<>(userRole, headers); + if (addRole.getIsApplied()) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system and adding user role", + addRole.getRoleName()); + ResponseEntity<String> addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and added user role", + getResponse.getBody(), addRole.getRoleName()); + if (addResponse.getStatusCode().value() != 201) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Connected to external system unable to save user role", getResponse.getBody(), + addRole.getRoleName()); + throw new Exception("Failed to add user role for application"); + } + } + } + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user role for application {}", app.getId(),e); + } + + } + /** * * @param userId @@ -1066,60 +1270,86 @@ public class UserRolesCommonServiceImpl { .executeNamedQuery("userAppRolesRequestList", params, null); epRequestIdSize = epRequestId.size(); } - if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + 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<RoleInAppForUser> 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<EcompUserAppRoles> userRoleList = null; + if(userId != null){ + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("userId", userId.getId()); + appParams.put("appId", app.getId()); + userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null); + } + 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 (!(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && checkIfAdminRoleExists + && (roleInAppForUserList.size() == 1 || reqType.equals("DELETE")))) { + 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, "Failed to added remote user", e); + throw new Exception(reqMessage); + } Set<EcompRole> 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<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles; + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList); + logger.info(EELFLoggerDelegate.debugLogger, "{} 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<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, app.getId(), orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), + userRolesInLocalApp); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); } else {// remote app + + 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; - } + addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService); reqMessage = "Saved Successfully"; } - if (remoteAppUser != null) { + if (remoteAppUser != null) { Set<EcompRole> 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, "{} 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 +1359,19 @@ public class UserRolesCommonServiceImpl { remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService); }*/ + } + } else { + if(!(reqType.equals("DELETE") && userId == null)){ + reqMessage = "Saved Successfully"; + } + Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList); + 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); } if(!result){ reqMessage = "Failed to save the user app role(s)"; @@ -1138,7 +1380,6 @@ 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", @@ -1268,23 +1509,16 @@ public class UserRolesCommonServiceImpl { * @see org.openecomp.portalapp.portal.service.UserRolesService# * getAppRolesForUser(java.lang.Long, java.lang.String) */ + @SuppressWarnings("unchecked") public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) { List<RoleInAppForUser> rolesInAppForUser = null; - List<EPUser> 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<String, String> userParams = new HashMap<>(); - userParams.put("orgUserIdValue", userId); - userInfo = checkIfUserExists(userParams); - if(userInfo.size() == 0 || userInfo.isEmpty()) - { - createLocalUserIfNecessary(userId); - } - List<Role> roleList = roleService.getAvailableRoles(); + List<Role> roleList = roleService.getAvailableRoles(userId); List<Role> activeRoleList = new ArrayList<Role>(); for(Role role: roleList) { if(role.getActive()) { @@ -1296,28 +1530,66 @@ public class UserRolesCommonServiceImpl { } } - - EPApp app = appsService.getApp(appId); - EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); - Set<EPRole> 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<EPRole> 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<EcompRole> roles = new ArrayList<>(); + if(app.getCentralAuth()){ + List<EPRole> 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<String, String> params = new HashMap<>(); + final Map<String, Long> userParams = new HashMap<>(); + params.put("orgUserIdValue", userId); + List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null); + userParams.put("appId", app.getId()); + userParams.put("userId", user.get(0).getId()); + List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null); + List<EcompRole> 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 +1662,7 @@ public class UserRolesCommonServiceImpl { public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) { FieldsValidator fieldsValidator = new FieldsValidator(); final Map<String, Long> 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 +1681,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"); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java index d7685627..1fead505 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java @@ -49,8 +49,8 @@ public class WidgetParameterServiceImpl implements WidgetParameterService{ List<Criterion> restrictionsList = new ArrayList<Criterion>(); Criterion widgetIdCrit = Restrictions.eq("widgetId", widgetId); restrictionsList.add(widgetIdCrit); - Criterion attIdCrit = Restrictions.eq("userId", userId); - restrictionsList.add(attIdCrit); + Criterion userIdCrit = Restrictions.eq("userId", userId); + restrictionsList.add(userIdCrit); Criterion paramIdCrit = Restrictions.eq("paramId", paramId); restrictionsList.add(paramIdCrit); |