From 7929b78e2d59904a847f4498242a55096eb2dac8 Mon Sep 17 00:00:00 2001 From: Dominik Mizyn Date: Tue, 3 Mar 2020 15:39:09 +0100 Subject: [PATCH] RoleManageController up RoleManageController up and all needed services Issue-ID: PORTAL-710 Change-Id: I7e49aaf65d93f8c4b7df697f523d61e1a9358a7a Signed-off-by: Dominik Mizyn --- portal-BE/pom.xml | 6 + .../portal/controller/RoleManageController.java | 851 +++++++++++++++++++++ .../controller/RolesApprovalSystemController.java | 7 +- .../portal/domain/dto/transport/CentralV2Role.java | 72 +- .../portal/exception/DuplicateRecordException.java | 47 ++ .../exception/NonCentralizedAppException.java | 56 ++ .../org/onap/portal/service/AdminRolesService.java | 3 +- .../onap/portal/service/CentralizedAppService.java | 29 + .../portal/service/ExternalAccessRolesService.java | 65 +- 9 files changed, 1092 insertions(+), 44 deletions(-) create mode 100644 portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java create mode 100644 portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java create mode 100644 portal-BE/src/main/java/org/onap/portal/exception/NonCentralizedAppException.java create mode 100644 portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java diff --git a/portal-BE/pom.xml b/portal-BE/pom.xml index e00a9507..cda52df2 100644 --- a/portal-BE/pom.xml +++ b/portal-BE/pom.xml @@ -176,6 +176,12 @@ 2.10.0 compile + + org.onap.portal.sdk + epsdk-app-common + 2.6.0 + compile + portal diff --git a/portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java b/portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java new file mode 100644 index 00000000..dc4a575a --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java @@ -0,0 +1,851 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portal.controller; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import java.io.IOException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import javax.management.InvalidApplicationException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Valid; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.onap.portal.domain.db.ep.EpAppFunction; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.PortalRestResponse; +import org.onap.portal.domain.dto.PortalRestStatusEnum; +import org.onap.portal.domain.dto.ecomp.CentralizedApp; +import org.onap.portal.domain.dto.ecomp.EcompAuditLog; +import org.onap.portal.domain.dto.ecomp.UploadRoleFunctionExtSystem; +import org.onap.portal.domain.dto.transport.CentralV2Role; +import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator; +import org.onap.portal.exception.DuplicateRecordException; +import org.onap.portal.exception.InvalidRoleException; +import org.onap.portal.exception.NonCentralizedAppException; +import org.onap.portal.logging.aop.EPEELFLoggerAdvice; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.AdminRolesService; +import org.onap.portal.service.CentralizedAppService; +import org.onap.portal.service.ExternalAccessRolesService; +import org.onap.portal.service.app.FnAppService; +import org.onap.portal.service.user.FnUserService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portal.utils.PortalConstants; +import org.onap.portal.validation.SecureString; +import org.onap.portalapp.controller.core.RoleController; +import org.onap.portalapp.controller.core.RoleListController; +import org.onap.portalsdk.core.domain.AuditLog; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.AuditService; +import org.onap.portalsdk.core.service.AuditServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.JsonMessage; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +@RestController +@Configuration +public class RoleManageController { + + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + private static final String PIPE = "|"; + private static final String ROLE_INVALID_CHARS = "%=():,\"\""; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class); + + private RoleListController roleListController = new RoleListController(); + private RoleController roleController = new RoleController(); + private final AuditService auditService = new AuditServiceImpl(); + + private final CentralizedAppService centralizedAppService; + private final FnUserService fnUserService; + private final FnAppService fnAppService; + private final AdminRolesService adminRolesService; + private final ExternalAccessRolesService externalAccessRolesService; + + @Autowired + public RoleManageController(CentralizedAppService centralizedAppService, FnUserService fnUserService, + FnAppService fnAppService, + AdminRolesService adminRolesService, + ExternalAccessRolesService externalAccessRolesService) { + this.centralizedAppService = centralizedAppService; + this.fnUserService = fnUserService; + this.fnAppService = fnAppService; + this.adminRolesService = adminRolesService; + this.externalAccessRolesService = externalAccessRolesService; + } + + @RequestMapping(value = {"/portalApi/get_roles/{appId}"}, method = RequestMethod.GET) + public void getRoles(Principal principal, HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId) { + try { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + FnApp requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral()) { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + List answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()); + model.put("availableRoles", answer); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } else { + throw new NonCentralizedAppException(requestedApp.getAppName()); + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user"); + SendErrorForUnauthorizedUser(response, user); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e); + } + } + + @RequestMapping(value = {"/portalApi/role_list/toggleRole/{appId}/{roleId}"}, method = RequestMethod.POST) + public Map toggleRole(Principal principal, HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception { + FnApp requestedApp; + String restcallStatus; + HashMap responseMap = new HashMap<>(); + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + try { + requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey()); + boolean active = domainRole.isActive(); + domainRole.setActive(!active); + String result = mapper.writeValueAsString(domainRole); + Role newRole = externalAccessRolesService.convertCentralRoleToRole(result); + ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService + .saveRoleForApplication(newRole, requestedApp.getUebKey()); + boolean getAddResponse = externalRequestFieldsValidator.isResult(); + if (getAddResponse) { + restcallStatus = "Success"; + logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId()); + } else { + restcallStatus = "Toggle Role Failed"; + logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId()); + } + responseMap.put("restcallStatus", restcallStatus); + responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey())); + } else { + logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + responseMap.put("restcallStatus", " Unauthorized user"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e); + throw e; + } + return responseMap; + } + + @RequestMapping(value = {"/portalApi/role_list/removeRole/{appId}/{roleId}"}, method = RequestMethod.POST) + public Map removeRole(Principal principal, HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + FnApp requestedApp; + String restCallStatus; + HashMap responseMap = new HashMap<>(); + ExternalRequestFieldsValidator externalRequestFieldsValidator; + try { + requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral()) { + externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId, + requestedApp.getUebKey(), user.getOrgUserId()); + boolean deleteResponse = externalRequestFieldsValidator.isResult(); + if (deleteResponse) { + restCallStatus = "Success"; + FnUser requestedUser = (FnUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0); + FnApp app = (FnApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0); + logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}", + app.getId(), roleId); + String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE; + AuditLog auditLog = getAuditInfo(requestedUser, activityCode); + auditLog.setComments(EcompPortalUtils.truncateString( + "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'", + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole", + EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE, + String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), + roleId.toString())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } else { + restCallStatus = "Remove Role failed"; + responseMap.put("error", externalRequestFieldsValidator.getDetailMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed"); + } + responseMap.put("restCallStatus", restCallStatus); + responseMap.put("availableRoles", + externalAccessRolesService.getRolesForApp(requestedApp.getUebKey())); + } else { + throw new NonCentralizedAppException(requestedApp.getAppName()); + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + responseMap.put("restCallStatus", " Unauthorized user"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e); + throw e; + } + return responseMap; + } + + @RequestMapping(value = {"/portalApi/role/saveRole/{appId}"}, method = RequestMethod.POST) + public Map saveRole(Principal principal, HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + String responseString = null; + HashMap responseMap = new HashMap<>(); + try { + FnApp requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral().equals(true)) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class); + List childRoles = mapper.readValue(root.get("childRoles").toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class)); + List roleFunctions = mapper.readValue(root.get("roleFunctions").toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, + EpAppFunction.class)); + if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) { + throw new InvalidRoleException("Invalid role name found for '" + role.getName() + + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed"); + } + CentralV2Role domainRole; + if (role.getId() != null) { + domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey()); + domainRole.setName(role.getName()); + domainRole.setPriority(role.getPriority()); + } else { + List roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()); + for (CentralV2Role existRole : roles) { + if (existRole.getName().equalsIgnoreCase(role.getName())) { + throw new DuplicateRecordException("Role already exists: " + existRole.getName()); + } + } + domainRole = CentralV2Role.builder().build(); + domainRole.setName(role.getName()); + domainRole.setPriority(role.getPriority()); + domainRole.setActive(role.isActive()); + if (role.getChildRoles() != null && role.getChildRoles().size() > 0) { + for (Object childRole : childRoles) { + domainRole.addChildRole((CentralV2Role) childRole); + } + } + } + if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) { + domainRole.setRoleFunctions(new TreeSet<>()); + for (EpAppFunction roleFunction : roleFunctions) { + if (roleFunction.getType() == null && roleFunction.getAction() == null) { + throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType() + + " and action: " + roleFunction.getAction() + " found while saving!"); + } + if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getFunctionCd())) { + roleFunction.setFunctionCd(roleFunction.getType() + PIPE + + EcompPortalUtils.encodeFunctionCode(roleFunction.getFunctionCd()) + PIPE + + roleFunction.getAction()); + } else { + roleFunction + .setFunctionCd(roleFunction.getType() + PIPE + roleFunction.getFunctionCd() + PIPE + + roleFunction.getAction()); + } + domainRole.addRoleFunction(roleFunction); + } + } else { + domainRole.setRoleFunctions(new TreeSet<>()); + } + String result = mapper.writeValueAsString(domainRole); + Role newRole = externalAccessRolesService.convertCentralRoleToRole(result); + ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService + .saveRoleForApplication(newRole, requestedApp.getUebKey()); + boolean getAddResponse = externalRequestFieldsValidator.isResult(); + if (getAddResponse) { + String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE + : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION; + logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}", + requestedApp.getId(), role.getName()); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(activityCode); + auditLog.setComments(EcompPortalUtils.truncateString( + "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'", + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditLog.setAffectedRecordId(user.getOrgUserId()); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode, + String.valueOf(user.getId()), user.getOrgUserId(), role.getName())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + responseMap.put("status", "Success"); + responseMap.put("role", domainRole); + } else { + if (externalRequestFieldsValidator.getDetailMessage().contains("406")) { + externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName() + + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed"); + } + responseMap.put("status", "SaveRole Failed"); + responseMap.put("role", responseString); + responseMap.put("error", externalRequestFieldsValidator.getDetailMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed"); + } + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + responseMap.put("error", " Unauthorized user"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e); + responseMap.put("error", e.getMessage()); + } + return responseMap; + } + + @RequestMapping(value = {"/portalApi/role/removeRoleFunction"}, method = RequestMethod.POST) + public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return getRoleController().removeRoleFunction(request, response); + } + + @RequestMapping(value = {"/portalApi/role/addRoleFunction"}, method = RequestMethod.POST) + public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return getRoleController().addRoleFunction(request, response); + } + + @RequestMapping(value = {"/portalApi/role/removeChildRole"}, method = RequestMethod.POST) + public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + return getRoleController().removeChildRole(request, response); + } + + @RequestMapping(value = {"/portalApi/role/addChildRole"}, method = RequestMethod.POST) + public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + return getRoleController().addChildRole(request, response); + } + + @RequestMapping(value = {"/portalApi/get_role/{appId}/{roleId}"}, method = RequestMethod.GET) + public void getRole(Principal principal, HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, + @PathVariable("roleId") Long roleId) throws Exception { + try { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + ObjectMapper mapper = new ObjectMapper(); + FnApp requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral()) { + CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey()); + logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId); + Map model = new HashMap<>(); + model.put("availableRoleFunctions", mapper + .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey()))); + model.put("availableRoles", + mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId))); + model.put("role", mapper.writeValueAsString(answer)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } else { + throw new NonCentralizedAppException(requestedApp.getAppName()); + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.getRoleFunctionList, Unauthorized user"); + SendErrorForUnauthorizedUser(response, user); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e); + throw e; + } + } + + @RequestMapping(value = {"/portalApi/get_role_functions/{appId}"}, method = RequestMethod.GET) + public void getRoleFunctionList(Principal principal, HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId) throws Exception { + try { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + FnApp requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral()) { + List answer = null; + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey()); + model.put("availableRoleFunctions", answer); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } else { + throw new NonCentralizedAppException(requestedApp.getAppName()); + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.getRoleFunctionList, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + response.getWriter().write("Unauthorized User"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e); + throw e; + } + } + + @RequestMapping(value = {"/portalApi/role_function_list/saveRoleFunction/{appId}"}, method = RequestMethod.POST) + public PortalRestResponse saveRoleFunction(Principal principal, HttpServletRequest request, + HttpServletResponse response, @Valid @RequestBody EpAppFunction roleFunc, @PathVariable("appId") Long appId) { + if (roleFunc != null) { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(roleFunc); + + if (!constraintViolations.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR"); + } + } + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + boolean saveOrUpdateResponse; + try { + FnApp requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral() && roleFunc != null) { + String code = roleFunc.getType() + PIPE + roleFunc.getFunctionCd() + PIPE + roleFunc.getAction(); + EpAppFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code, + requestedApp.getUebKey()); + if (domainRoleFunction != null + && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) { + addIfTypeActionDoesNotExits(domainRoleFunction); + } + boolean isSave = true; + if (domainRoleFunction != null && domainRoleFunction.getFunctionCd() + .equals(roleFunc.getFunctionCd()) + && domainRoleFunction.getType().equals(roleFunc.getType()) + && domainRoleFunction.getAction().equals(roleFunc.getAction())) { + domainRoleFunction.setFunctionName(roleFunc.getFunctionName()); + saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction, + requestedApp); + isSave = false; + } else { + roleFunc.setAppId(requestedApp); + saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc, + requestedApp); + } + if (saveOrUpdateResponse) { + FnUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0); + FnApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0); + String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION + : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION; + logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode); + } + } else { + throw new NonCentralizedAppException(requestedApp.getAppName() + " is not Centralized Application"); + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure"); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success"); + } + + private void logExterlaAuthRoleFunctionActivity(String code, FnUser requestedUser, FnApp app, String activityCode) { + logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}", + app.getId(), code); + AuditLog auditLog = getAuditInfo(requestedUser, activityCode); + auditLog.setComments(EcompPortalUtils.truncateString( + "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'", + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode, + String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code)); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + + private void addIfTypeActionDoesNotExits(EpAppFunction domainRoleFunction) { + if (domainRoleFunction.getFunctionCd().contains(PIPE)) { + String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getFunctionCd()); + String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getFunctionCd()); + String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getFunctionCd()); + domainRoleFunction.setType(newfunctionTypeFormat); + domainRoleFunction.setAction(newfunctionActionFormat); + domainRoleFunction.setFunctionCd(newfunctionCodeFormat); + } else { + String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getFunctionCd()); + String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getFunctionCd()); + domainRoleFunction.setType(type); + domainRoleFunction.setAction(action); + } + } + + @RequestMapping(value = {"/portalApi/role_function_list/removeRoleFunction/{appId}"}, method = RequestMethod.POST) + public PortalRestResponse removeRoleFunction(Principal principal, + HttpServletRequest request, HttpServletResponse response, + @RequestBody String roleFunc, @PathVariable("appId") Long appId) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + if (roleFunc != null) { + SecureString secureString = new SecureString(roleFunc); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(secureString); + + if (!constraintViolations.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR"); + } + } + + try { + FnApp requestedApp = fnAppService.getById(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getAuthCentral()) { + ObjectMapper mapper = new ObjectMapper(); + boolean getDelFuncResponse; + EpAppFunction availableRoleFunction = mapper.readValue(roleFunc, EpAppFunction.class); + String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getFunctionCd() + PIPE + + availableRoleFunction.getAction(); + EpAppFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code, + requestedApp.getUebKey()); + getDelFuncResponse = externalAccessRolesService + .deleteCentralRoleFunction(domainRoleFunction.getFunctionCd(), requestedApp); + if (getDelFuncResponse) { + logger.info(EELFLoggerDelegate.applicationLogger, + "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(), + domainRoleFunction.getFunctionCd()); + String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION; + AuditLog auditLog = getAuditInfo(user, activityCode); + auditLog.setComments( + EcompPortalUtils.truncateString( + "Deleted function for app:" + requestedApp.getId() + " and function code:'" + + domainRoleFunction.getFunctionCd() + "'", + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction", + EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION, + String.valueOf(user.getId()), user.getOrgUserId(), + domainRoleFunction.getFunctionCd())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + logger.info(EELFLoggerDelegate.auditLogger, + "Remove role function " + domainRoleFunction.getFunctionName()); + } + } else { + throw new NonCentralizedAppException(requestedApp.getAppName() + " is not Centralized Application"); + } + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.removeRoleFunction, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure"); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success"); + } + + @RequestMapping(value = {"/portalApi/centralizedApps"}, method = RequestMethod.GET) + public List getCentralizedAppRoles(Principal principal, HttpServletRequest request, + HttpServletResponse response, + String userId) { + if (userId != null) { + SecureString secureString = new SecureString(userId); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set> constraintViolations = validator.validate(secureString); + + if (!constraintViolations.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed"); + return null; + } + } + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List applicationsList = null; + if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) || adminRolesService + .isSuperAdmin(user.getLoginId()) + || adminRolesService.isRoleAdmin(user.getId())) { + applicationsList = centralizedAppService.getCentralizedAppsOfUser(userId); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.getCentralizedAppRoles, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + } + return applicationsList; + } + + public List getCentralizedAppsOfUser(String userId) { + List centralizedAppsList = new ArrayList<>(); + try { + centralizedAppsList = centralizedAppService.getCentralizedAppsOfUser(userId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); + } + return centralizedAppsList; + } + + public RoleListController getRoleListController() { + return roleListController; + } + + public void setRoleListController(RoleListController roleListController) { + this.roleListController = roleListController; + } + + public RoleController getRoleController() { + return roleController; + } + + public void setRoleController(RoleController roleController) { + this.roleController = roleController; + } + + @RequestMapping(value = {"/portalApi/syncRoles"}, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse syncRoles(Principal principal, HttpServletRequest request, + HttpServletResponse response, + @RequestBody Long appId) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + try { + FnApp app = fnAppService.getById(appId); + if (isAuthorizedUser(user, app)) { + fieldsValidation(app); + externalAccessRolesService.syncApplicationRolesWithEcompDB(app); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : ""); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success"); + } + + @RequestMapping(value = {"/portalApi/syncFunctions"}, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse syncFunctions(Principal principal, HttpServletRequest request, + HttpServletResponse response, + @RequestBody Long appId) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + try { + FnApp app = fnAppService.getById(appId); + if (isAuthorizedUser(user, app)) { + fieldsValidation(app); + externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.syncFunctions, Unauthorized user:{}", + user != null ? user.getOrgUserId() : ""); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success"); + } + + public List getAvailableChildRoles(String uebKey, Long roleId) throws Exception { + List availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey); + if (roleId == null || roleId == 0) { + return availableChildRoles; + } + CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey); + Set allParentRoles = new TreeSet<>(); + getAllParentRolesAsList(currentRole, allParentRoles); + availableChildRoles + .removeIf(role -> !role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)); + return availableChildRoles; + } + + private void getAllParentRolesAsList(CentralV2Role role, Set allParentRoles) { + Set parentRoles = role.getParentRoles(); + allParentRoles.addAll(parentRoles); + for (CentralV2Role parentRole : parentRoles) { + getAllParentRolesAsList(parentRole, allParentRoles); + } + } + + public AuditLog getAuditInfo(FnUser user, String activityCode) { + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(activityCode); + auditLog.setAffectedRecordId(user.getOrgUserId()); + + return auditLog; + } + + private void fieldsValidation(FnApp app) throws Exception { + List appInfo = externalAccessRolesService.getApp(app.getUebKey()); + if (appInfo.isEmpty()) { + throw new InvalidApplicationException("Invalid credentials"); + } + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed() + && appInfo.get(0).getAuthCentral()) { + ResponseEntity response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0)); + if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND) { + throw new InvalidApplicationException("Invalid NameSpace"); + } + } + } + + private boolean isAuthorizedUser(FnUser user, FnApp requestedApp) { + return user != null && (adminRolesService.isAccountAdminOfApplication(user.getId(), requestedApp) + || (adminRolesService.isSuperAdmin(user.getLoginId()) && requestedApp.getId() + .equals(PortalConstants.PORTAL_APP_ID))); + } + + private void SendErrorForUnauthorizedUser(HttpServletResponse response, FnUser user) throws IOException { + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + response.getWriter().write("Unauthorized User"); + } + + @RequestMapping(value = { + "/portalApi/uploadRoleFunction/{appId}"}, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadRoleFunc(Principal principal, HttpServletRequest request, + HttpServletResponse response, + @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + try { + FnApp app = fnAppService.getById(appId); + if (isAuthorizedUser(user, app)) { + fieldsValidation(app); + externalAccessRolesService.bulkUploadRoleFunc(data, app); + String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION; + String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE + + data.getAction(); + logExterlaAuthRoleFunctionActivity(code, user, app, activityCode); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : ""); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success"); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java b/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java index 53bf7e11..3a54523c 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java @@ -48,7 +48,6 @@ import org.onap.portal.domain.dto.model.ExternalSystemRoleApproval; import org.onap.portal.domain.dto.model.ExternalSystemUser; import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator; import org.onap.portal.service.AdminRolesService; -import org.onap.portal.service.ExternalAccessRolesService; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -66,8 +65,12 @@ public class RolesApprovalSystemController { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesApprovalSystemController.class); + private final AdminRolesService userRolesService; + @Autowired - private AdminRolesService userRolesService; + public RolesApprovalSystemController(AdminRolesService userRolesService) { + this.userRolesService = userRolesService; + } @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class) @RequestMapping(value = {"/userProfile"}, method = RequestMethod.POST, produces = "application/json") diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java index 5f15fc0c..02a04233 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java @@ -61,49 +61,49 @@ import org.onap.portal.domain.db.fn.FnRoleFunction; @AllArgsConstructor public class CentralV2Role implements Serializable, Comparable { - private static final long serialVersionUID = -4332644961113063714L; + private static final long serialVersionUID = -4332644961113063714L; - private Long id; - private LocalDateTime created; - private LocalDateTime modified; - private Long createdId; - private Long modifiedId; - private Long rowNum; - private String name; - private boolean active; - private Integer priority; - @Builder.Default - private SortedSet roleFunctions = new TreeSet<>(); - @Builder.Default - private SortedSet childRoles = new TreeSet<>(); - @Builder.Default - private SortedSet parentRoles = new TreeSet<>(); + private Long id; + private LocalDateTime created; + private LocalDateTime modified; + private Long createdId; + private Long modifiedId; + private Long rowNum; + private String name; + private boolean active; + private Integer priority; + @Builder.Default + private SortedSet roleFunctions = new TreeSet<>(); + @Builder.Default + private SortedSet childRoles = new TreeSet<>(); + @Builder.Default + private SortedSet parentRoles = new TreeSet<>(); - public CentralV2Role(Long id, String name) { - this.id = id; - this.name = name; - } + public CentralV2Role(Long id, String name) { + this.id = id; + this.name = name; + } - public void addRoleFunction(FnRoleFunction roleFunction) { - this.roleFunctions.add(roleFunction); - } + public void addRoleFunction(DomainVo roleFunction) { + this.roleFunctions.add(roleFunction); + } - public void addChildRole(CentralV2Role role) { - this.childRoles.add(role); - } + public void addChildRole(CentralV2Role role) { + this.childRoles.add(role); + } - public void addParentRole(CentralV2Role role) { - this.parentRoles.add(role); - } + public void addParentRole(CentralV2Role role) { + this.parentRoles.add(role); + } - @Override - public int compareTo(Object obj) { - CentralV2Role other = (CentralV2Role) obj; + @Override + public int compareTo(Object obj) { + CentralV2Role other = (CentralV2Role) obj; - String c1 = getName(); - String c2 = other.getName(); + String c1 = getName(); + String c2 = other.getName(); - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java b/portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java new file mode 100644 index 00000000..c85278d3 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portal.exception; + +public class DuplicateRecordException extends Exception { + + private static final long serialVersionUID = 2759542750310357001L; + + public DuplicateRecordException(String msg) { + super(msg); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/exception/NonCentralizedAppException.java b/portal-BE/src/main/java/org/onap/portal/exception/NonCentralizedAppException.java new file mode 100644 index 00000000..3782e6ab --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/exception/NonCentralizedAppException.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.exception; + +public class NonCentralizedAppException extends Exception { + + String appName; + + private static final long serialVersionUID = 1L; + + public NonCentralizedAppException(String name) { + this.appName = name; + } + + @Override + public String toString() { + return appName + " is not Centralized Application"; + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java index 3ee30827..27a5eeaf 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java @@ -78,7 +78,6 @@ import org.onap.portal.domain.db.fn.FnRole; import org.onap.portal.domain.db.fn.FnRoleFunction; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.db.fn.FnUserRole; -import org.onap.portal.domain.dto.ecomp.EPUserAppRolesRequest; import org.onap.portal.domain.dto.model.ExternalSystemRoleApproval; import org.onap.portal.domain.dto.model.ExternalSystemUser; import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin; @@ -286,7 +285,7 @@ public class AdminRolesService { return false; } - private boolean isAccountAdminOfApplication(Long userId, FnApp app) { + public boolean isAccountAdminOfApplication(Long userId, FnApp app) { boolean isApplicationAccountAdmin = false; try { logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId); diff --git a/portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java b/portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java new file mode 100644 index 00000000..d4f3e0df --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java @@ -0,0 +1,29 @@ +package org.onap.portal.service; + +import java.util.List; +import javax.persistence.EntityManager; +import org.onap.portal.domain.dto.ecomp.CentralizedApp; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class CentralizedAppService { + + private final EntityManager entityManager; + + @Autowired + public CentralizedAppService(EntityManager entityManager) { + this.entityManager = entityManager; + } + + public List getCentralizedAppsOfUser(final String userId) { + String query = "select distinct fa.app_id, fa.app_name " + + "from fn_role fr, fn_user_role fur, fn_app fa, fn_user fu " + + "Where fu.user_id = fur.user_id and fur.role_id = fr.role_id and fa.app_id = fur.app_id " + + "and fu.org_user_id = :userId and (fur.role_id = 999 or fur.role_id = 1) and fr.active_yn='Y' and ((fa.enabled = 'Y' and fa.auth_central='Y') or fa.app_id =1)"; + + return entityManager.createQuery(query).getResultList(); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java index 4bfce266..fbe02af6 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java @@ -48,6 +48,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; @@ -74,6 +75,7 @@ import org.onap.portal.domain.db.fn.FnUserRole; import org.onap.portal.domain.dto.ecomp.EPAppRoleFunction; import org.onap.portal.domain.dto.ecomp.EPUserAppRolesRequest; import org.onap.portal.domain.dto.ecomp.ExternalRoleDetails; +import org.onap.portal.domain.dto.ecomp.UploadRoleFunctionExtSystem; import org.onap.portal.domain.dto.model.ExternalSystemUser; import org.onap.portal.domain.dto.transport.BulkUploadRoleFunction; import org.onap.portal.domain.dto.transport.BulkUploadUserRoles; @@ -112,6 +114,7 @@ import org.onap.portal.utils.EPUserUtils; import org.onap.portal.utils.EcompPortalUtils; import org.onap.portal.utils.PortalConstants; 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; @@ -209,7 +212,7 @@ public class ExternalAccessRolesService { this.bulkUploadUserRolesService = bulkUploadUserRolesService; } - String getFunctionCodeType(String roleFuncItem) { + public String getFunctionCodeType(String roleFuncItem) { String type = null; if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu")) || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) { @@ -311,7 +314,7 @@ public class ExternalAccessRolesService { return roleList; } - String getFunctionCodeAction(String roleFuncItem) { + public String getFunctionCodeAction(String roleFuncItem) { return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem); } @@ -2355,7 +2358,7 @@ public class ExternalAccessRolesService { return setUserRoles; } - private List getUser(String loginId) throws InvalidUserException { + public List getUser(String loginId) throws InvalidUserException { List userList = fnUserService.getUserWithOrgUserId(loginId); if (userList.isEmpty()) { throw new InvalidUserException("User not found"); @@ -3217,12 +3220,66 @@ public class ExternalAccessRolesService { Role role = new Role(); role.setName(epRole.getRoleName()); boolean status = addRoleDescriptionInExtSystem(role.getName(), app.getAuthNamespace()); - if (status) + if (status) { roleDescUpdated++; + } } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e); } return roleDescUpdated; } + + public Role convertCentralRoleToRole(String result) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + Role newRole = new Role(); + try { + newRole = mapper.readValue(result, Role.class); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e); + } + if (newRole.getRoleFunctions() != null) { + Set roleFunctionList = newRole.getRoleFunctions(); + Set roleFunctionListNew = new HashSet<>(); + for (Object nextValue : roleFunctionList) { + RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFun); + } + newRole.setRoleFunctions(roleFunctionListNew); + } + return newRole; + } + + public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, FnApp app) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try { + ExternalAccessRolePerms extRolePerms; + ExternalAccessPerms extPerms; + extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + data.getType(), + EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction()); + String appNameSpace = ""; + if (data.isGlobalRolePartnerFunc()) { + //TODO HARDCODED ID + appNameSpace = fnAppService.getById(1L).getAuthNamespace(); + } else { + appNameSpace = app.getAuthNamespace(); + } + 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; + } + } } -- 2.16.6