X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=ecomp-portal-BE-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fportalapp%2Fportal%2Fservice%2FExternalAccessRolesServiceImpl.java;h=c528e55e7290ff1e2ef6cd51a7bc34961ce5a5e1;hb=1c3cc6fb0e4d2f4f2278240ff0387596c776b9c9;hp=39bd92d67b3eaf2792653b7210ce94f9435f24d9;hpb=f59a56b7c12badbb41bb2155b6de47e9c9c48bcd;p=portal.git diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java index 39bd92d6..c528e55e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -33,7 +33,7 @@ * * ============LICENSE_END============================================ * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * */ package org.onap.portalapp.portal.service; @@ -42,7 +42,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -53,7 +52,6 @@ import java.util.stream.Collectors; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; -import org.apache.commons.lang.StringUtils; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -70,6 +68,7 @@ import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EPUserApp; import org.onap.portalapp.portal.domain.ExternalRoleDetails; +import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem; import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException; import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException; import org.onap.portalapp.portal.exceptions.InactiveApplicationException; @@ -89,14 +88,15 @@ import org.onap.portalapp.portal.transport.CentralUserApp; import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.CentralV2User; import org.onap.portalapp.portal.transport.CentralV2UserApp; +import org.onap.portalapp.portal.transport.CentralizedAppRoles; import org.onap.portalapp.portal.transport.EcompUserRoles; import org.onap.portalapp.portal.transport.ExternalAccessPerms; import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail; import org.onap.portalapp.portal.transport.ExternalAccessRole; import org.onap.portalapp.portal.transport.ExternalAccessRolePerms; import org.onap.portalapp.portal.transport.ExternalAccessUser; +import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail; import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; -import org.onap.portalapp.portal.transport.ExternalRoleDescription; import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction; import org.onap.portalapp.portal.transport.LocalRole; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; @@ -107,6 +107,7 @@ import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.restful.domain.EcompRoleFunction; import org.onap.portalsdk.core.restful.domain.EcompUser; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; @@ -153,8 +154,6 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic private static final String FUNCTION_PIPE = "|"; - private static final String IS_NULL_STRING = "null"; - private static final String EXTERNAL_AUTH_PERMS = "perms"; private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description"; @@ -163,18 +162,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system"; - private static final String APP_ROLE_ID = "appRoleId"; - private static final String APP_ID = "appId"; - private static final String PRIORITY = "priority"; - - private static final String ACTIVE = "active"; - private static final String ROLE_NAME = "name"; - private static final String ID = "id"; - private static final String APP_ID_EQUALS = " app_id = "; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class); @@ -311,12 +302,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic * @throws Exception * If updateRoleInExternalSystem fails we catch it in logger for detail message */ - @SuppressWarnings("unchecked") private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception { boolean response = false; ObjectMapper mapper = new ObjectMapper(); ResponseEntity deleteResponse = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); List epRoleList = null; if (app.getId().equals(PortalConstants.PORTAL_APP_ID) || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { @@ -324,7 +313,6 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } else { epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app); } - // Assigning functions to global role if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { List globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); @@ -356,86 +344,29 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance() .constructCollectionType(List.class, ExternalAccessPerms.class)); } - ExternalRoleDescription sysRoleList = mapper.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 isActiveValueChanged; - // check role active status - existingRoleActive = new Boolean(sysRoleList.getActive()); - isActiveValueChanged = existingRoleActive.equals(updateExtRole.getActive()); boolean isRoleNameChanged = false; - if (!sysRoleList.getName().equals(updateExtRole.getName())) { + if (!desc.equals(updateExtRole.getName())) { isRoleNameChanged = true; - Map delRoleKeyMapper = new HashMap<>(); - delRoleKeyMapper.put(ROLE_NAME, name); - String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper); - deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue); - if (deleteResponse.getStatusCode().value() != 200) { - logger.error(EELFLoggerDelegate.errorLogger, - "updateRoleInExternalSystem: Failed to delete role in external system due to {} ", - deleteResponse.getBody()); - throw new ExternalAuthSystemException(deleteResponse.getBody()); - } + deleteRoleInExtSystem(mapper, name); addRole(updateExtRole, app.getUebKey()); // add partner functions to the global role in External Auth System - if(!list.isEmpty() && isGlobalRole){ - addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole); + if (!list.isEmpty() && isGlobalRole) { + addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole); } - list.removeIf(perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())); - // if role name is changes please ignore the previous functions in External Auth and update with user requested functions - addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, - list); + list.removeIf( + perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())); + // if role name is changes please ignore the previous functions in External Auth + // and update with user requested functions + addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list); } - boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()), - String.valueOf(updateExtRole.getPriority())); - ExternalAccessRole updateRole = new ExternalAccessRole(); - if (!isActiveValueChanged || !checkPriorityStatus || sysRoleList.getId().equals(IS_NULL_STRING) - || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) { - String updateDesc = ""; - List getRole; - final Map getAppRoleByName = new HashMap<>(); - getAppRoleByName.put(APP_ROLE_NAME_PARAM, updateExtRole.getName()); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - getRole = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getAppRoleByName, - null); - } else { - getAppRoleByName.put("appId", String.valueOf(app.getId())); - getRole = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, - getAppRoleByName, null); - } - Map extSystemUpdateRoleJsonMapper = new LinkedHashMap<>(); - extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId())); - extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName())); - extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive())); - extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority())); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - extSystemUpdateRoleJsonMapper.put(APP_ID, "null"); - extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null"); - } else { - extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId())); - extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, - String.valueOf(getRole.get(0).getAppRoleId())); - - } - updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper); - updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - updateRole.setDescription(updateDesc); - String updateRoleDesc = mapper.writeValueAsString(updateRole); - HttpEntity entity = new HttpEntity<>(updateRoleDesc, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for PUT: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleDesc); - ResponseEntity updatePermsResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role", - HttpMethod.PUT, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "updateRoleInExternalSystem: Finished updating in External Auth system {} and status code: {} ", - updateRoleDesc, updatePermsResponse.getStatusCode().value()); + // Delete role in External System if role is inactive + if (!updateExtRole.getActive()) { + deleteRoleInExtSystem(mapper, name); } - if(!isRoleNameChanged) { + if (!isRoleNameChanged) { response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list); } @@ -443,17 +374,41 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } else { // It seems like role exists in local DB but not in External // Access system - addRole(updateExtRole, app.getUebKey()); - List roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole); - response = true; - if (!roleFunctionListUpdate.isEmpty()) { - addRoleFunctionsInExternalSystem(updateExtRole, mapper, app); + if (updateExtRole.getActive()) { + addRole(updateExtRole, app.getUebKey()); + ExternalAccessRolePerms extAddRolePerms = null; + ExternalAccessPerms extAddPerms = null; + List roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (RoleFunction roleFunc : roleFunctionListAdd) { + extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(), + roleFunc.getCode(), roleFunc.getAction()); + extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, + app.getNameSpace() + "." + updateExtRole.getName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers); + } } } } return response; } + private void deleteRoleInExtSystem(ObjectMapper mapper, String name) + throws JsonProcessingException, Exception, ExternalAuthSystemException { + ResponseEntity deleteResponse; + Map delRoleKeyMapper = new HashMap<>(); + delRoleKeyMapper.put(ROLE_NAME, name); + String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper); + deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue); + if (deleteResponse.getStatusCode().value() != 200) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateRoleInExternalSystem: Failed to delete role in external system due to {} ", + deleteResponse.getBody()); + throw new ExternalAuthSystemException(deleteResponse.getBody()); + } + } + private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper, List roleFunctionListNew, String name, List list) throws Exception { boolean response; @@ -697,54 +652,23 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } - /** - * - * It adds functions to the role in external auth system - * - * @param updateExtRole - * @param addPermsMapper - * @param app - * @return true if success else false - * @throws Exception - */ - private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app) - throws Exception { - boolean response = false; - ExternalAccessRolePerms extAddRolePerms = null; - ExternalAccessPerms extAddPerms = null; - List roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - for (RoleFunction roleFunc : roleFunctionListAdd) { - String code = ""; - String type= ""; - String action = ""; - if (roleFunc.getCode().contains(FUNCTION_PIPE)) { - code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - type = getFunctionCodeType(roleFunc.getCode()); - action = getFunctionCodeAction(roleFunc.getCode()); - } else { - code = roleFunc.getCode(); - type = roleFunc.getCode().contains("menu") ? "menu" : "url"; - action = "*"; - } - extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action); - extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, - app.getNameSpace() + "." + updateExtRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); - HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity 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, - "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}", - addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); - } else { - response = true; - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value()); - } + private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms, + HttpHeaders headers) throws JsonProcessingException { + boolean response; + String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) { + response = false; + logger.debug(EELFLoggerDelegate.debugLogger, + "addRoleFunctionsInExternalSystem: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}", + addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value()); } return response; } @@ -819,17 +743,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ObjectMapper mapper = new ObjectMapper(); String addNewRole = ""; ExternalAccessRole extRole = new ExternalAccessRole(); - String addDesc = null; - Map extSystemJsonMapper = new LinkedHashMap<>(); - extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId())); - extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName())); - extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive())); - extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority())); - extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId())); - extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId())); - addDesc = mapper.writeValueAsString(extSystemJsonMapper); extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - extRole.setDescription(addDesc); + extRole.setDescription(String.valueOf(newRole.get(0).getName())); addNewRole = mapper.writeValueAsString(extRole); HttpEntity postEntity = new HttpEntity<>(addNewRole, headers); logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole); @@ -863,23 +778,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ObjectMapper mapper = new ObjectMapper(); String addNewRole = ""; ExternalAccessRole extRole = new ExternalAccessRole(); - List role = null; - String addDesc = null; - Map extSystemUpdateRole = new LinkedHashMap<>(); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - role = getPortalAppRoleInfo(addRole.getId()); - } else { - role = getPartnerAppRoleInfo(addRole.getId(), app); - } - extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId())); - extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName())); - extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive())); - extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority())); - extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId())); - extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId())); - addDesc = mapper.writeValueAsString(extSystemUpdateRole); extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - extRole.setDescription(addDesc); + extRole.setDescription(String.valueOf(addRole.getName())); addNewRole = mapper.writeValueAsString(extRole); return addNewRole; } @@ -894,7 +794,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic */ @SuppressWarnings("unchecked") @Transactional(rollbackFor = Exception.class) - private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { + public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { boolean result = false; EPRole epRole = null; Set roleFunctionList = addRoleInDB.getRoleFunctions(); @@ -941,6 +841,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { addNewRoleInExternalSystem(getRoleCreated, app); } + result = true; } else { // if role already exists then update it EPRole globalRole = null; List applicationRoles; @@ -1269,13 +1170,11 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic */ @SuppressWarnings("unchecked") private CentralV2User createEPUser(EPUser userInfo, Set userAppSet, EPApp app) throws Exception { - final Map params = new HashMap<>(); CentralV2User userAppList = new CentralV2User(); CentralV2User user1 = null; final Map params1 = new HashMap<>(); List globalRoleList = new ArrayList<>(); - try { if (app.getId() != PortalConstants.PORTAL_APP_ID) { params1.put("userId", userInfo.getId()); @@ -1324,8 +1223,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic SortedSet roleFunctionSet = new TreeSet<>(); for (CentralV2RoleFunction roleFunc : appRoleFunctionList) { String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + String type = getFunctionCodeType(roleFunc.getCode()); + String action = getFunctionCodeAction(roleFunc.getCode()); CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(), - functionCode, roleFunc.getName(), null, null); + functionCode, roleFunc.getName(), null, type, action, null); roleFunctionSet.add(cenRoleFunc); } Long userRoleId = null; @@ -1504,7 +1405,12 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic return roleFunc; roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction); } else { - roleFunc = getRoleFuncList.get(0); + // Check even if single record have pipes + if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) { + roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0)); + } else { + roleFunc = getRoleFuncList.get(0); + } } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e); @@ -1785,7 +1691,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName() .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}"; deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); - if (deleteResponse.getStatusCode().value() != 200 || deleteResponse.getStatusCode().value() != 404) { + if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) { EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode()); logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ", @@ -2194,7 +2100,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (extPerms.getJSONObject(i).has("description")) { description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); } else { - description = extPerms.getJSONObject(i).getString("instance"); + description = extPerms.getJSONObject(i).getString("type")+"|"+extPerms.getJSONObject(i).getString("instance") + +"|"+extPerms.getJSONObject(i).getString("action"); } if (extPerms.getJSONObject(i).has("roles")) { ObjectMapper rolesListMapper = new ObjectMapper(); @@ -2345,7 +2252,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic roleParams.put(APP_ROLE_NAME_PARAM, role); List roleCreated = null; if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, + roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null); } else { roleParams.put("appId", String.valueOf(app.getId())); @@ -2410,6 +2317,35 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic addRoleInExternalSystem(role, app.get(0)); rolesListAdded++; } + if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + // Add Account Admin role in External AUTH System + try { + String addAccountAdminRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + addAccountAdminRole = mapper.writeValueAsString(extRole); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(addAccountAdminRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + rolesListAdded++; + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to create Account Admin role", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "bulkUploadRoles: Account Admin Role already exits but does not break functionality", + e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "bulkUploadRoles: Failed to create Account Admin role", e.getMessage()); + } + } + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e); throw e; @@ -2480,14 +2416,24 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic * @param app */ private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) { - String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + String type = ""; + String instance = ""; + String action = ""; + if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){ + type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd()); + instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd()); + action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd()); + } else{ + type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + instance = addRoleFunc.getFunctionCd(); + action = "*"; + } ExternalAccessRolePerms extRolePerms = null; ExternalAccessPerms extPerms = null; ObjectMapper mapper = new ObjectMapper(); try { HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - - extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action, addRoleFunc.getFunctionName()); extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); @@ -2507,16 +2453,73 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } + @SuppressWarnings("unchecked") @Override - public void bulkUploadPartnerFunctions(String uebkey, List roleFunctionsList) throws Exception { + public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); - CentralV2RoleFunction cenRoleFunc = null; - for (RoleFunction roleFunction : roleFunctionsList) { - cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName()); - addRoleFunctionInExternalSystem(cenRoleFunc, app); + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + List roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params, + null); + Integer functionsAdded = 0; + try { + for (CentralV2RoleFunction roleFunc : roleFuncList) { + addFunctionInExternalSystem(roleFunc, app); + functionsAdded++; + } + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e); } + return functionsAdded; } + private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String type = ""; + String instance = ""; + String action = ""; + if ((roleFunc.getCode().contains(FUNCTION_PIPE)) + || (roleFunc.getType() != null && roleFunc.getAction() != null)) { + type = EcompPortalUtils.getFunctionType(roleFunc.getCode()); + instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + action = EcompPortalUtils.getFunctionAction(roleFunc.getCode()); + } else { + type = roleFunc.getCode().contains("menu") ? "menu" : "url"; + instance = roleFunc.getCode(); + action = "*"; + } + try { + extPerms.setAction(action); + extPerms.setInstance(instance); + extPerms.setType(app.getNameSpace() + "." + type); + extPerms.setDescription(roleFunc.getName()); + String addFunction = mapper.writeValueAsString(extPerms); + HttpEntity entity = new HttpEntity<>(addFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); + ResponseEntity addPermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", + addPermResponse.getStatusCode().value(), addFunction); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to add function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e); + throw e; + } + } + @Override public void bulkUploadPartnerRoles(String uebkey, List roleList) throws Exception { EPApp app = getApp(uebkey).get(0); @@ -2527,47 +2530,80 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @SuppressWarnings("unchecked") @Override - public void bulkUploadPartnerRoleFunctions(String uebkey, List roleList) throws Exception { + public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - for (Role role : roleList) { - try { - Set roleFunctionList = role.getRoleFunctions(); - List roleFunctionListNew = new ArrayList<>(); - ObjectMapper roleFunctionsMapper = new ObjectMapper(); - Iterator itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); - RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class); - roleFunctionListNew.add(roleFunction); - } - List 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(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String updateRolePerms = mapper.writeValueAsString(extRolePerms); - HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/perm", HttpMethod.PUT, entity, String.class); + List roles = getAppRoles(app.getId()); + final Map params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions", + params, null); + if (!appRoleFunc.isEmpty()) { + for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { + addRoleFunctionsInExternalSystem(addRoleFunc, role, app); + roleFunctions++; + } } - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, - "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality"); + } + // upload global role functions to ext auth system + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions); + } + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e); + } + return roleFunctions; + } + + @SuppressWarnings("unchecked") + private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception { + try { + EPApp portalApp = epAppService.getApp(1l); + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + List globalRoleFuncs = dataAccessService + .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null); + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) { + ExternalAccessRolePerms extRolePerms; + ExternalAccessPerms extPerms; + String type = ""; + String instance = ""; + String action = ""; + if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) { + type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd()); + instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd()); + action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd()); } else { - logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem", - e); + type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + instance = globalRoleFunc.getFunctionCd(); + action = "*"; } + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action); + extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + updateRoleFunctionInExternalSystem(updateRolePerms, entity); + roleFunctions++; } - + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to add role function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e); + throw e; } + return roleFunctions; } @Override @@ -2585,6 +2621,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app); logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList"); + //refactoring done List externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole); @@ -2598,7 +2635,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic applicationRolesList = getAppRoles(app.getId()); List applicationRoleIdList = new ArrayList<>(); for (EPRole applicationRole : applicationRolesList) { - applicationRoleIdList.add(applicationRole.getName()); + applicationRoleIdList.add(applicationRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); } List roleListToBeAddInEcompDB = new ArrayList<>(); @@ -2774,31 +2811,22 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ObjectMapper mapper, JSONArray extRole) throws IOException { List externalRoleDetailsList = new ArrayList<>(); - ExternalRoleDescription ApplicationRole = new ExternalRoleDescription(); - ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); + ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); List functionCodelist = new ArrayList<>(); + Map curRolesMap = getCurrentRolesInDB(app); 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(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { - ApplicationRole.setActive("true"); - ApplicationRole.setAppId(IS_NULL_STRING); - ApplicationRole.setPriority(IS_NULL_STRING); - ApplicationRole.setAppRoleId(IS_NULL_STRING); - String roleName = extRole.getJSONObject(i).getString(ROLE_NAME); - ApplicationRole.setName(roleName.substring(app.getNameSpace().length() + 1)); - } else { - String desc = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); - ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class); - } - + String name = extRole.getJSONObject(i).getString(ROLE_NAME); + String actualRoleName = name.substring(app.getNameSpace().length() + 1); SortedSet externalAccessPermsOfRole = new TreeSet<>(); if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) { JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS); for (int j = 0; j < extPerm.length(); j++) { JSONObject perms = extPerm.getJSONObject(j); - boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), app.getNameSpace()); + boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"), + app.getNameSpace()); if (isNamespaceMatching) { externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), perms.getString("instance"), perms.getString("action")); @@ -2809,46 +2837,33 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } - - if (ApplicationRole.getActive().equals(IS_NULL_STRING)) { - externalRoleDetail.setActive(false); - } else { - externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive())); - } - externalRoleDetail.setName(ApplicationRole.getName()); - - if (ApplicationRole.getAppId().equals(IS_NULL_STRING) && app.getId() == 1) { + externalRoleDetail.setActive(true); + externalRoleDetail.setName(actualRoleName); + if (app.getId() == 1) { externalRoleDetail.setAppId(null); - } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) { - externalRoleDetail.setAppId(app.getId()); } else { - externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId())); - } - - if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) { - externalRoleDetail.setPriority(null); - } else { - externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority())); - } - - if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) { - externalRoleDetail.setAppRoleId(null); + externalRoleDetail.setAppId(app.getId()); } - + // get role functions from DB + EPRole currRole = curRolesMap.get(actualRoleName + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + Long roleId = null; + if (currRole != null) + roleId = currRole.getId(); // get role functions from DB final Map roleFunctionsMap = new HashMap<>(); - if (!ApplicationRole.getId().equals(IS_NULL_STRING)) { - final Map appRoleFuncsParams = new HashMap<>(); + final Map appRoleFuncsParams = new HashMap<>(); + if (roleId != null) { appRoleFuncsParams.put("appId", app.getId()); - appRoleFuncsParams.put("roleId", Long.valueOf(ApplicationRole.getId())); - List appRoleFunctions = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null); + appRoleFuncsParams.put("roleId", roleId); + List appRoleFunctions = dataAccessService + .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null); if (!appRoleFunctions.isEmpty()) { for (EPAppRoleFunction roleFunc : appRoleFunctions) { roleFunctionsMap.put(roleFunc.getCode(), roleFunc); } } } - if (!externalAccessPermsOfRole.isEmpty()) { // Adding functions to role for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) { @@ -2860,22 +2875,24 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode); if (checkRoleFunctionPipeExits == null) { try { - final Map appFuncsParams = new HashMap<>(); + final Map appFuncsParams = new HashMap<>(); appFuncsParams.put("appId", String.valueOf(app.getId())); appFuncsParams.put("functionCd", externalpermission.getInstance()); logger.debug(EELFLoggerDelegate.debugLogger, "SyncApplicationRolesWithEcompDB: Adding function to the role: {}", externalpermission.getInstance()); List roleFunction = null; - roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null); + roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", + appFuncsParams, null); if (roleFunction.isEmpty()) { appFuncsParams.put("functionCd", funcCode); - roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null); + roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", + appFuncsParams, null); } if (!roleFunction.isEmpty()) { EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); apRoleFunction.setAppId(app.getId()); - apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); + apRoleFunction.setRoleId(roleId); apRoleFunction.setCode(roleFunction.get(0).getCode()); dataAccessService.saveDomainObject(apRoleFunction, null); } @@ -2934,6 +2951,9 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :", res); + if(res == null || res.trim().isEmpty()) + return null; + JSONObject jsonObj = new JSONObject(res); JSONArray extRole = jsonObj.getJSONArray("userRole"); @@ -2949,7 +2969,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic */ private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { EPRole role = new EPRole(); - role.setActive(externalRoleDetails.isActive()); + role.setActive(true); role.setAppId(externalRoleDetails.getAppId()); role.setAppRoleId(externalRoleDetails.getAppRoleId()); role.setName(externalRoleDetails.getName()); @@ -3080,79 +3100,116 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @Override public List getMenuFunctionsList(String uebkey) throws Exception { List appMenuFunctionsList = null; + List appMenuFunctionsFinalList = new ArrayList<>(); try { EPApp app = getApp(uebkey).get(0); final Map appParams = new HashMap<>(); appParams.put(APP_ID, app.getId()); appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null); + for(String appMenuFunction : appMenuFunctionsList) { + if(appMenuFunction.contains(FUNCTION_PIPE)) { + appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction)); + } else { + appMenuFunctionsFinalList.add(appMenuFunction); + } + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e); - return appMenuFunctionsList; + return appMenuFunctionsFinalList; } - return appMenuFunctionsList; + return appMenuFunctionsFinalList; } @SuppressWarnings({ "unchecked"}) @Override public List getAllAppUsers(String uebkey) throws Exception { List usersList = new ArrayList<>(); - List usersfinalList = new ArrayList<>(); - try { - EPApp app = getApp(uebkey).get(0); - final Map appParams = new HashMap<>(); - appParams.put("appId", app.getId()); - List userList = (List) dataAccessService - .executeNamedQuery("ApplicationUserRoles", appParams, null); - for (EcompUserRoles ecompUserRole : userList) { - boolean found = false; - Set roles = null; - for (EcompUser user : usersfinalList) { - if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(ecompUserRole.getRoleId()); - ecompRole.setName(ecompUserRole.getRoleName()); - roles = user.getRoles(); - roles.add(ecompRole); - user.setRoles(roles); - found = true; - break; - } - } - - if (!found) { - EcompUser epUser = new EcompUser(); - epUser.setOrgId(ecompUserRole.getOrgId()); - epUser.setManagerId(ecompUserRole.getManagerId()); - epUser.setFirstName(ecompUserRole.getFirstName()); - epUser.setLastName(ecompUserRole.getLastName()); - epUser.setPhone(ecompUserRole.getPhone()); - epUser.setEmail(ecompUserRole.getEmail()); - epUser.setOrgUserId(ecompUserRole.getOrgUserId()); - epUser.setOrgCode(ecompUserRole.getOrgCode()); - epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId()); - epUser.setJobTitle(ecompUserRole.getJobTitle()); - epUser.setLoginId(ecompUserRole.getLoginId()); - epUser.setActive(true); - roles = new HashSet<>(); - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(ecompUserRole.getRoleId()); - ecompRole.setName(ecompUserRole.getRoleName()); - roles.add(ecompRole); - epUser.setRoles(roles); - usersfinalList.add(epUser); - } - } - ObjectMapper mapper = new ObjectMapper(); + List usersfinalList = new ArrayList<>(); + try { + EPApp app = getApp(uebkey).get(0); + final Map appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + List userList = (List) dataAccessService + .executeNamedQuery("ApplicationUserRoles", appParams, null); + for (EcompUserRoles ecompUserRole : userList) { + boolean found = false; + Set roles = null; + for (EcompUser user : usersfinalList) { + if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(ecompUserRole.getRoleId()); + ecompRole.setName(ecompUserRole.getRoleName()); + roles = user.getRoles(); + EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny() + .orElse(null); + SortedSet roleFunctionSet = new TreeSet<>(); + if(role != null) + { + roleFunctionSet = (SortedSet) role.getRoleFunctions(); + } + + String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode()); + functionCode = EPUserUtils.decodeFunctionCode(functionCode); + EcompRoleFunction epRoleFunction = new EcompRoleFunction(); + epRoleFunction.setName(ecompUserRole.getFunctionName()); + epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode)); + epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode())); + epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode())); + roleFunctionSet.add(epRoleFunction); + ecompRole.setRoleFunctions(roleFunctionSet); + roles.add(ecompRole); + user.setRoles(roles); + found = true; + break; + } + } + + if (!found) { + EcompUser epUser = new EcompUser(); + epUser.setOrgId(ecompUserRole.getOrgId()); + epUser.setManagerId(ecompUserRole.getManagerId()); + epUser.setFirstName(ecompUserRole.getFirstName()); + epUser.setLastName(ecompUserRole.getLastName()); + epUser.setPhone(ecompUserRole.getPhone()); + epUser.setEmail(ecompUserRole.getEmail()); + epUser.setOrgUserId(ecompUserRole.getOrgUserId()); + epUser.setOrgCode(ecompUserRole.getOrgCode()); + epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId()); + epUser.setJobTitle(ecompUserRole.getJobTitle()); + epUser.setLoginId(ecompUserRole.getLoginId()); + epUser.setActive(true); + roles = new HashSet<>(); + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(ecompUserRole.getRoleId()); + ecompRole.setName(ecompUserRole.getRoleName()); + SortedSet roleFunctionSet = new TreeSet<>(); + + String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode()); + functionCode = EPUserUtils.decodeFunctionCode(functionCode); + EcompRoleFunction epRoleFunction = new EcompRoleFunction(); + epRoleFunction.setName(ecompUserRole.getFunctionName()); + epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode)); + epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode())); + epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode())); + roleFunctionSet.add(epRoleFunction); + ecompRole.setRoleFunctions(roleFunctionSet); + roles.add(ecompRole); + epUser.setRoles(roles); + usersfinalList.add(epUser); + } + } + ObjectMapper mapper = new ObjectMapper(); + + for (EcompUser u1 : usersfinalList) { + String str = mapper.writeValueAsString(u1); + usersList.add(str); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e); + throw e; + } + return usersfinalList; - for (EcompUser u1 : usersfinalList) { - String str = mapper.writeValueAsString(u1); - usersList.add(str); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e); - throw e; - } - return usersfinalList; } @@ -3304,10 +3361,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } @Override - public List convertCentralRoleFunctionToRoleFunctionObject(List answer) { - List addRoleFuncList = new ArrayList<>(); + public List convertCentralRoleFunctionToRoleFunctionObject(List answer) { + List addRoleFuncList = new ArrayList<>(); for(CentralV2RoleFunction cenRoleFunc : answer){ - RoleFunction setRoleFunc = new RoleFunction(); + CentralRoleFunction setRoleFunc = new CentralRoleFunction(); setRoleFunc.setCode(cenRoleFunc.getCode()); setRoleFunc.setName(cenRoleFunc.getName()); addRoleFuncList.add(setRoleFunc); @@ -3324,6 +3381,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e); + throw e; } return sendUserRoles; } @@ -3367,7 +3425,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName()); cenRoleFunction.add(cenRoleFunc); } - CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(), + CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction); cua.setRole(role); userApps.add(cua); @@ -3393,13 +3451,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @Override public List convertV2CentralRoleListToOldVerisonCentralRoleList(List v2CenRoleList) { List cenRoleList = new ArrayList<>(); - SortedSet cenRoleFuncList = new TreeSet<>(); for(CentralV2Role v2CenRole : v2CenRoleList){ + SortedSet cenRoleFuncList = new TreeSet<>(); for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){ CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); cenRoleFuncList.add(roleFunc); } - CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList); + CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList); cenRoleList.add(role); } return cenRoleList; @@ -3435,7 +3493,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); cenRoleFuncList.add(roleFunc); } - return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), + return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList); } @@ -3474,4 +3532,207 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes())); return encodedString; } + + @Override + public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try { + ExternalAccessRolePerms extRolePerms; + ExternalAccessPerms extPerms; + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction()); + String appNameSpace = ""; + if(data.getIsGlobalRolePartnerFunc()) { + appNameSpace = epAppService.getApp(1l).getNameSpace(); + } else { + appNameSpace = app.getNameSpace(); + } + extRolePerms = new ExternalAccessRolePerms(extPerms, + appNameSpace + "." + + data.getRoleName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + updateRoleFunctionInExternalSystem(updateRolePerms, entity); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to add role function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e); + throw e; + } + + } + + private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity entity) { + logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity addPermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ", + addPermResponse.getStatusCode().value(), updateRolePerms); + } + + @Override + public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception { + String name = ""; + if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity getUserRolesEntity = new HttpEntity<>(headers); + ResponseEntity getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + List userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj = null; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + updateUserRolesInLocal(userRoleDetailList, extRoles, loginId); + } + + @SuppressWarnings("unchecked") + private void updateUserRolesInLocal(List userRoleDetailList, JSONArray extRoles, + String loginId) throws InvalidUserException { + HashMap userParams = new HashMap<>(); + userParams.put("orgUserId", loginId); + // Get all centralized applications existing user roles from local + List currentUserAppRoles = dataAccessService + .executeNamedQuery("getUserCentralizedAppRoles", userParams, null); + EPUser user = getUser(loginId).get(0); + // Get all centralized applications roles from local + HashMap cenAppRolesMap = getCentralizedAppRoleList(); + HashMap currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles( + currentUserAppRoles); + // Get all centralized applications + admin role from local + HashMap centralisedAppsMap = getCentralizedAdminAppsInfo(); + if (extRoles != null) { + ExternalAccessUserRoleDetail userRoleDetail = null; + for (int i = 0; i < extRoles.length(); i++) { + if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN) + && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) { + userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), + null); + userRoleDetailList.add(userRoleDetail); + } + } + addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap, + centralisedAppsMap); + } + } + + private void addUserRolesInLocal(List userRoleDetailList, EPUser user, + HashMap cenAppRolesMap, + HashMap currentCentralizedUserAppRolesMap, + HashMap centralisedAppsMap) { + for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) { + try { + // check if user already has role in local + if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) { + CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName()); + if (getCenAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}", + extUserRoleDetail.toString()); + EPUserApp userApp = new EPUserApp(); + EPApp app = new EPApp(); + app.setId(getCenAppRole.getAppId()); + EPRole epRole = new EPRole(); + epRole.setId(getCenAppRole.getRoleId()); + userApp.setApp(app); + userApp.setUserId(user.getId()); + userApp.setRole(epRole); + dataAccessService.saveDomainObject(userApp, null); + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}", + extUserRoleDetail.toString()); + } else if (getCenAppRole == null // check if user has app account admin role + && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) { + EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName()); + if (app != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}", + extUserRoleDetail.toString()); + EPUserApp userApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + userApp.setApp(app); + userApp.setUserId(user.getId()); + userApp.setRole(epRole); + dataAccessService.saveDomainObject(userApp, null); + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}", + extUserRoleDetail.toString()); + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addUserRolesInLocal - Failed to update user role in local from external auth system {} ", + extUserRoleDetail.toString(), e); + } + } + } + + @SuppressWarnings("unchecked") + private HashMap getCentralizedAdminAppsInfo() { + List centralizedApps = dataAccessService + .executeNamedQuery("getCentralizedApps", null, null); + HashMap centralisedAppsMap = new HashMap<>(); + for (EPApp cenApp : centralizedApps) { + centralisedAppsMap.put(cenApp.getNameSpace()+ "." + + PortalConstants.ADMIN_ROLE.replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp); + } + return centralisedAppsMap; + } + + private HashMap getCurrentUserCentralizedAppRoles( + List currentUserAppRoles) { + HashMap currentCentralizedUserAppRolesMap = new HashMap<>(); + for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) { + currentCentralizedUserAppRolesMap.put( + cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + cenAppUserRole); + } + return currentCentralizedUserAppRolesMap; + } + + @SuppressWarnings("unchecked") + private HashMap getCentralizedAppRoleList() { + List centralizedAppRoles = dataAccessService + .executeNamedQuery("getAllCentralizedAppsRoles", null, null); + HashMap cenAppRolesMap = new HashMap<>(); + for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) { + cenAppRolesMap.put( + CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + CentralizedAppRole); + } + return cenAppRolesMap; + } + + @Override + public ResponseEntity getUserRolesFromExtAuthSystem(String name, HttpEntity getUserRolesEntity) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if (getResponse.getStatusCode().value() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}", + getResponse.getBody()); + + }else{ + logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() ); + EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode()); + } + return getResponse; + } + }