diff options
Diffstat (limited to 'ecomp-portal-BE-common')
80 files changed, 6633 insertions, 5021 deletions
diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml index b8787f78..61f166db 100644 --- a/ecomp-portal-BE-common/pom.xml +++ b/ecomp-portal-BE-common/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.portal</groupId> <artifactId>onap-portal-parent</artifactId> - <version>2.5.0</version> + <version>2.6.0-SNAPSHOT</version> </parent> <artifactId>portal-be-common</artifactId> @@ -600,6 +600,24 @@ <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.8.10</version> </dependency> + <!-- https://mvnrepository.com/artifact/org.glassfish.web/javax.el --> + <dependency> + <groupId>org.glassfish.web</groupId> + <artifactId>javax.el</artifactId> + <version>2.2.6</version> + </dependency> + <!-- https://mvnrepository.com/artifact/javax.el/el-api --> + <dependency> + <groupId>javax.el</groupId> + <artifactId>el-api</artifactId> + <version>2.2.1-b04</version> + </dependency> + <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup --> + <dependency> + <groupId>org.jsoup</groupId> + <artifactId>jsoup</artifactId> + <version>1.12.1</version> + </dependency> <dependency> <groupId>org.glassfish.jersey.connectors</groupId> <artifactId>jersey-jetty-connector</artifactId> diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java index cd911b80..7b42d52d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java @@ -80,9 +80,7 @@ public class MusicSessionRepositoryHandler { MusicService.removeSession(id); } catch (MusicLockingException e) { logger.error(EELFLoggerDelegate.errorLogger, "removeSession locking failed with id " + id, e); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, "removeSession failed with id " + id, e); - } + } } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java index b5bd02bc..4b401e22 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsController.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -37,13 +39,21 @@ */ package org.onap.portalapp.portal.controller; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.json.JSONArray; +import org.json.JSONObject; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.AdminUserApplications; import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel; @@ -52,10 +62,13 @@ import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EcompApp; import org.onap.portalapp.portal.domain.UserRoles; +import org.onap.portalapp.portal.exceptions.InvalidApplicationException; import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.service.EPAppService; import org.onap.portalapp.portal.service.EPLeftMenuService; +import org.onap.portalapp.portal.service.ExternalAccessRolesService; import org.onap.portalapp.portal.transport.EPAppsManualPreference; import org.onap.portalapp.portal.transport.EPAppsSortPreference; import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref; @@ -63,6 +76,7 @@ import org.onap.portalapp.portal.transport.EPWidgetsSortPreference; import org.onap.portalapp.portal.transport.FieldsValidator; import org.onap.portalapp.portal.transport.LocalRole; import org.onap.portalapp.portal.transport.OnboardingApp; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalapp.util.EPUserUtils; @@ -73,15 +87,18 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +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 com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; @RestController @EnableAspectJAutoProxy @@ -97,6 +114,10 @@ public class AppsController extends EPRestrictedBaseController { @Autowired private EPLeftMenuService leftMenuService; + + @Autowired + private ExternalAccessRolesService externalAccessRolesService; + RestTemplate template = new RestTemplate(); /** * RESTful service method to fetch all Applications available to current @@ -471,7 +492,7 @@ public class AppsController extends EPRestrictedBaseController { if (!adminRolesService.isSuperAdmin(user)) { EcompPortalUtils.setBadPermissions(user, response, "getApps"); } else { - apps = appService.getAllApps(false); + apps = appService.getAllApplications(false); EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/availableApps", "GET result =", apps); } } catch (Exception e) { @@ -664,10 +685,18 @@ public class AppsController extends EPRestrictedBaseController { EPUser user = EPUserUtils.getUserSession(request); List<OnboardingApp> onboardingApps = null; try { - if (!adminRolesService.isSuperAdmin(user)) { + if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) { EcompPortalUtils.setBadPermissions(user, response, "getOnboardingApps"); } else { + + if(adminRolesService.isSuperAdmin(user)){ onboardingApps = appService.getOnboardingApps(); + } + else if(adminRolesService.isAccountAdmin(user)) + { + //get all his admin apps + onboardingApps = appService.getAdminAppsOfUser(user); + } EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "GET result =", "onboardingApps of size " + onboardingApps.size()); } @@ -687,19 +716,39 @@ public class AppsController extends EPRestrictedBaseController { * @param modifiedOnboardingApp * app to update * @return FieldsValidator + * @throws Exception */ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.PUT, produces = "application/json") public FieldsValidator putOnboardingApp(HttpServletRequest request, - @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) { + @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) throws Exception { FieldsValidator fieldsValidator = null; EPUser user = null; EPApp oldEPApp = null; + oldEPApp = appService.getApp(modifiedOnboardingApp.id); + ResponseEntity<String> res = null; + try { user = EPUserUtils.getUserSession(request); - if (!adminRolesService.isSuperAdmin(user)) { + if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdminOfAnyActiveorInactiveApplication(user, oldEPApp) ) { EcompPortalUtils.setBadPermissions(user, response, "putOnboardingApp"); } else { - oldEPApp = appService.getApp(modifiedOnboardingApp.id); + if((oldEPApp.getCentralAuth() && modifiedOnboardingApp.isCentralAuth && !oldEPApp.getNameSpace().equalsIgnoreCase(modifiedOnboardingApp.nameSpace) && modifiedOnboardingApp.nameSpace!= null ) || (!oldEPApp.getCentralAuth() && modifiedOnboardingApp.isCentralAuth && modifiedOnboardingApp.nameSpace!= null)) + { + try { + res = appService.checkIfNameSpaceIsValid(modifiedOnboardingApp.nameSpace); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) { + fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response); + throw new InvalidApplicationException("Invalid NameSpace"); + }else{ + fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response); + throw e; + } + } + + } modifiedOnboardingApp.normalize(); fieldsValidator = appService.modifyOnboardingApp(modifiedOnboardingApp, user); response.setStatus(fieldsValidator.httpStatusCode.intValue()); @@ -711,8 +760,9 @@ public class AppsController extends EPRestrictedBaseController { try { String oldvaluesAsJson = new ObjectMapper().writeValueAsString(oldEPApp); String newvaluesAsJson = new ObjectMapper().writeValueAsString(modifiedOnboardingApp); - logger.info(EELFLoggerDelegate.auditLogger, "/portalApi/onboardingApps, old values ="+oldvaluesAsJson); - logger.info(EELFLoggerDelegate.auditLogger, "/portalApi/onboardingApps, loginId="+user.getLoginId()+", new values ="+newvaluesAsJson); + logger.info(EELFLoggerDelegate.auditLogger, "/portalApi/onboardingApps, old values ={}", oldvaluesAsJson); + logger.info(EELFLoggerDelegate.auditLogger, "/portalApi/onboardingApps, loginId={}, new values ={}", + user != null ? user.getLoginId() : "", newvaluesAsJson); } catch (JsonProcessingException e) { logger.error(EELFLoggerDelegate.errorLogger, "putOnboardingApps failed", e); } @@ -722,6 +772,8 @@ public class AppsController extends EPRestrictedBaseController { return fieldsValidator; } + + /** * * @param request @@ -742,17 +794,58 @@ public class AppsController extends EPRestrictedBaseController { EcompPortalUtils.setBadPermissions(user, response, "postOnboardingApps"); } else { newOnboardingApp.normalize(); + ResponseEntity<String> res = null; + try { + if( !(newOnboardingApp.nameSpace == null) && !newOnboardingApp.nameSpace.isEmpty()) + res = appService.checkIfNameSpaceIsValid(newOnboardingApp.nameSpace); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + if (e.getStatusCode() == HttpStatus.NOT_FOUND || e.getStatusCode() == HttpStatus.FORBIDDEN) { + fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response); + throw new InvalidApplicationException("Invalid NameSpace"); + }else{ + fieldsValidator = setResponse(e.getStatusCode(),fieldsValidator,response); + throw e; + } + } fieldsValidator = appService.addOnboardingApp(newOnboardingApp, user); response.setStatus(fieldsValidator.httpStatusCode.intValue()); } + if(response.getStatus()==200) { + try { + String newvaluesAsJson = new ObjectMapper().writeValueAsString(newOnboardingApp); + logger.info(EELFLoggerDelegate.auditLogger, "/portalApi/onboardingApps, loginId="+user.getLoginId()+", values ="+newvaluesAsJson); + } catch (JsonProcessingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApps failed", e); + } + } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApp failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "postOnboardingApp failed", e); } EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps", "POST result =", response.getStatus()); return fieldsValidator; } + + private FieldsValidator setResponse(HttpStatus statusCode,FieldsValidator fieldsValidator,HttpServletResponse response) + { + fieldsValidator = new FieldsValidator(); + if (statusCode == HttpStatus.NOT_FOUND || statusCode == HttpStatus.FORBIDDEN) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND); + logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed"+ "invalid namespace"); + }else if (statusCode == HttpStatus.UNAUTHORIZED) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_UNAUTHORIZED); + logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed"+ "unauthorized"); + } else{ + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "setResponse failed ",statusCode); + + } + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + return fieldsValidator; + } /** * REST endpoint to process a request to delete an on-boarded application. @@ -778,11 +871,15 @@ public class AppsController extends EPRestrictedBaseController { fieldsValidator = appService.deleteOnboardingApp(user, appId); response.setStatus(fieldsValidator.httpStatusCode.intValue()); } + if (response.getStatus() == 200) { + logger.info(EELFLoggerDelegate.auditLogger, + "/portalApi/onboardingApps/" + appId + "deleted by user " + user.getLoginId()); + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/onboardingApps" + appId, "DELETE result =", response.getStatus()); return fieldsValidator; @@ -823,5 +920,6 @@ public class AppsController extends EPRestrictedBaseController { header.setContentLength(app.getThumbnail().length); return new HttpEntity<byte[]>(app.getThumbnail(), header); } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java index cef5fa74..fe029e0e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java @@ -39,9 +39,15 @@ package org.onap.portalapp.portal.controller; import java.util.List; +import java.util.Set; 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.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -88,16 +94,12 @@ import io.swagger.annotations.ApiOperation; @EnableAspectJAutoProxy @EPAuditLog public class AppsControllerExternalRequest implements BasicAuthenticationController { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class); private static final String ONBOARD_APP = "/onboardApp"; - // Where is this used? - public boolean isAuxRESTfulCall() { - return true; - } - /** * For testing whether a user is a superadmin. */ @@ -145,10 +147,20 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json") @ResponseBody public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response, - @RequestBody EPUser epUser) { + @Valid @RequestBody EPUser epUser) { EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + if (epUser!=null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<EPUser>> constraintViolations = validator.validate(epUser); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } + // Check mandatory fields. if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 // || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 // @@ -248,10 +260,18 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json") @ResponseBody public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @RequestBody OnboardingApp newOnboardApp) { + @Valid @RequestBody OnboardingApp newOnboardApp) { EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); - + if (newOnboardApp != null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<OnboardingApp>> constraintViolations = validator.validate(newOnboardApp); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } // Validate fields if (newOnboardApp.id != null) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -335,9 +355,20 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json") @ResponseBody public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) { + @PathVariable("appId") Long appId, @Valid @RequestBody OnboardingApp oldOnboardApp) { EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + + if (oldOnboardApp != null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<OnboardingApp>> constraintViolations = validator.validate(oldOnboardApp); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } + // Validate fields. if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java index 34090d6b..67d75666 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuditLogController.java @@ -88,7 +88,7 @@ public class AuditLogController extends EPRestrictedBaseController { @RequestMapping(value = "/store", method = RequestMethod.GET, produces = "application/json") public void auditLog(HttpServletRequest request, @RequestParam String affectedAppId, @RequestParam String type, @RequestParam String comment) { - logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {], comment {}", affectedAppId, type, + logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {}, comment {}", affectedAppId, type, comment); String cd_type = null; try { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java index 29f5b20f..04ee5e0b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java @@ -45,8 +45,14 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import javax.servlet.http.HttpServletRequest; +import javax.validation.ConstraintViolation; +import javax.validation.Valid; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -56,6 +62,7 @@ import org.onap.portalapp.portal.service.DashboardSearchService; import org.onap.portalapp.portal.transport.CommonWidget; import org.onap.portalapp.portal.transport.CommonWidgetMeta; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.domain.support.CollaborateList; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; @@ -68,6 +75,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/portalApi/search") public class DashboardSearchResultController extends EPRestrictedBaseController { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class); @@ -85,8 +93,11 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request, @RequestParam String resourceType) { - return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success", - searchService.getWidgetData(resourceType)); + if (stringIsNotSafeHtml(resourceType)) { + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "resourceType: String string is not valid", ""); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.getWidgetData(resourceType)); } /** @@ -97,19 +108,26 @@ public class DashboardSearchResultController extends EPRestrictedBaseController * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) { + public PortalRestResponse<String> saveWidgetDataBulk(@Valid @RequestBody CommonWidgetMeta commonWidgetMeta) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta); - if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", - "Category cannot be null or empty"); + if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Cateogry cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<CommonWidgetMeta>> constraintViolations = validator.validate(commonWidgetMeta); + if (!constraintViolations.isEmpty()) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category is not valid"); + } // validate dates for (CommonWidget cw : commonWidgetMeta.getItems()) { String err = validateCommonWidget(cw); if (err != null) - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null); } - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", - searchService.saveWidgetDataBulk(commonWidgetMeta)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetDataBulk(commonWidgetMeta)); } /** @@ -120,16 +138,23 @@ public class DashboardSearchResultController extends EPRestrictedBaseController * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) { + public PortalRestResponse<String> saveWidgetData(@Valid @RequestBody CommonWidget commonWidget) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); - if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")) - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", - "Cateogry cannot be null or empty"); + if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<CommonWidget>> constraintViolations = validator.validate(commonWidget); + if (!constraintViolations.isEmpty()) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category is not valid"); + } String err = validateCommonWidget(commonWidget); if (err != null) - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", - searchService.saveWidgetData(commonWidget)); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetData(commonWidget)); } /** @@ -162,10 +187,17 @@ public class DashboardSearchResultController extends EPRestrictedBaseController * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) { + public PortalRestResponse<String> deleteWidgetData(@Valid @RequestBody CommonWidget commonWidget) { + if (commonWidget!=null){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<CommonWidget>> constraintViolations = validator.validate(commonWidget); + if (!constraintViolations.isEmpty()) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "CommonWidget is not valid"); + } logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget); - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", - searchService.deleteWidgetData(commonWidget)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.deleteWidgetData(commonWidget)); } /** @@ -185,11 +217,14 @@ public class DashboardSearchResultController extends EPRestrictedBaseController if (user == null) { return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: User object is null? - check logs", - new HashMap<String, List<SearchResultItem>>()); + new HashMap<>()); } else if (searchString == null || searchString.trim().length() == 0) { return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null", - new HashMap<String, List<SearchResultItem>>()); - } else { + new HashMap<>()); + }else if (stringIsNotSafeHtml(searchString)){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not valid", + new HashMap<>()); + }else { logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'", user.getLoginId(), searchString); Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(), @@ -199,7 +234,7 @@ public class DashboardSearchResultController extends EPRestrictedBaseController } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", - new HashMap<String, List<SearchResultItem>>()); + new HashMap<>()); } } @@ -258,4 +293,13 @@ public class DashboardSearchResultController extends EPRestrictedBaseController } } + private boolean stringIsNotSafeHtml(String string){ + SecureString secureString = new SecureString(string); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString); + return !constraintViolations.isEmpty(); + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java index fb0c269b..15ce305d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -112,11 +114,13 @@ public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseContro String appKey = request.getHeader("uebkey"); EPApp app = findEpApp(appKey); List<Long> postRoleIds = new ArrayList<Long>(); - for (Long roleId : notificationItem.getRoleIds()) { - EPRole role = epRoleService.getRole(app.getId(), roleId); - if (role != null) - postRoleIds.add(role.getId()); - } + if (app != null) { + for (Long roleId : notificationItem.getRoleIds()) { + EPRole role = epRoleService.getRole(app.getId(), roleId); + if (role != null) + postRoleIds.add(role.getId()); + } + } // --- recreate the user notification object with the POrtal Role Ids EpNotificationItem postItem = new EpNotificationItem(); @@ -151,10 +155,10 @@ public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseContro try { list = this.getDataAccessService().executeNamedQuery("getMyAppDetailsByUebKey", params, null); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getMyAppDetailsByUebKey failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getMyAppDetailsByUebKey failed", e); } - return (list == null || list.size() == 0) ? null : (EPApp) list.get(0); + return (list == null || list.isEmpty()) ? null : (EPApp) list.get(0); } @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List") diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java index cecbd9bd..6818d505 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java @@ -123,7 +123,7 @@ public class HealthCheckController extends EPUnRestrictedBaseController { HealthStatus healthStatus = new HealthStatus(500, ""); // Return the status as 500 if it suspended due to manual fail over - if (HealthMonitor.isSuspended) { + if (HealthMonitor.isSuspended()) { healthStatus.body = "Suspended"; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); MDC.put(EPCommonSystemProperties.RESPONSE_CODE, @@ -171,16 +171,15 @@ public class HealthCheckController extends EPUnRestrictedBaseController { // dbInfo.dbClusterStatus = statusOk; // } - if (!HealthMonitor.isDatabasePermissionsOk()) { + if (!HealthMonitor.isDbPermissionsOk()) { dbInfo.dbPermissions = "Problem, check the logs for more details"; EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError); } else { dbInfo.dbPermissions = statusOk; } statusCollection.add(dbInfo); - - org.onap.portalapp.music.util.MusicUtil MusicUtilSDK = new org.onap.portalapp.music.util.MusicUtil(); - if(MusicUtilSDK.isMusicEnable()){ + + if(org.onap.portalapp.music.util.MusicUtil.isMusicEnable()){ HealthStatusInfo CassandraStatusInfo = new HealthStatusInfo("Music-Cassandra"); //CassandraStatusInfo.hostName = EcompPortalUtils.getMyHostName(); CassandraStatusInfo.ipAddress = MusicUtil.getMyCassaHost(); @@ -234,7 +233,7 @@ public class HealthCheckController extends EPUnRestrictedBaseController { public HealthStatus healthCheckSuspend(HttpServletRequest request, HttpServletResponse response) { HealthStatus healthStatus = new HealthStatus(500, "Suspended for manual failover mechanism"); - HealthMonitor.isSuspended = true; + HealthMonitor.setSuspended(true); healthStatus.statusCode = 200; EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckSuspend", "GET result =", @@ -248,7 +247,7 @@ public class HealthCheckController extends EPUnRestrictedBaseController { public HealthStatus healthCheckResume(HttpServletRequest request, HttpServletResponse response) { HealthStatus healthStatus = new HealthStatus(500, "Resumed from manual failover mechanism"); - HealthMonitor.isSuspended = false; + HealthMonitor.setSuspended(false); healthStatus.statusCode = 200; EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckResume", "GET result =", response.getStatus()); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java index f3a79285..383e4720 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/LanguageController.java @@ -32,7 +32,7 @@ public class LanguageController { @Autowired private LanguageService languageService; - @RequestMapping(value = "/language",method = RequestMethod.GET) + @RequestMapping(value = "/language",method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public JSONObject getLanguageList() { return languageService.getLanguages(); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java index 50eaa600..2f956cc3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/MicroserviceController.java @@ -39,9 +39,15 @@ package org.onap.portalapp.portal.controller; import java.util.List; +import java.util.Set; 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.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.MicroserviceData; import org.onap.portalapp.portal.domain.WidgetCatalog; @@ -72,6 +78,7 @@ import org.springframework.web.client.RestTemplate; @EnableAspectJAutoProxy @EPAuditLog public class MicroserviceController extends EPRestrictedBaseController { + public static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); String whatService = "widgets-service"; RestTemplate template = new RestTemplate(); @@ -84,53 +91,68 @@ public class MicroserviceController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.POST) public PortalRestResponse<String> createMicroservice(HttpServletRequest request, HttpServletResponse response, - @RequestBody MicroserviceData newServiceData) throws Exception { + @Valid @RequestBody MicroserviceData newServiceData) throws Exception { if (newServiceData == null) { - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", - "MicroserviceData cannot be null or empty"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", + "MicroserviceData cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set<ConstraintViolation<MicroserviceData>> constraintViolations = validator.validate(newServiceData); + if(!constraintViolations.isEmpty()){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "ERROR", "MicroserviceData is not valid"); + } } long serviceId = microserviceService.saveMicroservice(newServiceData); try { microserviceService.saveServiceParameters(serviceId, newServiceData.getParameterList()); } catch (Exception e) { - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.GET) public List<MicroserviceData> getMicroservice(HttpServletRequest request, HttpServletResponse response) throws Exception { - List<MicroserviceData> list = microserviceService.getMicroserviceData(); - return list; + return microserviceService.getMicroserviceData(); } @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.PUT) public PortalRestResponse<String> updateMicroservice(HttpServletRequest request, HttpServletResponse response, - @PathVariable("serviceId") long serviceId, @RequestBody MicroserviceData newServiceData) throws Exception { + @PathVariable("serviceId") long serviceId, @Valid @RequestBody MicroserviceData newServiceData) { if (newServiceData == null) { - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", - "MicroserviceData cannot be null or empty"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", + "MicroserviceData cannot be null or empty"); + }else { + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set<ConstraintViolation<MicroserviceData>> constraintViolations = validator.validate(newServiceData); + if(!constraintViolations.isEmpty()){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "ERROR", "MicroserviceData is not valid"); + } } try { microserviceService.updateMicroservice(serviceId, newServiceData); } catch (Exception e) { - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.DELETE) public PortalRestResponse<String> deleteMicroservice(HttpServletRequest request, HttpServletResponse response, - @PathVariable("serviceId") long serviceId) throws Exception { + @PathVariable("serviceId") long serviceId) { try { ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { }; // If this service is assoicated with widgets, cannnot be deleted - ResponseEntity<List<WidgetCatalog>> ans = (ResponseEntity<List<WidgetCatalog>>) template.exchange( + ResponseEntity<List<WidgetCatalog>> ans = template.exchange( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + serviceId, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef); @@ -140,17 +162,18 @@ public class MicroserviceController extends EPRestrictedBaseController { else{ StringBuilder sb = new StringBuilder(); for(int i = 0; i < widgets.size(); i++){ - sb.append("'" + widgets.get(i).getName() + "' "); + sb.append("'").append(widgets.get(i).getName()).append("' "); if(i < (widgets.size()-1)){ sb.append(","); } } - return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", sb.toString()); + return new PortalRestResponse<>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", + sb.toString()); } } catch (Exception e) { - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java index c6849cd8..b50d1cf4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -48,6 +50,11 @@ import java.util.TreeSet; 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.portalapp.controller.EPRestrictedBaseController; @@ -77,6 +84,7 @@ import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -109,6 +117,8 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @EnableAspectJAutoProxy @EPAuditLog public class RoleManageController extends EPRestrictedBaseController { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + private static final String PIPE = "|"; private static final String ROLE_INVALID_CHARS = "%=():,\"\""; @@ -120,37 +130,36 @@ public class RoleManageController extends EPRestrictedBaseController { @Autowired private RoleListController roleListController; - + @Autowired private EPAppService appService; @Autowired private AuditService auditService; - + @Autowired private ExternalAccessRolesService externalAccessRolesService; - - + @Autowired private AdminRolesService adminRolesService; /** * Calls an SDK-Core library method that gets the available roles and writes - * them to the request object. Portal specifies a Hibernate mappings from - * the Role class to the fn_role_v view, which ensures that only Portal - * (app_id is null) roles are fetched. + * them to the request object. Portal specifies a Hibernate mappings from the + * Role class to the fn_role_v view, which ensures that only Portal (app_id is + * null) roles are fetched. * - * Any method declared void (no return value) or returning null causes the - * audit log aspect method to declare failure. TODO: should return a JSON - * string. + * Any method declared void (no return value) or returning null causes the audit + * log aspect method to declare failure. TODO: should return a JSON string. * * @param request * @param response - * @throws Exception + * @throws Exception */ - + @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET) - public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception { + public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) + throws Exception { try { EPUser user = EPUserUtils.getUserSession(request); EPApp requestedApp = appService.getApp(appId); @@ -176,12 +185,10 @@ public class RoleManageController extends EPRestrictedBaseController { logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e); } } - - @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST) - public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId, - @PathVariable("roleId") Long roleId) throws Exception { + public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception { EPApp requestedApp = null; String restcallStatus = null; HashMap<String, Object> responseMap = new HashMap<>(); @@ -222,10 +229,10 @@ public class RoleManageController extends EPRestrictedBaseController { } return responseMap; } - + @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST) - public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId, - @PathVariable("roleId") Long roleId) throws Exception { + public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception { EPUser user = EPUserUtils.getUserSession(request); EPApp requestedApp = null; @@ -288,7 +295,7 @@ public class RoleManageController extends EPRestrictedBaseController { } return responseMap; } - + @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST) public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception { @@ -343,9 +350,13 @@ public class RoleManageController extends EPRestrictedBaseController { throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType() + " and action: " + roleFunction.getAction() + " found while saving!"); } - roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode())); - roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE - + roleFunction.getAction()); + if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode())) + roleFunction.setCode(roleFunction.getType() + PIPE + + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE + + roleFunction.getAction()); + else + roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE + + roleFunction.getAction()); domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction); } } else { @@ -434,29 +445,29 @@ public class RoleManageController extends EPRestrictedBaseController { @PathVariable("roleId") Long roleId) throws Exception { try { EPUser user = EPUserUtils.getUserSession(request); - ObjectMapper mapper = new ObjectMapper(); - EPApp requestedApp = appService.getApp(appId); - if (isAuthorizedUser(user, requestedApp)) { - fieldsValidation(requestedApp); - if (requestedApp.getCentralAuth()) { - CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey()); - logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId); - Map<String, Object> 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.getName()); - } else { - logger.info(EELFLoggerDelegate.auditLogger, - "RoleManageController.getRoleFunctionList, Unauthorized user"); - SendErrorForUnauthorizedUser(response, user); - } + ObjectMapper mapper = new ObjectMapper(); + EPApp requestedApp = appService.getApp(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getCentralAuth()) { + CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey()); + logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId); + Map<String, Object> 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.getName()); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.getRoleFunctionList, Unauthorized user"); + SendErrorForUnauthorizedUser(response, user); + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e); throw e; @@ -468,26 +479,26 @@ public class RoleManageController extends EPRestrictedBaseController { @PathVariable("appId") Long appId) throws Exception { try { EPUser user = EPUserUtils.getUserSession(request); - EPApp requestedApp = appService.getApp(appId); - if (isAuthorizedUser(user, requestedApp)) { - fieldsValidation(requestedApp); - if (requestedApp.getCentralAuth()) { - List<CentralV2RoleFunction> answer = null; - Map<String, Object> 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.getName()); - } else { - logger.info(EELFLoggerDelegate.auditLogger, - "RoleManageController.getRoleFunctionList, Unauthorized user"); - EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); - response.getWriter().write("Unauthorized User"); - } + EPApp requestedApp = appService.getApp(appId); + if (isAuthorizedUser(user, requestedApp)) { + fieldsValidation(requestedApp); + if (requestedApp.getCentralAuth()) { + List<CentralV2RoleFunction> answer = null; + Map<String, Object> 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.getName()); + } 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; @@ -495,8 +506,17 @@ public class RoleManageController extends EPRestrictedBaseController { } @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST) - public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc, + public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc, @PathVariable("appId") Long appId) throws Exception { + if (roleFunc!=null) { + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc); + + if(!constraintViolations.isEmpty()){ + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR"); + } + } EPUser user = EPUserUtils.getUserSession(request); boolean saveOrUpdateResponse = false; try { @@ -504,13 +524,14 @@ public class RoleManageController extends EPRestrictedBaseController { if (isAuthorizedUser(user, requestedApp)) { fieldsValidation(requestedApp); if (requestedApp.getCentralAuth()) { - String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction(); + String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction(); CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code, requestedApp.getUebKey()); - if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) { + if (domainRoleFunction != null + && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) { addIfTypeActionDoesNotExits(domainRoleFunction); } - boolean isSave = true; + boolean isSave = true; if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode()) && domainRoleFunction.getType().equals(roleFunc.getType()) && domainRoleFunction.getAction().equals(roleFunc.getAction())) { @@ -526,16 +547,14 @@ public class RoleManageController extends EPRestrictedBaseController { if (saveOrUpdateResponse) { EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0); EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0); - String activityCode = (isSave) - ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION + 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.getName() + " is not Centralized Application"); } else { - logger.info(EELFLoggerDelegate.auditLogger, - "RoleManageController.saveRoleFunction, Unauthorized user"); + logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user"); EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); } @@ -545,35 +564,29 @@ public class RoleManageController extends EPRestrictedBaseController { } return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success"); } - + private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) { - logger.info(EELFLoggerDelegate.applicationLogger, - "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code); + 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 + "'", + 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.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)); + 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(CentralV2RoleFunction domainRoleFunction) { - if(domainRoleFunction.getCode().contains(PIPE)) { + if (domainRoleFunction.getCode().contains(PIPE)) { String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode()); String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode()); String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode()); @@ -592,6 +605,19 @@ public class RoleManageController extends EPRestrictedBaseController { public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception { EPUser user = EPUserUtils.getUserSession(request); + + if (roleFunc!=null) { + SecureString secureString = new SecureString(roleFunc); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString); + + if(!constraintViolations.isEmpty()){ + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR"); + } + } + try { EPApp requestedApp = appService.getApp(appId); if (isAuthorizedUser(user, requestedApp)) { @@ -654,18 +680,30 @@ public class RoleManageController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET) public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException { + if(userId!=null) { + SecureString secureString = new SecureString(userId); + + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString); + + if(!constraintViolations.isEmpty()){ + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed"); + return null; + } + } EPUser user = EPUserUtils.getUserSession(request); List<CentralizedApp> applicationsList = null; - if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user) || adminRolesService.isRoleAdmin(user)) { - applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId); - } else { - logger.info(EELFLoggerDelegate.auditLogger, - "RoleManageController.getCentralizedAppRoles, Unauthorized user"); - EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); - } + if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user) + || adminRolesService.isRoleAdmin(user)) { + applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.getCentralizedAppRoles, Unauthorized user"); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + } return applicationsList; } - + public RoleListController getRoleListController() { return roleListController; } @@ -682,7 +720,6 @@ public class RoleManageController extends EPRestrictedBaseController { this.roleController = roleController; } - @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody Long appId) { @@ -694,7 +731,7 @@ public class RoleManageController extends EPRestrictedBaseController { externalAccessRolesService.syncApplicationRolesWithEcompDB(app); } else { logger.info(EELFLoggerDelegate.auditLogger, - "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId()); + "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : ""); EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); } @@ -704,7 +741,7 @@ public class RoleManageController extends EPRestrictedBaseController { } return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success"); } - + @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response, @RequestBody Long appId) { @@ -713,10 +750,10 @@ public class RoleManageController extends EPRestrictedBaseController { EPApp app = appService.getApp(appId); if (isAuthorizedUser(user, app)) { fieldsValidation(app); - externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);; + externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app); } else { logger.info(EELFLoggerDelegate.auditLogger, - "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId()); + "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : ""); EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); } @@ -754,30 +791,30 @@ public class RoleManageController extends EPRestrictedBaseController { } return allParentRoles; } - - public AuditLog getAuditInfo(EPUser user, String activityCode) - { + + public AuditLog getAuditInfo(EPUser user, String activityCode) { AuditLog auditLog = new AuditLog(); auditLog.setUserId(user.getId()); auditLog.setActivityCode(activityCode); auditLog.setAffectedRecordId(user.getOrgUserId()); - + return auditLog; } - - private void fieldsValidation(EPApp app) throws Exception{ + + private void fieldsValidation(EPApp app) throws Exception { app.getUebKey(); List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey()); - if(appInfo.isEmpty()){ + if (appInfo.isEmpty()) { throw new InvalidApplicationException("Invalid credentials"); } - if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){ + if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() + && appInfo.get(0).getCentralAuth()) { ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0)); if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND) throw new InvalidApplicationException("Invalid NameSpace"); } } - + private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) { if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp) || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID))) @@ -789,8 +826,9 @@ public class RoleManageController extends EPRestrictedBaseController { EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); response.getWriter().write("Unauthorized User"); } - - @RequestMapping(value = { "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json") + + @RequestMapping(value = { + "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response, @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) { EPUser user = EPUserUtils.getUserSession(request); @@ -799,12 +837,13 @@ public class RoleManageController extends EPRestrictedBaseController { 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); + 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.getOrgUserId()); + "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : ""); EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java index 0be83c97..af34176c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java @@ -41,7 +41,9 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import javax.servlet.http.HttpServletRequest; @@ -49,8 +51,10 @@ import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import org.onap.portalapp.controller.EPRestrictedBaseController; +import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.onap.portalapp.portal.exceptions.RoleFunctionException; import org.onap.portalapp.portal.logging.aop.EPAuditLog; import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.scheduler.SchedulerProperties; @@ -62,8 +66,11 @@ import org.onap.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestOb import org.onap.portalapp.portal.scheduler.wrapper.GetTimeSlotsWrapper; import org.onap.portalapp.portal.scheduler.wrapper.PostCreateNewVnfWrapper; import org.onap.portalapp.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper; +import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.DataAccessService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -84,6 +91,9 @@ public class SchedulerController extends EPRestrictedBaseController { @Autowired private SchedulerRestInterface schedulerRestController; + + @Autowired + private AdminRolesService adminRolesService; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class); @@ -93,33 +103,36 @@ public class SchedulerController extends EPRestrictedBaseController { @RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET, produces = "application/json") public ResponseEntity<String> getTimeSlots(HttpServletRequest request, @PathVariable("scheduler_request") String scheduler_request) throws Exception { - try { - - Date startingTime = new Date(); - String startTimeRequest = requestDateFormat.format(startingTime); - logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler GET Timeslots for startTimeRequest: ", - startTimeRequest); - logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request); - - String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS) - + scheduler_request; - - GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request); - - Date endTime = new Date(); - String endTimeRequest = requestDateFormat.format(endTime); - logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}", - endTimeRequest); - return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), - HttpStatus.valueOf(schedulerResWrapper.getStatus()))); - } catch (Exception e) { - GetTimeSlotsWrapper schedulerResWrapper=new GetTimeSlotsWrapper(); - schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); - schedulerResWrapper.setEntity(e.getMessage()); - logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e); - return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + if (checkIfUserISValidToMakeSchedule(request)) { + try { + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + logger.debug(EELFLoggerDelegate.debugLogger, + "Controller Scheduler GET Timeslots for startTimeRequest: ", startTimeRequest); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request); + + String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS) + + scheduler_request; + + GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}", + endTimeRequest); + return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), + HttpStatus.valueOf(schedulerResWrapper.getStatus()))); + } catch (Exception e) { + GetTimeSlotsWrapper schedulerResWrapper = new GetTimeSlotsWrapper(); + schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + schedulerResWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e); + return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), + HttpStatus.INTERNAL_SERVER_ERROR)); + } + }else{ + return (new ResponseEntity<String>("User is unauthorized to make this call", HttpStatus.UNAUTHORIZED)); } - } protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception { @@ -157,41 +170,45 @@ public class SchedulerController extends EPRestrictedBaseController { @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request, @RequestBody JSONObject scheduler_request) throws Exception { - try { - Date startingTime = new Date(); - String startTimeRequest = requestDateFormat.format(startingTime); + if (checkIfUserISValidToMakeSchedule(request)) { + try { + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); - logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change", - startTimeRequest); + logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change", + startTimeRequest); - // Generating uuid - String uuid = UUID.randomUUID().toString(); + // Generating uuid + String uuid = UUID.randomUUID().toString(); - scheduler_request.put("scheduleId", uuid); - logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid); + scheduler_request.put("scheduleId", uuid); + logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid); - // adding uuid to the request payload - scheduler_request.put("scheduleId", uuid); - logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString()); + // adding uuid to the request payload + scheduler_request.put("scheduleId", uuid); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString()); - String path = SchedulerProperties - .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid; + String path = SchedulerProperties + .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid; - PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid); + PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid); - Date endTime = new Date(); - String endTimeRequest = requestDateFormat.format(endTime); - logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest); + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest); - return new ResponseEntity<String>(responseWrapper.getResponse(), - HttpStatus.valueOf(responseWrapper.getStatus())); - } catch (Exception e) { - PostCreateNewVnfWrapper responseWrapper=new PostCreateNewVnfWrapper(); - responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); - responseWrapper.setEntity(e.getMessage()); - logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e); - return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + return new ResponseEntity<String>(responseWrapper.getResponse(), + HttpStatus.valueOf(responseWrapper.getStatus())); + } catch (Exception e) { + PostCreateNewVnfWrapper responseWrapper = new PostCreateNewVnfWrapper(); + responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + responseWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e); + return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + } + }else{ + return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED)); } } @@ -233,6 +250,7 @@ public class SchedulerController extends EPRestrictedBaseController { @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request, @RequestBody JSONObject scheduler_request) throws Exception { + if (checkIfUserISValidToMakeSchedule(request)) { try { Date startingTime = new Date(); String startTimeRequest = requestDateFormat.format(startingTime); @@ -259,13 +277,16 @@ public class SchedulerController extends EPRestrictedBaseController { endTimeRequest); return (new ResponseEntity<String>(responseWrapper.getResponse(),HttpStatus.valueOf(responseWrapper.getStatus()))); - } catch (Exception e) { - PostSubmitVnfChangeTimeSlotsWrapper responseWrapper=new PostSubmitVnfChangeTimeSlotsWrapper(); - responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); - responseWrapper.setEntity(e.getMessage()); - logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e); - return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + } catch (Exception e) { + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = new PostSubmitVnfChangeTimeSlotsWrapper(); + responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); + responseWrapper.setEntity(e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e); + return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + } + }else{ + return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED)); } } @@ -310,43 +331,74 @@ public class SchedulerController extends EPRestrictedBaseController { * Get Scheduler UI constant values from properties file * * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + * @throws Exception */ @RequestMapping(value = "/get_scheduler_constant", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<Map<String, String>> getSchedulerConstant(HttpServletRequest request, - HttpServletResponse response) { + HttpServletResponse response) throws Exception { logger.debug(EELFLoggerDelegate.debugLogger, "get scheduler constant"); PortalRestResponse<Map<String, String>> portalRestResponse = null; - String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined"; - HashMap<String, String> constantMap = new HashMap<>(); - constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName"); - constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName"); - constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName"); - constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl"); - constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType"); - constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus"); - constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus"); - constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName"); - constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate"); - constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId"); - try { - Map<String, String> map = new HashMap<>(); - for (Map.Entry<String, String> entry : constantMap.entrySet()) { - if (SchedulerProperties.containsProperty(entry.getKey())) - map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey())); - else - throw new Exception(entry.getKey() + errorMsg); + + if (checkIfUserISValidToMakeSchedule(request)) { + String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined"; + HashMap<String, String> constantMap = new HashMap<>(); + constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName"); + constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName"); + constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName"); + constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl"); + constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType"); + constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus"); + constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus"); + constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName"); + constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate"); + constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId"); + try { + Map<String, String> map = new HashMap<>(); + for (Map.Entry<String, String> entry : constantMap.entrySet()) { + if (SchedulerProperties.containsProperty(entry.getKey())) + map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey())); + else + throw new Exception(entry.getKey() + errorMsg); + } + logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", map); + portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success", + map); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e); + portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, + e.getMessage(), null); } - logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", - map); - portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success", map); - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e); - portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, e.getMessage(), - null); + } - return portalRestResponse; + else{ + logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed: User unauthorized to make this call"); + portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null); + } + return portalRestResponse; } + private String getPath(HttpServletRequest request) + { + String requestURI = request.getRequestURI(); + String portalApiPath = ""; + if (requestURI != null) { + String[] uriArray = requestURI.split("/portalApi/"); + if (uriArray.length > 1) { + portalApiPath = uriArray[1]; + } + } + return portalApiPath; + } + + private boolean checkIfUserISValidToMakeSchedule(HttpServletRequest request) throws Exception + { + EPUser user = EPUserUtils.getUserSession(request); + String portalApiPath = getPath(request); + Set<String> functionCodeList = adminRolesService.getAllAppsFunctionsOfUser(user.getId().toString()); + boolean isValidUser = EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList); +// boolean isValidUser = functionCodeList.stream().anyMatch(x -> functionCodeList.contains(portalApiPath)); + return isValidUser; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java index b9f6f76d..71f7f81a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java @@ -47,6 +47,10 @@ import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; @@ -56,6 +60,7 @@ import org.onap.portalapp.portal.service.UserNotificationService; import org.onap.portalapp.portal.transport.EpNotificationItem; import org.onap.portalapp.portal.transport.EpRoleNotificationItem; import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -80,7 +85,7 @@ import io.swagger.annotations.ApiOperation; @EnableAspectJAutoProxy @EPAuditLog public class TicketEventController implements BasicAuthenticationController { - + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); @Autowired private UserNotificationService userNotificationService; @@ -105,6 +110,19 @@ public class TicketEventController implements BasicAuthenticationController { logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + + if (ticketEventJson!=null){ + SecureString secureString = new SecureString(ticketEventJson); + Validator validator = VALIDATOR_FACTORY.getValidator(); + + Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString); + if (!constraintViolations.isEmpty()){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; + } + } + try { JsonNode ticketEventNotif = mapper.readTree(ticketEventJson); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserController.java index f4fab562..fc76a0e6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserController.java @@ -69,6 +69,8 @@ public class UserController extends EPRestrictedBaseController { @Autowired private UserService userService; + private static final String HIDDEN_DEFAULT_PASSWORD = "*****"; + /** * RESTful service method to get ONAP Logged in User details. * @@ -83,7 +85,7 @@ public class UserController extends EPRestrictedBaseController { try { EPUser user = EPUserUtils.getUserSession(request); ProfileDetail profileDetail = new ProfileDetail(user.getFirstName(), user.getLastName(), - user.getMiddleInitial(), user.getEmail(), user.getLoginId(), CipherUtil.decryptPKC(user.getLoginPwd())); + user.getMiddleInitial(), user.getEmail(), user.getLoginId(), HIDDEN_DEFAULT_PASSWORD); portalRestResponse = new PortalRestResponse<ProfileDetail>(PortalRestStatusEnum.OK, "success", profileDetail); EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/loggedinUser", "result =", profileDetail); @@ -124,7 +126,9 @@ public class UserController extends EPRestrictedBaseController { user.setEmail(profileDetail.getEmail()); user.setMiddleInitial(profileDetail.getMiddleName()); user.setLoginId(profileDetail.getLoginId()); - user.setLoginPwd(CipherUtil.encryptPKC(profileDetail.getLoginPassword())); + if (!HIDDEN_DEFAULT_PASSWORD.equals(profileDetail.getLoginPassword())){ + user.setLoginPwd(CipherUtil.encryptPKC(profileDetail.getLoginPassword())); + } userService.saveUser(user); // Update user info in the session request.getSession().setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java index 72ae07da..0d665a98 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -285,7 +285,7 @@ public class UserRolesController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.GET }, produces = "application/json") public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId, - @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue, + @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,@RequestParam("isSystemUser") Boolean isSystemUser, HttpServletResponse response) { EPUser user = EPUserUtils.getUserSession(request); List<RoleInAppForUser> result = null; @@ -295,7 +295,7 @@ public class UserRolesController extends EPRestrictedBaseController { EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser"); feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus()); } else { - if (EcompPortalUtils.legitimateUserId(orgUserId)) { + if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) { result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user); logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result , appid); int responseCode = EcompPortalUtils.getExternalAppResponseCode(); @@ -354,18 +354,18 @@ public class UserRolesController extends EPRestrictedBaseController { PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); StringBuilder sbUserApps = new StringBuilder(); if (newAppRolesForUser != null) { - sbUserApps.append("User '" + newAppRolesForUser.orgUserId); - if (newAppRolesForUser.appRoles != null && newAppRolesForUser.appRoles.size() >= 1) { + sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId()); + if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) { sbUserApps.append("' has roles = { "); - for (RoleInAppForUser appRole : newAppRolesForUser.appRoles) { + for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) { if (appRole.isApplied) { sbUserApps.append(appRole.roleName + " ,"); } } sbUserApps.deleteCharAt(sbUserApps.length() - 1); - sbUserApps.append("} assigned for the app " + newAppRolesForUser.appId); + sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId()); } else { - sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.appId); + sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId()); } } logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString()); @@ -383,14 +383,14 @@ public class UserRolesController extends EPRestrictedBaseController { try{ if (changesApplied.isResult()) { logger.info(EELFLoggerDelegate.applicationLogger, - "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.appId, - newAppRolesForUser.orgUserId); + "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.getAppId(), + newAppRolesForUser.getAppId()); MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); AuditLog auditLog = new AuditLog(); auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER); - auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId); + auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId()); auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE)); auditService.logActivity(auditLog, null); @@ -401,7 +401,7 @@ public class UserRolesController extends EPRestrictedBaseController { logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser", EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), - newAppRolesForUser.orgUserId, sbUserApps.toString())); + newAppRolesForUser.getOrgUserId(), sbUserApps.toString())); MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); MDC.remove(SystemProperties.MDC_TIMER); @@ -413,8 +413,8 @@ public class UserRolesController extends EPRestrictedBaseController { }catch (Exception e){ logger.error(EELFLoggerDelegate.errorLogger, - "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.appId, - newAppRolesForUser.orgUserId); + "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(), + newAppRolesForUser.getOrgUserId()); portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null); } } @@ -561,4 +561,16 @@ public class UserRolesController extends EPRestrictedBaseController { return result; } + @RequestMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, method = RequestMethod.GET, produces = "application/json") + public boolean checkIfUserIsSuperAdmin(HttpServletRequest request, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + boolean isSuperAdmin = false; + try { + isSuperAdmin = adminRolesService.isSuperAdmin(user) ; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage()); + } + return isSuperAdmin; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java index 743cbc9a..f1192f92 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -37,13 +37,15 @@ */ package org.onap.portalapp.portal.controller; +import io.swagger.annotations.ApiOperation; +import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; - +import java.util.Objects; import javax.servlet.http.HttpServletRequest; - +import lombok.NoArgsConstructor; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController; @@ -60,7 +62,6 @@ import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; -import org.onap.portalsdk.core.service.AuditService; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; @@ -81,48 +82,29 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.AsyncRestTemplate; -import io.swagger.annotations.ApiOperation; - @RestController @RequestMapping(PortalConstants.REST_AUX_API) @Configuration @EnableAspectJAutoProxy @EPAuditLog +@NoArgsConstructor public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController { - - @Autowired private ConsulHealthService consulHealthService; + private AppsCacheService appCacheService; private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api"; private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction"; private static final String CONSUL_ML_SERVICE_ID = "machine-learning"; private static final String APP_KEY = "uebkey"; - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); - private AsyncRestTemplate restTemplate = new AsyncRestTemplate(); - + private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); + private final AsyncRestTemplate restTemplate = new AsyncRestTemplate(); + private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); + private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); @Autowired - AuditService auditService; - - @Autowired - AppsCacheService appCacheService; - - SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() { - @Override - public void onSuccess(ResponseEntity<String> arg) { - logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); - } - }; - - FailureCallback failureCallback = new FailureCallback() { - @Override - public void onFailure(Throwable arg) { - logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); - } - }; - - protected boolean isAuxRESTfulCall() { - return true; + public WebAnalyticsExtAppController(AppsCacheService appCacheService, ConsulHealthService consulHealthService) { + this.appCacheService = appCacheService; + this.consulHealthService = consulHealthService; } /** @@ -132,12 +114,10 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl * @param request * HttpServletRequest * @return String - * @throws Exception - * on failure */ @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class) @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript") - public String getAnalyticsScript(HttpServletRequest request) throws Exception { + public String getAnalyticsScript(HttpServletRequest request) { String responseText = ""; EPApp app = null; String version = ""; @@ -149,31 +129,26 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl } if (app != null) { String restEndPoint = app.getAppRestEndpoint(); - if(restEndPoint.indexOf("/api")!=-1) { + if(restEndPoint.contains("/api")) { version = restEndPoint.substring(restEndPoint.indexOf("/api")+4); } } - String END_POINT = "/storeAnalytics"; + String endPoint = "/storeAnalytics"; if(StringUtils.isNotBlank(version)) { - END_POINT = version + "/storeAnalytics"; + endPoint = version + "/storeAnalytics"; } final String fileName = "analytics.txt"; - InputStream analyticsFileStream = null; - try { - analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName); - responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name()); - } catch (Exception e) { + try (InputStream analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) { + responseText = IOUtils.toString(Objects.requireNonNull(analyticsFileStream), StandardCharsets.UTF_8.name()); + } catch (IOException e) { logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e); - } finally { - if (analyticsFileStream != null) - analyticsFileStream.close(); } String feURLContext = SystemProperties.getProperty("frontend_url"); String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/')); responseText = responseText.replace("PORTAL_ENV_URL", feURL); - responseText = responseText.replace("$END_POINT", END_POINT); + responseText = responseText.replace("$END_POINT", endPoint); return responseText; } @@ -185,14 +160,11 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl * @param analyticsMap * Analytics * @return PortalAPIResponse - * @throws Exception - * on failure */ @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json") @ResponseBody @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class) - public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) - throws Exception { + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) { try { MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); String appName = ""; @@ -225,16 +197,14 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); MDC.remove(SystemProperties.MDC_TIMER); - PortalAPIResponse response = new PortalAPIResponse(true, "success"); - return response; + return new PortalAPIResponse(true, "success"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e); - PortalAPIResponse response = new PortalAPIResponse(true, "error"); - return response; + return new PortalAPIResponse(true, "error"); } } - protected String getAppName(HttpServletRequest request, String appName) { + private String getAppName(HttpServletRequest request, String appName) { EPApp appRecord = getApp(request); if (appRecord != null) { @@ -243,7 +213,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl return appName; } - protected EPApp getApp(HttpServletRequest request) { + private EPApp getApp(HttpServletRequest request) { String appKeyValue = request.getHeader(APP_KEY); EPApp appRecord = null; if (appKeyValue == null || appKeyValue.equals("")) { @@ -254,12 +224,12 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl return appRecord; } - protected void storeAuxAnalytics(Analytics analyticsMap, String appName) { + private void storeAuxAnalytics(Analytics analyticsMap, String appName) { logger.info(EELFLoggerDelegate.debugLogger, " Registering an action for recommendation: AppName/Function/UserId " + appName + "/" + analyticsMap.getFunction() + "/" + analyticsMap.getUserid()); - Map<String, String> requestMapping = new HashMap<String, String>(); + Map<String, String> requestMapping = new HashMap<>(); requestMapping.put("id", analyticsMap.getUserid()); requestMapping.put("action", appName + "|" + analyticsMap.getFunction()); @@ -267,7 +237,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl headers.setContentType(MediaType.APPLICATION_JSON); // set your entity to send - HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers); + HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMapping, headers); // send it! ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange( diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java index 6cf2ea79..0fe8a351 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/AppContactUs.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.domain; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonBackReference; @@ -46,10 +47,15 @@ public class AppContactUs extends DomainVo { private static final long serialVersionUID = -2742197830465055134L; @JsonBackReference private EPApp app; + @SafeHtml private String description; + @SafeHtml private String contactEmail; + @SafeHtml private String contactName; + @SafeHtml private String url; + @SafeHtml private String activeYN; public EPApp getApp() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java index d2ded5ad..a761103f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/CentralV2RoleFunction.java @@ -39,6 +39,7 @@ package org.onap.portalapp.portal.domain; import java.io.Serializable; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -50,14 +51,18 @@ public class CentralV2RoleFunction extends DomainVo implements Serializable, Com * */ private static final long serialVersionUID = -4018975640065252688L; + @SafeHtml private String code; + @SafeHtml private String name; @JsonIgnore private Long appId; @JsonIgnore private Long roleId; private String type; + @SafeHtml private String action; + @SafeHtml private String editUrl; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java index 6e77e747..8227d9ab 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPApp.java @@ -41,7 +41,9 @@ import java.util.Arrays; import javax.persistence.Lob; +import javax.validation.Valid; import org.apache.commons.lang.StringUtils; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; /** @@ -50,29 +52,44 @@ import org.onap.portalsdk.core.domain.support.DomainVo; public class EPApp extends DomainVo { private static final long serialVersionUID = 1L; - + @SafeHtml private String name; + @SafeHtml private String imageUrl; + @SafeHtml private String description; + @SafeHtml private String notes; + @SafeHtml private String url; + @SafeHtml private String alternateUrl; + @SafeHtml private String appRestEndpoint; + @SafeHtml private String mlAppName; + @SafeHtml private String mlAppAdminId; private Long motsId; + @SafeHtml private String username; + @SafeHtml private String appPassword; @Lob private byte[] thumbnail; private Boolean open; private Boolean enabled; + @SafeHtml private String uebTopicName; + @SafeHtml private String uebKey; + @SafeHtml private String uebSecret; private Integer appType; + @Valid private AppContactUs contactUs; private Boolean centralAuth; + @SafeHtml private String nameSpace; public EPApp() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java index f9ff97d1..55f7e0cc 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPRole.java @@ -41,6 +41,8 @@ import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -48,6 +50,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; public class EPRole extends DomainVo { private static final long serialVersionUID = 1L; + @SafeHtml private String name; private boolean active; private Integer priority; @@ -57,7 +60,7 @@ public class EPRole extends DomainVo { private Long appRoleId; // used by ONAP only private SortedSet<RoleFunction> roleFunctions = new TreeSet<RoleFunction>(); - + @Valid private SortedSet<EPRole> childRoles = new TreeSet<EPRole>(); @JsonIgnore diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java index ce7495f7..a3c9c481 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUser.java @@ -42,6 +42,8 @@ import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -52,44 +54,78 @@ public class EPUser extends User { private Long orgId; private Long managerId; + @SafeHtml private String firstName; + @SafeHtml private String middleInitial; + @SafeHtml private String lastName; + @SafeHtml private String phone; + @SafeHtml private String fax; + @SafeHtml private String cellular; + @SafeHtml private String email; private Long addressId; + @SafeHtml private String alertMethodCd; + @SafeHtml private String hrid; + @SafeHtml private String orgUserId; + @SafeHtml private String orgCode; + @SafeHtml private String address1; + @SafeHtml private String address2; + @SafeHtml private String city; + @SafeHtml private String state; + @SafeHtml private String zipCode; + @SafeHtml private String country; + @SafeHtml private String orgManagerUserId; + @SafeHtml private String locationClli; + @SafeHtml private String businessCountryCode; + @SafeHtml private String businessCountryName; + @SafeHtml private String businessUnit; + @SafeHtml private String businessUnitName; + @SafeHtml private String department; + @SafeHtml private String departmentName; + @SafeHtml private String companyCode; + @SafeHtml private String company; + @SafeHtml private String zipCodeSuffix; + @SafeHtml private String jobTitle; + @SafeHtml private String commandChain; + @SafeHtml private String siloStatus; + @SafeHtml private String costCenter; + @SafeHtml private String financialLocCode; - + @SafeHtml private String loginId; + @SafeHtml private String loginPwd; private Date lastLoginDate; private boolean active; @@ -97,15 +133,19 @@ public class EPUser extends User { private Long selectedProfileId; private Long timeZoneId; private boolean online; + @SafeHtml private String chatId; + private boolean systemUser; private Integer languageId; private static final long serialVersionUID = 1L; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUser.class); private static final String ECOMP_PORTAL_NAME = "ECOMP"; private boolean isGuest = false; - + @Valid private SortedSet<EPUserApp> userApps = new TreeSet<EPUserApp>(); + @Valid private SortedSet<EPRole> pseudoRoles = new TreeSet<EPRole>(); public EPUser() {} @@ -653,6 +693,14 @@ public class EPUser extends User { public void setGuest(boolean isGuest) { this.isGuest = isGuest; } + + public boolean isSystemUser() { + return systemUser; + } + + public void setSystemUser(boolean systemUser) { + this.systemUser = systemUser; + } @Override public String toString() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java index 3470a9e3..d644c998 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.domain; +import javax.validation.Valid; import org.onap.portalsdk.core.domain.support.DomainVo; @SuppressWarnings("rawtypes") @@ -45,7 +46,9 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara private static final long serialVersionUID = 1L; private Long userId; + @Valid private EPApp app; + @Valid private EPRole role; private Integer priority; @@ -61,13 +64,12 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara } public Long getAppRoleId() { - return (role.getAppRoleId() == null) ? null : role.getAppRoleId(); + return this.role.getAppRoleId(); } @Override public String toString() { - String str = "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]"; - return str; + return "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]"; } public Long getUserId() { @@ -102,6 +104,7 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara this.priority = priority; } + @Override public boolean equals(Object other) { if ((this == other)) return true; @@ -111,10 +114,10 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara return false; EPUserApp castOther = (EPUserApp) other; - return (this.getUserId().equals(castOther.getUserId())) - && (this.getApp().getId().equals(castOther.getApp().getId())) - && (this.getRole().getId().equals(castOther.getRole().getId())) - && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority())); + return (otherUserIdIsSameAsThisUserId(castOther)) + && (otherAppIdIsSameAsThis(castOther)) + && (otherRoleIsSameAsThis(castOther)) + && (otherPriorityIsSameAsThis(castOther)); } public int hashCode() { @@ -135,4 +138,19 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara return c1.compareTo(c2); } + private boolean otherPriorityIsSameAsThis(EPUserApp other){ + return (this.priority==null && other.getPriority()==null) || this.getPriority().equals(other.getPriority()); + } + + private boolean otherRoleIsSameAsThis(EPUserApp other){ + return this.getRole().getId().equals(other.getRole().getId()); + } + + private boolean otherAppIdIsSameAsThis(EPUserApp other){ + return this.getApp().getId().equals(other.getApp().getId()); + } + + private boolean otherUserIdIsSameAsThisUserId(EPUserApp other){ + return this.getUserId().equals(other.getUserId()); + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java index 5b5e37c4..9900827f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java @@ -38,13 +38,20 @@ package org.onap.portalapp.portal.domain; import java.util.List; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; +import javax.validation.constraints.DecimalMax; +import javax.validation.constraints.Digits; +import javax.validation.constraints.Max; +import javax.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.SafeHtml; + /*** * * This class is almost identical to org.onap.portalapp.portal.transport.FunctionalMenuItem @@ -55,27 +62,42 @@ import javax.persistence.Transient; * */ @Entity +@NoArgsConstructor +@AllArgsConstructor public class FunctionalMenuItemWithAppID{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "MENU_ID") + @Digits(integer = 11, fraction = 0) public Long menuId; @Column(name = "COLUMN_NUM") + @Digits(integer = 2, fraction = 0) + @NotNull public Integer column; @Column(name = "TEXT") + @Max(value = 100) + @SafeHtml + @NotNull public String text; @Column(name = "PARENT_MENU_ID") + @Digits(integer = 11, fraction = 0) public Integer parentMenuId; @Column(name = "URL") + @Max(value = 128) + @SafeHtml + @NotNull public String url; @Column(name="ACTIVE_YN") + @Max(value = 1) + @SafeHtml + @NotNull public String active_yn; @Column(name="APP_ID") @@ -89,10 +111,10 @@ public class FunctionalMenuItemWithAppID{ public void normalize() { if (this.column == null) - this.column = new Integer(1); + this.column = 1; this.text = (this.text == null) ? "" : this.text.trim(); if (this.parentMenuId == null) - this.parentMenuId = new Integer(-1); + this.parentMenuId = -1; this.url = (this.url == null) ? "" : this.url.trim(); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java index f62b8928..b8f79d06 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceData.java @@ -44,6 +44,8 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; public class MicroserviceData extends DomainVo { @@ -55,23 +57,23 @@ public class MicroserviceData extends DomainVo { } private Long id; - + @SafeHtml private String name; - + @SafeHtml private String active; - + @SafeHtml private String desc; private long appId; - + @SafeHtml private String url; - + @SafeHtml private String securityType; - + @SafeHtml private String username; - + @SafeHtml private String password; - + @Valid private List<MicroserviceParameter> parameterList; public Long getId() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java index 0c645716..848c6a2a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/MicroserviceParameter.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.domain; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; public class MicroserviceParameter extends DomainVo { @@ -50,9 +51,9 @@ public class MicroserviceParameter extends DomainVo { private Long id; private long serviceId; - + @SafeHtml private String para_key; - + @SafeHtml private String para_value; public Long getId() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/RoleApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/RoleApp.java index d4ca5457..cf3e06b9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/RoleApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/RoleApp.java @@ -39,90 +39,21 @@ package org.onap.portalapp.portal.domain; import java.io.Serializable; import java.util.Set; +import lombok.Getter; +import lombok.Setter; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -//@Entity -//@Table(name = "FN_ROLE") +@Getter +@Setter public class RoleApp implements Serializable{ private static final long serialVersionUID = 1L; - //@Id - //@Column(name = "ROLE_ID") - //@GeneratedValue(strategy=GenerationType.AUTO) private Long roleId; - - - //@Column(name = "ROLE_Name") - private String roleName; - - //@ManyToOne(fetch = FetchType.EAGER) - //@JoinColumn(name="APP_ID") - private App app; - - //@JsonIgnore - //@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy="widgetRoles") - private Set<WidgetCatalog> widgets; - - /*@PreRemove - private void removeGroupsFromUsers() { - for (WidgetCatalog w : widgets) { - w.getWidgetRoles().remove(this); - } - }*/ - - /*@ManyToOne - @JoinColumn(name = "WIDGET_ID", nullable = false) - WidgetCatalog widgetCatalog;*/ - - //@JsonIgnore - //@ManyToMany(mappedBy = "widgetRoles") - //@ManyToMany(fetch = FetchType.EAGER, mappedBy = "widgetRoles") - //private Set<WidgetCatalog> widgets = new HashSet<WidgetCatalog>(); - - public Long getRoleId() { - return roleId; - } - - public void setRoleId(Long roleId) { - this.roleId = roleId; - } - - public String getRoleName() { - return roleName; - } - - public void setRoleName(String roleName) { - this.roleName = roleName; - } - - public App getApp() { - return app; - } - public void setApp(App app) { - this.app = app; - } - - + private String roleName; - public Set<WidgetCatalog> getWidgets() { - return widgets; - } + private App app; - public void setWidgets(Set<WidgetCatalog> widgets) { - this.widgets = widgets; - } + private Set<WidgetCatalog> widgets; @Override public String toString() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java index b1439060..39c906a1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java @@ -40,6 +40,7 @@ package org.onap.portalapp.portal.interceptor; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.regex.Matcher; @@ -154,8 +155,8 @@ public class PortalResourceInterceptor extends ResourceInterceptor { SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); //RoleAdmin check is being added because the role belongs to partner application //inorder to access portal api's, bypassing this with isRoleAdmin Check - if ((matchRoleFunctions(portalApiPath, allRoleFunctions) - && !matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) { + if ((EPUserUtils.matchRoleFunctions(portalApiPath, allRoleFunctions) + && !EPUserUtils.matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) { logger.error(EELFLoggerDelegate.errorLogger, "preHandle: User {} not authorized for path {} ", user.getOrgUserId(), portalApiPath); @@ -246,7 +247,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor { logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}"); String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE); logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace); - Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace); + Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace, new HashMap<>()); logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed); if(accessallowed){ logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed); @@ -296,9 +297,13 @@ public class PortalResourceInterceptor extends ResourceInterceptor { }catch(ClassCastException e){ logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}"); - + String secretKey = null; // Unauthorized access due to missing HTTP Authorization request header if (authHeader == null) { + if (remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY), + request.getHeader("username"), request.getHeader("password"))) { + return true; + } final String msg = "no authorization found"; logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg); sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg); @@ -396,42 +401,6 @@ public class PortalResourceInterceptor extends ResourceInterceptor { return result; } - private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) { - String[] path = portalApiPath.split("/"); - List<String> roleFunList = new ArrayList<>(); - if (path.length > 1) { - roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList()); - if (roleFunList.size() >= 1) { - for (String roleFunction : roleFunList) { - String[] roleFunctionArray = roleFunction.split("/"); - boolean b = true; - if (roleFunctionArray.length == path.length) { - for (int i = 0; i < roleFunctionArray.length; i++) { - if (b) { - if (!roleFunctionArray[i].equals("*")) { - Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(roleFunctionArray[i]); - b = m.matches(); - - } - } - } - if (b) - return b; - } - } - } - } else { - for (String roleFunction : roleFunctions) { - if (portalApiPath.matches(roleFunction)) - return true; - } - } - return false; - } - - - protected void handleSessionUpdates(HttpServletRequest request) { PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java index 891da3b7..4805a77d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java @@ -43,8 +43,8 @@ import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; -import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.client.FourLetterWordMain; import org.hibernate.Query; import org.hibernate.Session; @@ -61,6 +61,7 @@ import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.transaction.annotation.Transactional; @@ -68,19 +69,14 @@ import org.springframework.transaction.annotation.Transactional; @Transactional -@org.springframework.context.annotation.Configuration +@Configuration @EnableAspectJAutoProxy @EPMetricsLog +@NoArgsConstructor public class HealthMonitor { - - - ZooKeeper zookeeper = null; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class); - - @Autowired - private SessionFactory sessionFactory; - + private Thread healthMonitorThread; + private static SessionFactory sessionFactory; private static boolean databaseUp; private static boolean uebUp; @@ -89,50 +85,17 @@ public class HealthMonitor { private static boolean dbPermissionsOk; private static boolean zookeeperStatusOk; private static boolean cassandraStatusOk; - private static String APPLICATION = "Portal"; - - /** - * Read directly by external classes. - */ - public static boolean isSuspended = false; - - private Thread healthMonitorThread; - - public HealthMonitor() { - } - - public static boolean isDatabaseUp() { - return databaseUp; - } - - public static boolean isDatabasePermissionsOk() { - return dbPermissionsOk; - } + private static String application = "Portal"; + private static boolean isSuspended = false; - public static boolean isUebUp() { - return uebUp; - } - - public static boolean isFrontEndUp() { - return frontEndUp; - } - - public static boolean isBackEndUp() { - return backEndUp; - } - - public static boolean isZookeeperStatusOk() { - return zookeeperStatusOk; - } - - public static boolean isCassandraStatusOk() { - return cassandraStatusOk; + @Autowired + public HealthMonitor(SessionFactory sessionFactory) { + HealthMonitor.sessionFactory = sessionFactory; } - private void monitorEPHealth() throws InterruptedException { + private static void monitorEPHealth() { int numIntervalsDatabaseHasBeenDown = 0; - int numIntervalsClusterNotHealthy = 0; int numIntervalsDatabasePermissionsIncorrect = 0; int numIntervalsZookeeperNotHealthy = 0; int numIntervalsCassandraNotHealthy = 0; @@ -141,9 +104,9 @@ public class HealthMonitor { long sleepInterval = (Long - .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000); + .parseLong(SystemProperties.getProperty(EPCommonSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000); long numIntervalsBetweenAlerts = Long - .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS)); + .parseLong(SystemProperties.getProperty(EPCommonSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS)); logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: Polling health every " + sleepInterval + " milliseconds. Alerting every " + (sleepInterval * numIntervalsBetweenAlerts) / 1000 + " seconds when component remains down."); @@ -154,8 +117,8 @@ public class HealthMonitor { // // Get DB status. If down, signal alert once every X intervals. // - databaseUp = this.checkIfDatabaseUp(); - if (databaseUp == false) { + databaseUp = checkIfDatabaseUp(); + if (databaseUp) { if ((numIntervalsDatabaseHasBeenDown % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: database down, logging to error log to trigger alert."); @@ -167,8 +130,8 @@ public class HealthMonitor { } } - dbPermissionsOk = this.checkDatabasePermissions(); - if (dbPermissionsOk == false) { + dbPermissionsOk = checkDatabasePermissions(); + if (!dbPermissionsOk) { if ((numIntervalsDatabasePermissionsIncorrect % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: database permissions incorrect, logging to error log to trigger alert."); @@ -178,12 +141,11 @@ public class HealthMonitor { numIntervalsDatabasePermissionsIncorrect = 0; } } - org.onap.portalapp.music.util.MusicUtil MusicUtilSDK = new org.onap.portalapp.music.util.MusicUtil(); - if(MusicUtilSDK.isMusicEnable()){ + if(org.onap.portalapp.music.util.MusicUtil.isMusicEnable()){ - zookeeperStatusOk = this.checkZookeeperStatus(); + zookeeperStatusOk = checkZookeeperStatus(); - if (zookeeperStatusOk == false) { + if (!zookeeperStatusOk) { if ((numIntervalsZookeeperNotHealthy % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); @@ -194,8 +156,8 @@ public class HealthMonitor { } } - cassandraStatusOk = this.checkCassandraStatus(); - if (cassandraStatusOk == false) { + cassandraStatusOk = checkCassandraStatus(); + if (!cassandraStatusOk) { if ((numIntervalsCassandraNotHealthy % numIntervalsBetweenAlerts) == 0) { logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); @@ -206,45 +168,9 @@ public class HealthMonitor { } } } - - - // - // Get UEB status. Publish a bogus message to EP inbox, if 200 OK - // returned, status is Up. - // If down, signal alert once every X intervals. - // EP will ignore this bogus message. - // Commenting this out as Dependency on UEB is being deprecated - /* - * uebUp = this.checkIfUebUp(); if (uebUp == false) { - * - * if ((numIntervalsUebHasBeenDown % numIntervalsBetweenAlerts) == 0) { - * logger.debug(EELFLoggerDelegate.debugLogger, - * "monitorEPHealth: UEB down, logging to error log to trigger alert"); // Write - * a Log entry that will generate an alert EPLogUtil.logEcompError(logger, - * EPAppMessagesEnum.BeHealthCheckUebClusterError); - * numIntervalsUebHasBeenDown++; } else { numIntervalsUebHasBeenDown = 0; } } - */ - - // The front end should be up because the API is called through - // proxy front end server. frontEndUp = true; - - // If the rest API called, the backend is always up backEndUp = true; - // - // future nice to have...get Partner status - // - // For all apps exposing a rest url, query one of the rest - // urls(/roles?) and manage a list - // of app name/status. We might not return back a non 200 OK in - // health check, but we - // could return information in the json content of a health check. - // - - // - // Get DB status. If down, signal alert once every X intervals. - // if (Thread.interrupted()) { logger.info(EELFLoggerDelegate.errorLogger, "monitorEPHealth: thread interrupted"); break; @@ -262,12 +188,11 @@ public class HealthMonitor { @PostConstruct public void initHealthMonitor() { healthMonitorThread = new Thread("EP HealthMonitor thread") { + @Override public void run() { try { monitorEPHealth(); - } catch (InterruptedException e) { - logger.debug(EELFLoggerDelegate.debugLogger, "healthMonitorThread interrupted", e); - } + } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "healthMonitorThread failed", e); } @@ -292,7 +217,7 @@ public class HealthMonitor { * * @return true if the database can be read. */ - private boolean checkIfDatabaseUp() { + private static boolean checkIfDatabaseUp() { boolean isUp = false; Session localSession = null; try { @@ -316,25 +241,26 @@ public class HealthMonitor { return isUp; } - private boolean checkZookeeperStatus() { + private static boolean checkZookeeperStatus() { String[] zookeeperNodes = MusicUtil.getMyZkHost().split(","); logger.info(EELFLoggerDelegate.applicationLogger, "MusicUtil.getMyZkHost()---- :" + MusicUtil.getMyZkHost()); - for (int i = 0; i < zookeeperNodes.length; i++) { + for (String zookeeperNode : zookeeperNodes) { try { - logger.info(EELFLoggerDelegate.applicationLogger, "server ip--zookeeper :" + zookeeperNodes[i].trim()); - String[] iport = zookeeperNodes[i].split(":"); + logger.info(EELFLoggerDelegate.applicationLogger, "server ip--zookeeper :" + zookeeperNode.trim()); + String[] iport = zookeeperNode.split(":"); String zkNodeStatistics = FourLetterWordMain.send4LetterWord(iport[0].trim(), - Integer.parseInt(iport[1].trim()), "stat"); + Integer.parseInt(iport[1].trim()), "stat"); logger.info(EELFLoggerDelegate.applicationLogger, - "Getting Status for Zookeeper zkNodeStatistics :" + zkNodeStatistics); + "Getting Status for Zookeeper zkNodeStatistics :" + zkNodeStatistics); if (StringUtils.isNotBlank(zkNodeStatistics)) { String state = zkNodeStatistics.substring(zkNodeStatistics.indexOf("Mode:"), - zkNodeStatistics.indexOf("Node")); + zkNodeStatistics.indexOf("Node")); logger.info(EELFLoggerDelegate.applicationLogger, - "Getting Status for zookeeper :" + zookeeperNodes[i].trim() + ":------:" + state); - if (state.contains("leader")) + "Getting Status for zookeeper :" + zookeeperNode.trim() + ":------:" + state); + if (state.contains("leader") || state.contains("follower")) { return true; + } } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "ZookeeperStatus Service is not responding", e.getCause()); @@ -345,9 +271,9 @@ public class HealthMonitor { } - public boolean checkCassandraStatus() { + private static boolean checkCassandraStatus() { logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra"); - if (this.getAdminKeySpace()) { + if (getAdminKeySpace()) { return true; } else { logger.error(EELFLoggerDelegate.errorLogger, "Cassandra Service is not responding"); @@ -355,17 +281,18 @@ public class HealthMonitor { } } - private Boolean getAdminKeySpace() { + private static Boolean getAdminKeySpace() { String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE); Instant creationTime = Instant.now(); PreparedQueryObject pQuery = new PreparedQueryObject(); pQuery.appendQueryString( "UPDATE " + musicKeySpace + ".health_check SET creation_time = ? WHERE primary_id = ?"); pQuery.addValue(creationTime.toString()); - pQuery.addValue(APPLICATION); + pQuery.addValue(application); try { MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.CRITICAL); } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getErrorMessage(), e); return Boolean.FALSE; } return Boolean.TRUE; @@ -373,7 +300,7 @@ public class HealthMonitor { } - private boolean checkDatabasePermissions() { + private static boolean checkDatabasePermissions() { boolean isUp = false; Session localSession = null; try { @@ -391,7 +318,7 @@ public class HealthMonitor { break; } } - if (isUp == false) { + if (!isUp) { logger.error(EELFLoggerDelegate.errorLogger, "checkDatabasePermissions returning false. SHOW GRANTS FOR CURRENT_USER being dumped:"); for (String str : grantsList) { @@ -412,5 +339,40 @@ public class HealthMonitor { } return isUp; } - + + public static boolean isDatabaseUp() { + return databaseUp; + } + + public static boolean isUebUp() { + return uebUp; + } + + public static boolean isFrontEndUp() { + return frontEndUp; + } + + public static boolean isBackEndUp() { + return backEndUp; + } + + public static boolean isDbPermissionsOk() { + return dbPermissionsOk; + } + + public static boolean isZookeeperStatusOk() { + return zookeeperStatusOk; + } + + public static boolean isCassandraStatusOk() { + return cassandraStatusOk; + } + + public static boolean isSuspended() { + return isSuspended; + } + + public static void setSuspended(boolean isSuspended) { + HealthMonitor.isSuspended = isSuspended; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java index aa97d0b3..7dbcc025 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/UserSessionListener.java @@ -109,7 +109,8 @@ public class UserSessionListener implements HttpSessionListener { // Clean the shared context each time a session is destroyed. // TODO: move the threshold to configuration file. - getSharedContextService().expireSharedContexts(60 * 60 * 8); + //June2019:Commented as sharedContext is no more needed. +// getSharedContextService().expireSharedContexts(60 * 60 * 8); } logger.info(EELFLoggerDelegate.debugLogger, "Session Destroyed : " + session.getId()); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java index cc371719..098846f0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInt.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -38,23 +40,15 @@ package org.onap.portalapp.portal.scheduler; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; public class SchedulerRestInt { /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The request date format. */ - public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); - + public SchedulerRestInt() { - requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + DateUtil.getRequestDateFormat().setTimeZone(java.util.TimeZone.getTimeZone("GMT")); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java index ce2048b2..c1ca8735 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerUtil.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -37,25 +39,21 @@ */ package org.onap.portalapp.portal.scheduler; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.portalapp.portal.scheduler.restobjects.GetTimeSlotsRestObject; import org.onap.portalapp.portal.scheduler.restobjects.PostCreateNewVnfRestObject; import org.onap.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject; import org.onap.portalapp.portal.scheduler.wrapper.GetTimeSlotsWrapper; import org.onap.portalapp.portal.scheduler.wrapper.PostCreateNewVnfWrapper; import org.onap.portalapp.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Date; public class SchedulerUtil { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerUtil.class); - - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); public static GetTimeSlotsWrapper getTimeSlotsWrapResponse (GetTimeSlotsRestObject<String> rs) { @@ -127,8 +125,10 @@ public class SchedulerUtil { r_json_str = mapper.writeValueAsString(t); } catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); - } + logger.debug(EELFLoggerDelegate.debugLogger, + DateUtil.getDateFormat().format(new Date()) + "<== " + methodName + " Unable " + "to " + + "parse object as json"); + } } return (r_json_str); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java index 14b03478..17dc3f1e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -39,9 +41,6 @@ package org.onap.portalapp.portal.scheduler.client; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - import javax.servlet.ServletContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -64,10 +63,6 @@ public class HttpBasicClient{ /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpBasicClient.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** * Obtain a basic HTTP client . * diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java index 857bec31..d618a6ee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -39,7 +41,6 @@ package org.onap.portalapp.portal.scheduler.client; import java.io.File; -import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @@ -55,8 +56,8 @@ import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.util.CustomJacksonJaxBJsonProvider; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; /** * General SSL client using the VID tomcat keystore. It doesn't use client certificates. @@ -66,10 +67,7 @@ public class HttpsBasicClient{ /** The logger. */ static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsBasicClient.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + /** * Retrieve an SSL client. * @@ -85,11 +83,14 @@ public class HttpsBasicClient{ SSLContext ctx = null; try { - + + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); String truststore_path = SchedulerProperties.getProperty(SchedulerProperties.VID_TRUSTSTORE_FILENAME); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " truststore_path=" + truststore_path); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " " + + "truststore_path=" + + truststore_path); String truststore_password = SchedulerProperties.getProperty(SchedulerProperties.VID_TRUSTSTORE_PASSWD_X); @@ -97,7 +98,8 @@ public class HttpsBasicClient{ //logger.debug(dateFormat.format(new Date()) + " " + methodName + " decrypted_truststore_password=" + decrypted_truststore_password); File tr = new File (truststore_path); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute truststore path=" + tr.getAbsolutePath()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute " + + "truststore path=" + tr.getAbsolutePath()); //String keystore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_FILENAME); //String keystore_password = SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_PASSWD_X); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java index 1785bd13..75919eee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInt.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -38,11 +40,11 @@ package org.onap.portalapp.portal.scheduleraux; -import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import com.fasterxml.jackson.databind.ObjectMapper; @@ -51,15 +53,9 @@ public class SchedulerAuxRestInt { /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The request date format. */ - public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); - + public SchedulerAuxRestInt() { - requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + DateUtil.getRequestDateFormat().setTimeZone(java.util.TimeZone.getTimeZone("GMT")); } /** @@ -68,6 +64,7 @@ public class SchedulerAuxRestInt { * @param r the r */ public void logRequest ( RequestDetails r ) { + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); String methodName = "logRequest"; ObjectMapper mapper = new ObjectMapper(); String r_json_str = ""; @@ -77,9 +74,13 @@ public class SchedulerAuxRestInt { r_json_str = mapper.writeValueAsString(r); } catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " " + + "Unable to " + + "parse request as json"); } } - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=" + + "(" + + r_json_str + ")"); } -}
\ No newline at end of file +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java index e0a2fe5f..01a52cc8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -37,19 +39,13 @@ */ package org.onap.portalapp.portal.scheduleraux; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; - -import javax.annotation.PostConstruct; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; import org.apache.commons.codec.binary.Base64; import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.eclipse.jetty.util.security.Password; @@ -59,26 +55,26 @@ import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.client.HttpBasicClient; import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails; +import org.onap.portalapp.util.DateUtil; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import java.lang.reflect.Type; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc { /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class); - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** The client. */ private static Client client = null; @@ -147,6 +143,7 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc String methodName = "Get"; logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName); + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); String url = ""; restObject.set(t); @@ -165,8 +162,8 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc if (status == 200) { t = (T) cres.readEntity(t.getClass()); restObject.set(t); - logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", dateFormat.format(new Date()), - methodName); + logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", + dateFormat.format(new Date()), methodName); } else { throw new Exception(methodName + " with status=" + status + ", url= " + url); @@ -183,6 +180,7 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc String methodName = "Delete"; String url = ""; Response cres = null; + SimpleDateFormat dateFormat = DateUtil.getDateFormat(); logRequest(r); @@ -191,7 +189,7 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path; logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ", - dateFormat.format(new Date()), url, methodName); + dateFormat.format(new Date()), url, methodName); cres = client.target(url).request().accept("application/json").headers(commonHeaders) // .entity(r) @@ -235,8 +233,8 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc url, e); EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", dateFormat.format(new Date()), - methodName, url, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", + dateFormat.format(new Date()), methodName, url, e); EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); throw e; @@ -324,4 +322,4 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc public void logRequest(RequestDetails r) { // TODO Auto-generated method stub } -}
\ No newline at end of file +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java index 4a4c9283..f0f0af5a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -37,18 +39,13 @@ */ package org.onap.portalapp.portal.scheduleraux; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - import org.glassfish.jersey.client.ClientResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; public class SchedulerAuxUtil { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxUtil.class); - - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + public static SchedulerAuxResponseWrapper wrapResponse ( String body, int statusCode ) { SchedulerAuxResponseWrapper w = new SchedulerAuxResponseWrapper(); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java index a9d55fc8..3c228dff 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesService.java @@ -38,10 +38,12 @@ package org.onap.portalapp.portal.service; import java.util.List; +import java.util.Set; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.exceptions.RoleFunctionException; import org.onap.portalapp.portal.transport.AppsListWithAdminRole; public interface AdminRolesService { @@ -78,4 +80,7 @@ public interface AdminRolesService { List<EPRole> getRolesByApp(EPUser user, Long appId); public boolean isAccountAdminOfApplication(EPUser user, EPApp app); + public Set<String> getAllAppsFunctionsOfUser(String OrgUserId)throws RoleFunctionException; + + boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java index c8e04f4f..18aac6f4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -63,6 +65,7 @@ import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EPUserApp; import org.onap.portalapp.portal.domain.UserIdRoleId; import org.onap.portalapp.portal.domain.UserRole; +import org.onap.portalapp.portal.exceptions.RoleFunctionException; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; @@ -75,6 +78,7 @@ import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.domain.RoleFunction; +import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.restful.domain.EcompRole; import org.onap.portalsdk.core.service.DataAccessService; @@ -143,9 +147,9 @@ public class AdminRolesServiceImpl implements AdminRolesService { try { userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getEPUserByOrgUserId failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "getEPUserByOrgUserId failed", e); } - + HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>(); if (userList!= null && userList.size() > 0) { EPUser user = userList.get(0); @@ -166,8 +170,10 @@ public class AdminRolesServiceImpl implements AdminRolesService { appsListWithAdminRole.orgUserId = orgUserId; List<EPApp> appsList = null; try { - appsList = dataAccessService.getList(EPApp.class, - " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null); +// appsList = dataAccessService.getList(EPApp.class, +// null, null, null); + + appsList = dataAccessService.getList(EPApp.class, null); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e); EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); @@ -200,9 +206,9 @@ public class AdminRolesServiceImpl implements AdminRolesService { List<EPApp> apps = appsService.getAppsFullList(); HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>(); for (EPApp app : apps) { - if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) { +// if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) { enabledApps.put(app.getId(), app); - } +// } } List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>(); for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) { @@ -265,7 +271,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { // Add user admin role for list of centralized applications in external system addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin); result = true; - } + } } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); logger.error(EELFLoggerDelegate.errorLogger, @@ -444,12 +450,14 @@ public class AdminRolesServiceImpl implements AdminRolesService { public boolean isAccountAdmin(EPUser user) { try { - EPUser currentUser = user != null - ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) - : null; - + if (user == null) { + return false; + } + + EPUser currentUser = (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null); + final Map<String, Long> userParams = new HashMap<>(); - userParams.put("userId", user.getId()); + userParams.put("userId", user.getId()); logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId()); List<Integer> userAdminApps = new ArrayList<>(); @@ -460,7 +468,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { if (currentUser != null && currentUser.getId() != null) { for (EPUserApp userApp : currentUser.getEPUserApps()) { - + if (userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)||(userAdminApps.size()>1)) { logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found Id {}", user.getOrgUserId(), userApp.getRole().getId()); // Account Administrator sees only the applications @@ -476,19 +484,14 @@ public class AdminRolesServiceImpl implements AdminRolesService { } return false; } - - + + public boolean isRoleAdmin(EPUser user) { try { logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access"); - EPUser currentUser = user != null - ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) - : null; final Map<String, Long> userParams = new HashMap<>(); - userParams.put("userId", user.getId()); - List<RoleFunction> roleFunctionSet = new ArrayList<>(); - + userParams.put("userId", user.getId()); List getRoleFuncListOfUser = dataAccessService.executeNamedQuery("getRoleFunctionsOfUserforAlltheApplications", userParams, null); logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser" , getRoleFuncListOfUser); Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser); @@ -497,26 +500,15 @@ public class AdminRolesServiceImpl implements AdminRolesService { roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet()); if (roleFunSet.size() > 0) for (String roleFunction : roleFunSet) { - //String roleFun = EcompPortalUtils.getFunctionCode(roleFunction); - String roleFun = EcompPortalUtils.getFunctionCode(roleFunction); String type = externalAccessRolesService.getFunctionCodeType(roleFunction); - //getRoleFuncListOfPortalSet.remove(roleFunction); getRoleFuncListOfPortalSet1.add(type); } - - - for (String rolefunc : getRoleFuncListOfPortalSet1) { - logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , rolefunc); - if (rolefunc.equalsIgnoreCase(TYPE_APPROVER)) { - logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , rolefunc); - return true; - }else{ - return false; - - } - } - + boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream() + .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver")); + logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , checkIfFunctionsExits); + + return checkIfFunctionsExits; } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); @@ -568,13 +560,61 @@ public class AdminRolesServiceImpl implements AdminRolesService { Boolean isApplicationAccountAdmin=false; try { final Map<String, Long> userParams = new HashMap<>(); - userParams.put("userId", user.getId()); + userParams.put("userId", user.getId()); logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId()); List<Integer> userAdminApps = new ArrayList<>(); userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null); if(userAdminApps.size()>=1){ isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId()); logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId()); + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isAccountAdminOfApplication operation", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, user.getOrgUserId()); + return isApplicationAccountAdmin; + + } + + @Override + public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException { + final Map<String, String> params = new HashMap<>(); + params.put("userId", OrgUserId); + List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getAllAppsFunctionsOfUser", params, null); + Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal); + Set<String> roleFunSet = new HashSet<>(); + roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet()); + if (roleFunSet.size() > 0) + for (String roleFunction : roleFunSet) { + String roleFun = EcompPortalUtils.getFunctionCode(roleFunction); + getRoleFuncListOfPortalSet.remove(roleFunction); + getRoleFuncListOfPortalSet.add(roleFun); + } + + Set<String> finalRoleFunctionSet = new HashSet<>(); + for (String roleFn : getRoleFuncListOfPortalSet) { + finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn)); + } + +// List<String> functionsOfUser = new ArrayList<>(getRoleFuncListOfPortal); + return finalRoleFunctionSet; + } + + + @Override + public boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app) { + Boolean isApplicationAccountAdmin=false; + try { + final Map<String, Long> userParams = new HashMap<>(); + userParams.put("userId", user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId()); + List<Integer> userAdminApps = new ArrayList<>(); + userAdminApps =dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null); + if(userAdminApps.size()>=1){ + isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId()); } } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java index fd6610c2..18dabfb5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java @@ -4,6 +4,8 @@ * =================================================================== * Copyright (C) 2017-2018 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"); @@ -378,7 +380,7 @@ public class ApplicationsRestClientServiceImpl implements ApplicationsRestClient String str = ((ResponseImpl)response).readEntity(String.class); EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str); try { - t = (T) gson.fromJson(str, t.getClass()); + t = (T) gson.fromJson(str, clazz); //t = gson.fromJson(str, clazz); } catch (Exception e) { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java index 5c3c51bf..c3cc2864 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -48,6 +50,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletResponse; @@ -58,12 +61,13 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; +import org.json.JSONArray; +import org.json.JSONObject; import org.onap.portalapp.portal.domain.AdminUserApp; import org.onap.portalapp.portal.domain.AdminUserApplications; import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel; import org.onap.portalapp.portal.domain.AppsResponse; import org.onap.portalapp.portal.domain.EPApp; -import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EPUserAppRolesRequest; import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail; @@ -95,6 +99,13 @@ import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; @@ -109,7 +120,9 @@ public class EPAppCommonServiceImpl implements EPAppService { protected String ACCOUNT_ADMIN_ROLE_ID = "999"; protected String RESTRICTED_APP_ROLE_ID = "900"; - private static final String urlField = "url"; + //private static final String urlField = "url"; + private static final String nameSpaceField = "url"; + private static final String nameField = "name"; private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class); @@ -120,6 +133,8 @@ public class EPAppCommonServiceImpl implements EPAppService { protected SessionFactory sessionFactory; @Autowired private DataAccessService dataAccessService; + + RestTemplate template = new RestTemplate(); @PostConstruct private void init() { @@ -128,6 +143,65 @@ public class EPAppCommonServiceImpl implements EPAppService { ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID); RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID); } + + public Boolean onboardingAppFieldsValidation(OnboardingApp onboardingApp) { + //FieldsValidator fieldsValidator = new FieldsValidator(); + + if ((!onboardingApp.restrictedApp) &&( onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.restrictedApp == null + || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.restUrl == null || onboardingApp.restUrl.length() == 0 + || onboardingApp.username == null || onboardingApp.username.length() == 0 + || onboardingApp.isOpen == null + || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))) + // For a normal app (appType == PortalConstants.PortalAppId), + // these fields must be filled + // in. + // For a restricted app (appType==2), they will be empty. + || ((onboardingApp.restrictedApp) && (onboardingApp.name == null || onboardingApp.name.length() == 0 + || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.isOpen == null))) { + return false; + } + return true; + + } + + private Boolean onboardingInactiveAppFieldsForValidation(OnboardingApp onboardingApp) { + if (onboardingApp.name == null || onboardingApp.name.length() == 0 + || onboardingApp.isOpen == null) { + return false; + } + return true; + } + + protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) { + FieldsValidator fieldsValidator = new FieldsValidator(); + if (onboardingApp.isCentralAuth) { + if (!onboardingApp.isEnabled) { + if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + } else if (onboardingApp.isEnabled) { + if (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.nameSpace == null + || onboardingApp.nameSpace.length() == 0) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + } + } else { + if (!onboardingApp.isEnabled) { + if (!onboardingInactiveAppFieldsForValidation(onboardingApp)) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + } else if (onboardingApp.isEnabled) { + if(onboardingApp.restrictedApp && onboardingAppFieldsValidation(onboardingApp) == false){ + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + else if (!onboardingApp.restrictedApp && (onboardingAppFieldsValidation(onboardingApp) == false || onboardingApp.appPassword == null + || onboardingApp.appPassword.length() == 0)) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + } + } + return fieldsValidator; + } @Override public List<EPApp> getUserAsAdminApps(EPUser user) { @@ -405,6 +479,23 @@ public class EPAppCommonServiceImpl implements EPAppService { return appsModified; } + + @Override + public List<AppsResponse> getAllApplications(Boolean all) { + // If all is true, return both active and inactive apps. Otherwise, just + // active apps. + @SuppressWarnings("unchecked") + // Sort the list by application name so the drop-down looks pretty. + List<EPApp> apps = all + ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null) + :dataAccessService.getList(EPApp.class, null); + + List<AppsResponse> appsModified = new ArrayList<AppsResponse>(); + for (EPApp app : apps) { + appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled())); + } + return appsModified; + } @Override public UserRoles getUserProfile(String loginId) { final Map<String, String> params = new HashMap<>(); @@ -487,13 +578,13 @@ public class EPAppCommonServiceImpl implements EPAppService { return query.toString(); } - protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) { + /*protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) { FieldsValidator fieldsValidator = new FieldsValidator(); if(onboardingApp.isCentralAuth){ if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null || onboardingApp.isOpen == null || onboardingApp.isEnabled == null - || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)) + || (onboardingApp.id != null && ECOMP_APP_ID.equals(onboardingApp.id.toString())) // For a normal app (appType == PortalConstants.PortalAppId), // these fields must be filled // in. @@ -509,7 +600,7 @@ public class EPAppCommonServiceImpl implements EPAppService { if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null || onboardingApp.isOpen == null || onboardingApp.isEnabled == null - || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)) + || (onboardingApp.id != null && ECOMP_APP_ID.equals(onboardingApp.id.toString())) // For a normal app (appType == PortalConstants.PortalAppId), // these fields must be filled // in. @@ -525,7 +616,7 @@ public class EPAppCommonServiceImpl implements EPAppService { } return fieldsValidator; - } + }*/ @Override public List<EPApp> getUserApps(EPUser user) { @@ -738,6 +829,27 @@ public class EPAppCommonServiceImpl implements EPAppService { } return onboardingAppsList; } + + @SuppressWarnings("unchecked") + @Override + public List<OnboardingApp> getAdminAppsOfUser(EPUser user) { + + List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>(); + List<Integer> userAdminApps = new ArrayList<>(); + final Map<String, Long> userParams = new HashMap<>(); + userParams.put("userId", user.getId()); + userAdminApps = dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null); + +// userAdminApps.removeIf(x -> x == Integer.valueOf(ECOMP_APP_ID)); + + logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size()); + onboardingAppsList = getOnboardingApps(); + + final List<Integer> userAdminApps1 = userAdminApps; + List<OnboardingApp> userApplicationAdmins = onboardingAppsList.stream().filter(x -> userAdminApps1.contains((int) (long)x.id)).collect(Collectors.toList()); + + return userApplicationAdmins; + } @Override public List<OnboardingApp> getEnabledNonOpenOnboardingApps() { @@ -756,25 +868,33 @@ public class EPAppCommonServiceImpl implements EPAppService { @SuppressWarnings("unchecked") private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) { - boolean duplicatedUrl = false; + boolean duplicatedNameSpace = false; boolean duplicatedName = false; List<EPApp> apps; if (onboardingApp.id == null) { List<Criterion> restrictionsList = new ArrayList<Criterion>(); - Criterion urlCrit =Restrictions.eq("url", onboardingApp.url); - Criterion nameCrit = Restrictions.eq("name",onboardingApp.name); - Criterion orCrit = Restrictions.or(urlCrit, nameCrit); - + Criterion nameCrit = Restrictions.eq("name",onboardingApp.name); + Criterion nameSpaceCrit = null; + Criterion orCrit = null; + if (onboardingApp.isCentralAuth) { + nameSpaceCrit = Restrictions.eq("nameSpace", onboardingApp.nameSpace); + orCrit = Restrictions.or(nameCrit, nameSpaceCrit); + } else + orCrit = Restrictions.or(nameCrit); restrictionsList.add(orCrit); apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null); - - } else { List<Criterion> restrictionsList = new ArrayList<Criterion>(); Criterion idCrit =Restrictions.eq("id", onboardingApp.id); - Criterion urlCrit =Restrictions.eq("url", onboardingApp.url); - Criterion nameCrit = Restrictions.eq("name",onboardingApp.name); - Criterion orCrit = Restrictions.or(idCrit, urlCrit, nameCrit); + Criterion nameCrit = Restrictions.eq("name",onboardingApp.name); + Criterion nameSpaceCrit = null; + Criterion orCrit= null; + if (onboardingApp.isCentralAuth) { + nameSpaceCrit = Restrictions.eq("nameSpace",onboardingApp.nameSpace); + orCrit = Restrictions.or(idCrit, nameSpaceCrit, nameCrit); + } + else + orCrit = Restrictions.or(idCrit, nameCrit); restrictionsList.add(orCrit); apps = (List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null); @@ -784,22 +904,23 @@ public class EPAppCommonServiceImpl implements EPAppService { if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) { continue; } - if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) { - duplicatedUrl = true; + if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) { + duplicatedName = true; if (duplicatedName) { break; } } - if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) { - duplicatedName = true; - if (duplicatedUrl) { + if (!duplicatedNameSpace && app.getNameSpace().equalsIgnoreCase(onboardingApp.nameSpace)) { + duplicatedNameSpace = true; + if (duplicatedNameSpace) { break; } } + } - if (duplicatedUrl || duplicatedName) { - if (duplicatedUrl) { - fieldsValidator.addProblematicFieldName(urlField); + if (duplicatedNameSpace || duplicatedName) { + if (duplicatedNameSpace) { + fieldsValidator.addProblematicFieldName(nameSpaceField); } if (duplicatedName) { fieldsValidator.addProblematicFieldName(nameField); @@ -1494,7 +1615,7 @@ public class EPAppCommonServiceImpl implements EPAppService { // Don't encrypt or decrypt the password if it is null or the empty string private String decryptedPassword(String encryptedAppPwd, EPApp app) { String result = ""; - if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) { + if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) { try { result = CipherUtil.decryptPKC(encryptedAppPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); @@ -1507,7 +1628,7 @@ public class EPAppCommonServiceImpl implements EPAppService { protected String encryptedPassword(String decryptedAppPwd, EPApp app) { String result = ""; - if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) { + if (decryptedAppPwd != null && !decryptedAppPwd.isEmpty()) { try { result = CipherUtil.encryptPKC(decryptedAppPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); @@ -1800,4 +1921,57 @@ public class EPAppCommonServiceImpl implements EPAppService { return userAndRoles; } -}
\ No newline at end of file + + @SuppressWarnings("unused") + @Override + public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system for : "+namespace); + ResponseEntity<String> response = null; + try { + response = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "nss/" + namespace, HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists for"+ namespace , + response.getStatusCode().value()); + if (response.getStatusCode().value() == 200) { + String res = response.getBody(); + JSONObject jsonObj = new JSONObject(res); + JSONArray namespaceArray = jsonObj.getJSONArray("ns"); + if(!namespaceArray.getJSONObject(0).has("admin")){ + logger.error(EELFLoggerDelegate.errorLogger, + "No admins are available for requested namespace:" + namespace); + throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED, + "Portal Mechid is not an admin of" + namespace); + } + + JSONArray namespaceAdminArray = namespaceArray.getJSONObject(0).getJSONArray("admin"); + ArrayList<String> list = new ArrayList<String>(); + if (namespaceAdminArray != null) { + int len = namespaceAdminArray.length(); + for (int i = 0; i < len; i++) { + list.add(namespaceAdminArray.get(i).toString()); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "List of Admins of requested namespace" + list); + final String userName = SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME); + boolean idExists = list.stream().anyMatch(t -> userName.equals(t)); + if (false) { + logger.error(EELFLoggerDelegate.errorLogger, + "Portal mechid is not admin of requested namespace:" + namespace); + throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED, + "Portal Mechid is not an admin of" + namespace); + } + } + + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } + return response; + + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java index b314adec..6838ae4a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppService.java @@ -54,6 +54,7 @@ import org.onap.portalapp.portal.transport.EPWidgetsSortPreference; import org.onap.portalapp.portal.transport.FieldsValidator; import org.onap.portalapp.portal.transport.LocalRole; import org.onap.portalapp.portal.transport.OnboardingApp; +import org.springframework.http.ResponseEntity; public interface EPAppService { @@ -244,5 +245,10 @@ public interface EPAppService { UserRoles getUserProfileForRolesLeftMenu(String loginId); UserRoles getUserProfileNormalizedForRolesLeftMenu(EPUser user); + public List<OnboardingApp> getAdminAppsOfUser(EPUser user); + + public ResponseEntity<String> checkIfNameSpaceIsValid(String namespace) throws Exception ; + + List<AppsResponse> getAllApplications(Boolean all); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java index ef3cb5ad..c1dba221 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLdapService.java @@ -40,7 +40,7 @@ package org.onap.portalapp.portal.service; import org.onap.portalsdk.core.command.support.SearchResult; import org.onap.portalsdk.core.domain.support.DomainVo; - +@FunctionalInterface public interface EPLdapService { // search POST for users based on the criteria selected in the Request diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java index ee960c40..d064545d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java @@ -416,13 +416,6 @@ public interface ExternalAccessRolesService { public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception; /** - * It encodes the function code based on Hex encoding - * @param funCode - * - */ - public String encodeFunctionCode(String funCode); - - /** * * It returns list of ExternalRoleDetails which is converted from JSON array of roles * 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 7bb9995b..786ad429 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 @@ -47,11 +47,9 @@ import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -113,3742 +111,3682 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @EPMetricsLog @EPAuditLog public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService { - private static final String APP_ROLE_NAME_PARAM = "appRoleName"; - private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem"; - private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles"; - private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction"; - private static final String FUNCTION_CODE_PARAMS = "functionCode"; - private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '"; - private static final String OWNER = ".owner"; - private static final String ADMIN = ".admin"; - private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator"; - private static final String FUNCTION_PIPE = "|"; - private static final String EXTERNAL_AUTH_PERMS = "perms"; - private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description"; - private static final String IS_EMPTY_JSON_STRING = "{}"; - private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system"; - private static final String APP_ID = "appId"; - private static final String ROLE_NAME = "name"; - private static final String APP_ID_EQUALS = " app_id = "; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class); - @Autowired - private DataAccessService dataAccessService; - @Autowired - private EPAppService epAppService; - @Autowired - private SessionFactory sessionFactory; - @Autowired - EPRoleService ePRoleService; - RestTemplate template = new RestTemplate(); - // These decode values are based on HexDecoder - static final String decodeValueOfForwardSlash = "2f"; - static final String decodeValueOfHiphen = "2d"; - static final String decodeValueOfStar = "2a"; - - @SuppressWarnings("unchecked") - @Override - public List<EPRole> getAppRoles(Long appId) throws Exception { - List<EPRole> applicationRoles = null; - final Map<String, Long> appParams = new HashMap<>(); - try { - if (appId == 1) { - applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null); - } else { - appParams.put("appId", appId); - applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e); - throw e; - } - return applicationRoles; - } - - @SuppressWarnings("unchecked") - @Override - public List<EPApp> getApp(String uebkey) throws Exception { - List<EPApp> app = null; - try { - final Map<String, String> appUebkeyParams = new HashMap<>(); - appUebkeyParams.put("appKey", uebkey); - app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null); - if (!app.isEmpty() && !app.get(0).getEnabled() - && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { - throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable"); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e); - throw e; - } - return app; - } - - /** - * It returns single application role from external auth system - * - * @param addRole - * @param app - * @return JSON string which contains application role details - * @throws Exception - */ - private String getSingleAppRole(String addRole, EPApp app) throws Exception { - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - ResponseEntity<String> response = null; - logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system"); - response = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" - + app.getNameSpace() + "." + addRole - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), - HttpMethod.GET, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", - response.getStatusCode().value()); - return response.getBody(); - } - - @Override - public boolean addRole(Role addRole, String uebkey) throws Exception { - boolean response = false; - ResponseEntity<String> addResponse = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - EPApp app = getApp(uebkey).get(0); - String newRole = updateExistingRoleInExternalSystem(addRole, app); - HttpEntity<String> entity = new HttpEntity<>(newRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system"); - addResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", - HttpMethod.POST, entity, String.class); - if (addResponse.getStatusCode().value() == 201) { - response = true; - logger.debug(EELFLoggerDelegate.debugLogger, - "addRole: Finished adding role in the External Auth system and response code: {} ", - addResponse.getStatusCode().value()); - } - if (addResponse.getStatusCode().value() == 406) { - logger.error(EELFLoggerDelegate.errorLogger, - "addRole: Failed to add in the External Auth system due to {} and status code: {}", - addResponse.getBody(), addResponse.getStatusCode().value()); - } - return response; - } - - /** - * - * It deletes record in external auth system - * - * @param delRole - * @return JSON String which has status code and response body - * @throws Exception - */ - private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception { - ResponseEntity<String> delResponse = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(delRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole); - delResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true", - HttpMethod.DELETE, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", - delRole, delResponse.getStatusCode().value()); - return delResponse; - } - - /** - * It updates role in external auth system - * - * @param updateExtRole - * @param app - * @return true if success else false - * @throws Exception If updateRoleInExternalSystem fails we catch it in logger for detail message - */ - private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception { - boolean response = false; - ObjectMapper mapper = new ObjectMapper(); - ResponseEntity<String> deleteResponse = null; - List<EPRole> epRoleList = null; - if (app.getId().equals(PortalConstants.PORTAL_APP_ID) - || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { - epRoleList = getPortalAppRoleInfo(updateExtRole.getId()); - } else { - epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app); - } - // Assigning functions to global role - if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { - List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); - EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID); - addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo); - response = true; - } else { - String appRole = getSingleAppRole(epRoleList.get(0).getName(), app); - List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); - if (!appRole.equals(IS_EMPTY_JSON_STRING)) { - JSONObject jsonObj = new JSONObject(appRole); - JSONArray extRole = jsonObj.getJSONArray("role"); - if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { - String roleName = extRole.getJSONObject(0).getString(ROLE_NAME); - Map<String, String> delRoleKeyMapper = new HashMap<>(); - delRoleKeyMapper.put(ROLE_NAME, roleName); - String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper); - deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue); - if (deleteResponse.getStatusCode().value() != 200) { - throw new ExternalAuthSystemException(deleteResponse.getBody()); - } - addRole(updateExtRole, app.getUebKey()); - } else { - String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); - String name = extRole.getJSONObject(0).getString(ROLE_NAME); - List<ExternalAccessPerms> list = new ArrayList<>(); - if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) { - JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS); - list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance() - .constructCollectionType(List.class, ExternalAccessPerms.class)); - } - // If role name or role functions are updated then delete - // record in External System and add new record to avoid - // conflicts - boolean isRoleNameChanged = false; - if (!desc.equals(updateExtRole.getName())) { - isRoleNameChanged = true; - 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); - } - 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); - } - // Delete role in External System if role is inactive - if (!updateExtRole.getActive()) { - deleteRoleInExtSystem(mapper, name); - } - if (!isRoleNameChanged) { - response = - addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list); - } - } - } else { - // It seems like role exists in local DB but not in External - // Access system - if (updateExtRole.getActive()) { - addRole(updateExtRole, app.getUebKey()); - ExternalAccessRolePerms extAddRolePerms = null; - ExternalAccessPerms extAddPerms = null; - List<RoleFunction> 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<String> deleteResponse; - Map<String, String> 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<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception { - boolean response; - Map<String, RoleFunction> updateRoleFunc = new HashMap<>(); - for (RoleFunction addPerm : roleFunctionListNew) { - updateRoleFunc.put(addPerm.getCode(), addPerm); - } - final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>(); - final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>(); - list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())); - // Update permissions in the ExternalAccess System - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - if (!list.isEmpty()) { - for (ExternalAccessPerms perm : list) { - RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1) - + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction()); - if (roleFunc == null) { - RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance()); - if (roleFuncPipeFilter == null) - removePermForRole(perm, mapper, name, headers); - } - extRolePermMap.put(perm.getInstance(), perm); - extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE - + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm); - } - } - response = true; - if (!roleFunctionListNew.isEmpty()) { - for (RoleFunction roleFunc : roleFunctionListNew) { - if (roleFunc.getCode().contains(FUNCTION_PIPE)) { - ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode()); - if (perm == null) { - response = - addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers, roleFunc); - } - } else { - if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) { - response = - addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers, roleFunc); - } - } - } - } - return response; - } - - /* - * Adds function to the role in the external auth system while editing a role or updating new - * functions to a role - * - */ - private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper, - HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException { - boolean response; - ExternalAccessRolePerms extRolePerms; - ExternalAccessPerms extPerms; - String code = ""; - String type = ""; - String action = ""; - if (roleFunc.getCode().contains(FUNCTION_PIPE)) { - code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - type = EcompPortalUtils.getFunctionType(roleFunc.getCode()); - action = getFunctionCodeAction(roleFunc.getCode()); - } else { - code = roleFunc.getCode(); - type = roleFunc.getCode().contains("menu") ? "menu" : "url"; - action = "*"; - } - extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action); - extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String updateRolePerms = mapper.writeValueAsString(extRolePerms); - HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity<String> 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, - "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}", - addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); - } else { - response = true; - logger.debug(EELFLoggerDelegate.debugLogger, - "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", - updateRolePerms, addResponse.getStatusCode().value()); - } - return response; - } - - private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper, - EPApp app, Role updateExtRole) throws Exception { - for (ExternalAccessPerms perm : permslist) { - if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) { - ExternalAccessRolePerms extAddGlobalRolePerms = null; - ExternalAccessPerms extAddPerms = null; - extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction()); - extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms, - app.getNameSpace() + "." + updateExtRole.getName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(addPerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - try { - ResponseEntity<String> addResponse = template - .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/perm", HttpMethod.POST, entity, String.class); - if (addResponse.getStatusCode().value() != 201) { - logger.debug(EELFLoggerDelegate.debugLogger, - "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}", - addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, - "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ", - addResponse.getStatusCode().value()); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e); - } - } - } - } - - @SuppressWarnings("unchecked") - private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, - List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo) - throws Exception { - try { - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole"); - // GET Permissions from External Auth System - JSONArray extPerms = getExtAuthPermissions(app); - List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms); - final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>(); - final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>(); - final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>(); - final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>(); - for (ExternalAccessPermsDetail permDetail : permsDetailList) { - existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail); - existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail); - } - // Add If function does not exists for role in External Auth System - for (RoleFunction roleFunc : roleFunctionListNew) { - String roleFuncCode = ""; - ExternalAccessPermsDetail permsDetail; - if (roleFunc.getCode().contains(FUNCTION_PIPE)) { - roleFuncCode = roleFunc.getCode(); - permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode()); - } else { - roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - permsDetail = existingPermsWithRoles.get(roleFuncCode); - } - if (null == permsDetail.getRoles() - || !permsDetail.getRoles() - .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE - + epRoleList.get(0).getName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, - "_"))) { - addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo); - } - userRquestedFunctionsMap.put(roleFuncCode, roleFunc); - userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc); - } - // Delete functions if exists in External Auth System but not in - // incoming - // request - final Map<String, Long> epAppRoleFuncParams = new HashMap<>(); - epAppRoleFuncParams.put("requestedAppId", app.getId()); - epAppRoleFuncParams.put("roleId", updateExtRole.getId()); - List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = - dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null); - for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) { - String globalRoleFuncWithoutPipes = ""; - RoleFunction roleFunc = null; - if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) { - globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd(); - roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes); - } else { - globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd()); - roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes); - } - if (roleFunc == null) { - ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) - ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) - : existingPermsWithRoles.get(globalRoleFuncWithoutPipes); - ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), - EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), - permDetailFromMap.getAction()); - String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - removePermForRole(perm, mapper, roleName, headers); - } - } - logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e); - throw e; - } - } - - private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, - ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception { - try { - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem"); - ExternalAccessRolePerms extAddRolePerms = null; - ExternalAccessPerms extAddPerms = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - String code = ""; - String type = ""; - String action = ""; - if (addFunction.getCode().contains(FUNCTION_PIPE)) { - code = EcompPortalUtils.getFunctionCode(addFunction.getCode()); - type = getFunctionCodeType(addFunction.getCode()); - action = getFunctionCodeAction(addFunction.getCode()); - } else { - code = addFunction.getCode(); - type = addFunction.getCode().contains("menu") ? "menu" : "url"; - action = "*"; - } - extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action); - extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole - .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String updateRolePerms = mapper.writeValueAsString(extAddRolePerms); - HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity<String> addResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", - HttpMethod.POST, entity, String.class); - if (addResponse.getStatusCode().value() != 201) { - 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 { - logger.debug(EELFLoggerDelegate.debugLogger, - "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", - addResponse.getStatusCode().value()); - } - logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e); - throw e; - } - } - - private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms, - HttpHeaders headers) throws JsonProcessingException { - boolean response; - String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); - HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity<String> 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; - } - - /** - * - * It converts list of functions in updateExtRole parameter to the RoleFunction object - * - * @param updateExtRole - * @return list of functions - */ - @SuppressWarnings("unchecked") - private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) { - Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions(); - List<RoleFunction> roleFunctionList = new ArrayList<>(); - ObjectMapper roleFuncMapper = new ObjectMapper(); - Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); - RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class); - roleFunctionList.add(roleFunction); - } - return roleFunctionList.stream().distinct().collect(Collectors.toList()); - } - - /** - * It delete permissions/functions in the external auth system - * - * @param perm - * @param permMapper - * @param name - * @param headers - * @throws JsonProcessingException - * @throws Exception - */ - private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers) - throws ExternalAuthSystemException, JsonProcessingException { - ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name); - String permDetails = permMapper.writeValueAsString(extAccessRolePerms); - try { - HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails); - ResponseEntity<String> deletePermResponse = - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class); - if (deletePermResponse.getStatusCode().value() != 200) { - throw new ExternalAuthSystemException(deletePermResponse.getBody()); - } - logger.debug(EELFLoggerDelegate.debugLogger, - "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}", - permDetails, deletePermResponse.getStatusCode().value()); - } catch (Exception e) { - if (e.getMessage().contains("404")) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", - permDetails, e.getMessage()); - } else { - throw e; - } - } - } - - /** - * It will create new role in the External Auth System - * - * @param newRole - * @param app - * @return true if successfully added in the system else false - * @throws Exception If fails to add role in the system - */ - private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) - throws Exception, HttpClientErrorException { - try { - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - ObjectMapper mapper = new ObjectMapper(); - String addNewRole = ""; - ExternalAccessRole extRole = new ExternalAccessRole(); - extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - extRole.setDescription(String.valueOf(newRole.get(0).getName())); - addNewRole = mapper.writeValueAsString(extRole); - HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole); - ResponseEntity<String> addNewRoleInExternalSystem = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", - HttpMethod.POST, postEntity, String.class); - if (addNewRoleInExternalSystem.getStatusCode().value() == 201) { - logger.debug(EELFLoggerDelegate.debugLogger, - "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}", - addNewRole, addNewRoleInExternalSystem.getStatusCode().value()); - } - } catch (HttpClientErrorException ht) { - dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null); - logger.error(EELFLoggerDelegate.debugLogger, - "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht); - throw new HttpClientErrorException(ht.getStatusCode()); - } - } - - /** - * - * It updates existing role in the External Auth System - * - * @param addRole It Contains role information - * @param app - * @return string which is formatted to match with the external auth system - * @throws JsonProcessingException - */ - private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - String addNewRole = ""; - ExternalAccessRole extRole = new ExternalAccessRole(); - extRole.setName(app.getNameSpace() + "." + addRole.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - extRole.setDescription(String.valueOf(addRole.getName())); - addNewRole = mapper.writeValueAsString(extRole); - return addNewRole; - } - - /** - * It create a role in the external auth system and then in our local - * - * @param addRoleInDB - * @param app - * @return true else false - * @throws Exception - */ - @SuppressWarnings("unchecked") - @Transactional(rollbackFor = Exception.class) - public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { - boolean result = false; - EPRole epRole = null; - Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions(); - List<RoleFunction> roleFunctionListNew = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); - RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); - roleFunctionListNew.add(roleFunction); - } - List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList()); - try { - if (addRoleInDB.getId() == null) { // check if it is new role - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - checkIfRoleExitsInExternalSystem(addRoleInDB, app); - } - EPRole epRoleNew = new EPRole(); - epRoleNew.setActive(addRoleInDB.getActive()); - epRoleNew.setName(addRoleInDB.getName()); - epRoleNew.setPriority(addRoleInDB.getPriority()); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epRoleNew.setAppId(null); - } else { - epRoleNew.setAppId(app.getId()); - } - dataAccessService.saveDomainObject(epRoleNew, null); - List<EPRole> getRoleCreated = null; - final Map<String, String> epAppRoleParams = new HashMap<>(); - final Map<String, String> epAppPortalRoleParams = new HashMap<>(); - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epAppRoleParams.put("appId", String.valueOf(app.getId())); - epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName()); - List<EPRole> roleCreated = dataAccessService - .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null); - EPRole epUpdateRole = roleCreated.get(0); - epUpdateRole.setAppRoleId(epUpdateRole.getId()); - dataAccessService.saveDomainObject(epUpdateRole, null); - getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, - epAppRoleParams, null); - } else { - epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName()); - getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, - epAppPortalRoleParams, null); - } - // Add role in External Auth system - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - addNewRoleInExternalSystem(getRoleCreated, app); - } - result = true; - } else { // if role already exists then update it - EPRole globalRole = null; - List<EPRole> applicationRoles; - List<EPRole> globalRoleList = getGlobalRolesOfPortal(); - boolean isGlobalRole = false; - if (!globalRoleList.isEmpty()) { - EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny() - .orElse(null); - if (role != null) { - globalRole = role; - isGlobalRole = true; - } - } - if (app.getId().equals(PortalConstants.PORTAL_APP_ID) - || (globalRole != null && app.getId() != globalRole.getAppId())) { - applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId()); - } else { - applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app); - } - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole); - // Add all user to the re-named role in external auth system - if (!applicationRoles.isEmpty() - && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) { - bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(), - addRoleInDB.getName()); - } - } - deleteRoleFunction(app, applicationRoles); - if (!applicationRoles.isEmpty()) { - epRole = applicationRoles.get(0); - epRole.setName(addRoleInDB.getName()); - epRole.setPriority(addRoleInDB.getPriority()); - epRole.setActive(addRoleInDB.getActive()); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epRole.setAppId(null); - epRole.setAppRoleId(null); - } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) - && applicationRoles.get(0).getAppRoleId() == null) { - epRole.setAppRoleId(epRole.getId()); - } - dataAccessService.saveDomainObject(epRole, null); - } - Long roleAppId = null; - if (globalRole != null && !app.getId().equals(globalRole.getAppId())) - roleAppId = PortalConstants.PORTAL_APP_ID; - saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId); - result = true; - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e); - throw e; - } - return result; - } - - /** - * - * It validates whether role exists in external auth system - * - * @param checkRole - * @param app - * @throws Exception If role exits - */ - private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception { - getNameSpaceIfExists(app); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - String roleName = app.getNameSpace() + "." + checkRole.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"); - HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity<String> checkRoleInExternalSystem = - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/" + roleName, HttpMethod.GET, checkRoleEntity, String.class); - if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) { - logger.debug( - "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", - checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value()); - throw new ExternalAuthSystemException(" Role already exists in external system"); - } - } - - /** - * It saves list of functions to the role in portal - * - * @param roleFunctionListNew - * @param app - * @param applicationRoles - * @throws Exception - */ - @SuppressWarnings("unchecked") - private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles, - Long roleAppId) throws Exception { - final Map<String, String> getAppFunctionParams = new HashMap<>(); - for (RoleFunction roleFunc : roleFunctionListNew) { - String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - EPAppRoleFunction appRoleFunc = new EPAppRoleFunction(); - appRoleFunc.setAppId(app.getId()); - appRoleFunc.setRoleId(applicationRoles.get(0).getId()); - appRoleFunc.setRoleAppId(String.valueOf(roleAppId)); - getAppFunctionParams.put("appId", String.valueOf(app.getId())); - getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); - // query to check if function code has pipes - List<CentralV2RoleFunction> roleFunction = - dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null); - if (roleFunction.isEmpty()) { - getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code); - roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null); - } - if (roleFunction.size() > 1) { - CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction); - appRoleFunc.setCode(getExactFunctionCode.getCode()); - } else { - appRoleFunc.setCode(roleFunction.get(0).getCode()); - } - dataAccessService.saveDomainObject(appRoleFunc, null); - } - } - - /** - * - * It filters the app functions which starts with similar name in the result set - * - * @param roleFunc - * @param roleFunction - * @return CentralRoleFunction - */ - private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) { - final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>(); - final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>(); - CentralV2RoleFunction getExactFunctionCode = null; - for (CentralV2RoleFunction cenRoleFunction : roleFunction) { - appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction); - appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction); - } - getExactFunctionCode = appFunctionsFilter.get(roleFuncCode); - if (getExactFunctionCode == null) { - getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode); - } - return getExactFunctionCode; - } - - /** - * It deletes all EPAppRoleFunction records in the portal - * - * @param app - * @param role - */ - @SuppressWarnings("unchecked") - private void deleteRoleFunction(EPApp app, List<EPRole> role) { - final Map<String, Long> appRoleFuncsParams = new HashMap<>(); - appRoleFuncsParams.put("appId", app.getId()); - appRoleFuncsParams.put("roleId", role.get(0).getId()); - List<EPAppRoleFunction> appRoleFunctionList = - dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null); - if (!appRoleFunctionList.isEmpty()) { - for (EPAppRoleFunction approleFunction : appRoleFunctionList) { - dataAccessService.deleteDomainObject(approleFunction, null); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public List<EPUser> getUser(String loginId) throws InvalidUserException { - final Map<String, String> userParams = new HashMap<>(); - userParams.put("org_user_id", loginId); - List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null); - if (userList.isEmpty()) { - throw new InvalidUserException("User not found"); - } - return userList; - } - - @Override - public String getV2UserWithRoles(String loginId, String uebkey) throws Exception { - final Map<String, String> params = new HashMap<>(); - List<EPUser> userList = null; - CentralV2User cenV2User = null; - String result = null; - try { - params.put("orgUserIdValue", loginId); - List<EPApp> appList = getApp(uebkey); - if (!appList.isEmpty()) { - userList = getUser(loginId); - if (!userList.isEmpty()) { - ObjectMapper mapper = new ObjectMapper(); - cenV2User = getV2UserAppRoles(loginId, uebkey); - result = mapper.writeValueAsString(cenV2User); - } else if (userList.isEmpty()) { - throw new InvalidUserException("User not found"); - } - } else { - throw new InactiveApplicationException("Application not found"); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e); - throw e; - } - return result; - } - - @Override - public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception { - logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp"); - List<CentralV2Role> roleList = new ArrayList<>(); - final Map<String, Long> params = new HashMap<>(); - try { - List<EPApp> app = getApp(uebkey); - List<EPRole> appRolesList = getAppRoles(app.get(0).getId()); - roleList = createCentralRoleObject(app, appRolesList, roleList, params); - if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) { - List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId()); - List<EPRole> globalRolesList = getGlobalRolesOfPortal(); - List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>(); - if (!globalRolesList.isEmpty()) { - for (EPRole eprole : globalRolesList) { - CentralV2Role cenRole = convertRoleToCentralV2Role(eprole); - portalsGlobalRolesFinlaList.add(cenRole); - } - roleList.addAll(globalRoleList); - for (CentralV2Role role : portalsGlobalRolesFinlaList) { - CentralV2Role result = - roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny().orElse(null); - if (result == null) - roleList.add(role); - } - } else { - for (EPRole role : globalRolesList) { - CentralV2Role cenRole = convertRoleToCentralV2Role(role); - roleList.add(cenRole); - } - } - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e); - throw e; - } - logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!"); - return roleList.stream().distinct().collect(Collectors.toList()); - } - - @SuppressWarnings("unchecked") - @Override - public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - List<CentralV2RoleFunction> finalRoleList = new ArrayList<>(); - final Map<String, Long> params = new HashMap<>(); - params.put(APP_ID, app.getId()); - List<CentralV2RoleFunction> getRoleFuncList = - dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); - for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) { - String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode()); - String type = ""; - if (roleFuncItem.getCode().contains("|")) - type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode()); - else - type = getFunctionCodeType(roleFuncItem.getCode()); - String action = getFunctionCodeAction(roleFuncItem.getCode()); - roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code)); - roleFuncItem.setType(type); - roleFuncItem.setAction(action); - finalRoleList.add(roleFuncItem); - } - return finalRoleList; - } - - @Override - public String getFunctionCodeAction(String roleFuncItem) { - return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem); - } - - @Override - public String getFunctionCodeType(String roleFuncItem) { - String type = null; - if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu")) - || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) { - type = "menu"; - } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem) - || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) { - type = "url"; - } else if (roleFuncItem.contains(FUNCTION_PIPE) - && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) { - type = EcompPortalUtils.getFunctionType(roleFuncItem); - } - return type; - } - - /** - * - * It check whether function code has no pipes and no url string in it - * - * @param roleFuncItem - * @return true or false - */ - private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) { - return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url"); - } - - /** - * - * It check whether function code has pipes and url string in it - * - * @param roleFuncItem - * @return true or false - */ - private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) { - return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url"); - } - - /** - * - * It check whether function code has no pipes and has url string in it - * - * @param roleFuncItem - * @return true or false - */ - private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) { - return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url"); - } - - /** - * It returns user detail information which is deep copy of EPUser.class object - * - * @param userInfo - * @param userAppSet - * @param app - * @return - * @throws Exception - */ - @SuppressWarnings("unchecked") - private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception { - final Map<String, Long> params = new HashMap<>(); - CentralV2User userAppList = new CentralV2User(); - CentralV2User user1 = null; - final Map<String, Long> params1 = new HashMap<>(); - List<EPRole> globalRoleList = new ArrayList<>(); - try { - if (app.getId() != PortalConstants.PORTAL_APP_ID) { - params1.put("userId", userInfo.getId()); - params1.put("appId", app.getId()); - globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null); - } - userAppList.setUserApps(new TreeSet<CentralV2UserApp>()); - for (EPUserApp userApp : userAppSet) { - if (userApp.getRole().getActive()) { - EPApp epApp = userApp.getApp(); - String globalRole = userApp.getRole().getName().toLowerCase(); - if (((epApp.getId().equals(app.getId())) - && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))) - || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) - && (globalRole.toLowerCase().startsWith("global_")))) { - CentralV2UserApp cua = new CentralV2UserApp(); - cua.setUserId(null); - CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(), - epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(), - epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(), - epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(), - epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(), - String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()), - epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(), - epApp.getUebTopicName()); - cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); - cua.setApp(cenApp); - Long appId = null; - if (globalRole.toLowerCase().startsWith("global_") - && epApp.getId().equals(PortalConstants.PORTAL_APP_ID) - && !epApp.getId().equals(app.getId())) { - appId = app.getId(); - EPRole result = null; - if (globalRoleList.size() > 0) - result = globalRoleList.stream() - .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny() - .orElse(null); - if (result == null) - continue; - } else { - appId = userApp.getApp().getId(); - } - params.put("roleId", userApp.getRole().getId()); - params.put(APP_ID, appId); - List<CentralV2RoleFunction> appRoleFunctionList = - dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet<CentralV2RoleFunction> 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, type, action, null); - roleFunctionSet.add(cenRoleFunc); - } - Long userRoleId = null; - if (globalRole.toLowerCase().startsWith("global_") - || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) { - userRoleId = userApp.getRole().getId(); - } else { - userRoleId = userApp.getRole().getAppRoleId(); - } - CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(), - userApp.getRole().getModified(), userApp.getRole().getCreatedId(), - userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(), - userApp.getRole().getName(), userApp.getRole().getActive(), - userApp.getRole().getPriority(), roleFunctionSet, null, null); - cua.setRole(cenRole); - userAppList.getUserApps().add(cua); - } - } - } - user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(), - userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(), - userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(), - userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(), - userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(), - userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(), - userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(), - userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(), - userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(), - userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(), - userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(), - userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(), - userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(), - userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(), - userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e); - throw e; - } - return user1; - } - - @Override - public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception { - final Map<String, Long> params = new HashMap<>(); - List<CentralV2Role> roleList = new ArrayList<>(); - CentralV2Role cenRole = new CentralV2Role(); - List<EPRole> roleInfo = null; - List<EPApp> app = null; - try { - app = getApp(uebkey); - if (app.isEmpty()) { - throw new InactiveApplicationException("Application not found"); - } - if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) { - List<EPRole> globalRoleList = new ArrayList<>(); - globalRoleList = getGlobalRolesOfPortal(); - if (globalRoleList.size() > 0) { - EPRole result = - globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny().orElse(null); - if (result != null) - return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId); - } - } - if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { - roleInfo = getPortalAppRoleInfo(roleId); - } else { - roleInfo = getPartnerAppRoleInfo(roleId, app.get(0)); - } - roleList = createCentralRoleObject(app, roleInfo, roleList, params); - if (roleList.isEmpty()) { - return cenRole; - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e); - throw e; - } - return roleList.get(0); - } - - @SuppressWarnings("unchecked") - private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) { - List<EPRole> roleInfo; - final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); - getPartnerAppRoleParams.put("appRoleId", roleId); - getPartnerAppRoleParams.put("appId", app.getId()); - roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null); - if (roleInfo.isEmpty()) { - getPartnerAppRoleParams.put("appRoleId", roleId); - roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null); - } - return roleInfo; - } - - @SuppressWarnings("unchecked") - private List<EPRole> getPortalAppRoleInfo(Long roleId) { - List<EPRole> roleInfo; - final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); - getPortalAppRoleParams.put("roleId", roleId); - roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null); - return roleInfo; - } - - /** - * - * It returns list of app roles along with role functions and which went through deep copy - * - * @param app - * @param roleInfo - * @param roleList - * @param params - * @return - * @throws DecoderException - */ - @SuppressWarnings("unchecked") - @Override - public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo, - List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException { - for (EPRole role : roleInfo) { - params.put("roleId", role.getId()); - params.put(APP_ID, app.get(0).getId()); - List<CentralV2RoleFunction> cenRoleFuncList = - dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>(); - for (CentralV2RoleFunction roleFunc : cenRoleFuncList) { - String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - functionCode = EPUserUtils.decodeFunctionCode(functionCode); - String type = getFunctionCodeType(roleFunc.getCode()); - String action = getFunctionCodeAction(roleFunc.getCode()); - CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode, - roleFunc.getName(), null, type, action, null); - roleFunctionSet.add(cenRoleFunc); - } - SortedSet<CentralV2Role> childRoles = new TreeSet<>(); - SortedSet<CentralV2Role> parentRoles = new TreeSet<>(); - CentralV2Role cenRole = null; - if (role.getAppRoleId() == null) { - cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), - role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(), - roleFunctionSet, childRoles, parentRoles); - } else { - cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(), - role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), - role.getPriority(), roleFunctionSet, childRoles, parentRoles); - } - roleList.add(cenRole); - } - return roleList; - } - - @SuppressWarnings("unchecked") - @Override - public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception { - String code = EcompPortalUtils.getFunctionCode(functionCode); - String encodedCode = encodeFunctionCode(code); - CentralV2RoleFunction roleFunc = null; - EPApp app = getApp(uebkey).get(0); - List<CentralV2RoleFunction> getRoleFuncList = null; - final Map<String, String> params = new HashMap<>(); - try { - params.put(FUNCTION_CODE_PARAMS, functionCode); - params.put(APP_ID, String.valueOf(app.getId())); - getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); - if (getRoleFuncList.isEmpty()) { - params.put(FUNCTION_CODE_PARAMS, encodedCode); - getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); - if (getRoleFuncList.isEmpty()) { - return roleFunc; - } - } - if (getRoleFuncList.size() > 1) { - CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList); - if (cenV2RoleFunction == null) - return roleFunc; - roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction); - } else { - // 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); - throw e; - } - return roleFunc; - } - - private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) { - CentralV2RoleFunction roleFunc; - String functionCodeFormat = getRoleFuncList.getCode(); - if (functionCodeFormat.contains(FUNCTION_PIPE)) { - String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat); - String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat); - String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat); - roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat, - getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, - newfunctionActionFormat, getRoleFuncList.getEditUrl()); - } else { - roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(), - getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl()); - } - return roleFunc; - } - - @Override - public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) - throws Exception { - boolean saveOrUpdateFunction = false; - try { - domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode())); - final Map<String, String> functionParams = new HashMap<>(); - functionParams.put("appId", String.valueOf(app.getId())); - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - addRoleFunctionInExternalSystem(domainCentralRoleFunction, app); - } - if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) { - domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE - + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction()); - } - domainCentralRoleFunction.setAppId(app.getId()); - dataAccessService.saveDomainObject(domainCentralRoleFunction, null); - saveOrUpdateFunction = true; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e); - throw e; - } - return saveOrUpdateFunction; - } - - /** - * It creates application permission in external auth system - * - * @param domainCentralRoleFunction - * @param app - * @throws Exception - */ - private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) - throws Exception { - ObjectMapper mapper = new ObjectMapper(); - ExternalAccessPerms extPerms = new ExternalAccessPerms(); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - String type = ""; - String instance = ""; - String action = ""; - if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) - || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) { - type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) - ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) - : domainCentralRoleFunction.getType(); - instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) - ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) - : domainCentralRoleFunction.getCode(); - action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) - ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) - : domainCentralRoleFunction.getAction(); - } else { - type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; - instance = domainCentralRoleFunction.getCode(); - action = "*"; - } - // get Permissions from External Auth System - JSONArray extPermsList = getExtAuthPermissions(app); - List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList); - String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action; - boolean checkIfFunctionsExits = - permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm)); - if (!checkIfFunctionsExits) { - try { - extPerms.setAction(action); - extPerms.setInstance(instance); - extPerms.setType(app.getNameSpace() + "." + type); - extPerms.setDescription(domainCentralRoleFunction.getName()); - String addFunction = mapper.writeValueAsString(extPerms); - HttpEntity<String> entity = new HttpEntity<>(addFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); - ResponseEntity<String> addPermResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", - HttpMethod.POST, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "addRoleFunctionInExternalSystem: 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, - "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e); - throw e; - } - } else { - try { - extPerms.setAction(action); - extPerms.setInstance(instance); - extPerms.setType(app.getNameSpace() + "." + type); - extPerms.setDescription(domainCentralRoleFunction.getName()); - String updateRoleFunction = mapper.writeValueAsString(extPerms); - HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction); - ResponseEntity<String> updatePermResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", - HttpMethod.PUT, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", - updateRoleFunction, updatePermResponse.getStatusCode().value()); - } 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, - "addRoleFunctionInExternalSystem: Failed to update function in external central auth system", - e); - throw e; - } - } - } - - @SuppressWarnings("unchecked") - @Override - @Transactional(rollbackFor = Exception.class) - public boolean deleteCentralRoleFunction(String code, EPApp app) { - boolean deleteFunctionResponse = false; - try { - final Map<String, String> params = new HashMap<>(); - params.put(FUNCTION_CODE_PARAMS, code); - params.put(APP_ID, String.valueOf(app.getId())); - List<CentralV2RoleFunction> domainCentralRoleFunction = - dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); - CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction); - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - deleteRoleFunctionInExternalSystem(appFunctionCode, app); - // Delete role function dependency records - deleteAppRoleFunctions(appFunctionCode.getCode(), app); - } - dataAccessService.deleteDomainObject(appFunctionCode, null); - deleteFunctionResponse = true; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e); - } - return deleteFunctionResponse; - } - - /** - * It deletes app function record in portal - * - * @param code - * @param app - */ - private void deleteAppRoleFunctions(String code, EPApp app) { - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, - APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null); - } - - /** - * - * It deletes permission in the external auth system - * - * @param domainCentralRoleFunction - * @param app - * @throws Exception - */ - private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) - throws Exception { - try { - ObjectMapper mapper = new ObjectMapper(); - ExternalAccessPerms extPerms = new ExternalAccessPerms(); - String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()); - String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode()); - String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode()); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - extPerms.setAction(actionValue); - extPerms.setInstance(instanceValue); - extPerms.setType(app.getNameSpace() + "." + checkType); - extPerms.setDescription(domainCentralRoleFunction.getName()); - String deleteRoleFunction = mapper.writeValueAsString(extPerms); - HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction); - ResponseEntity<String> delPermResponse = - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "perm?force=true", HttpMethod.DELETE, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ", - deleteRoleFunction, delPermResponse.getStatusCode().value()); - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "HttpClientErrorException - Failed to delete functions in External System", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("404 Not Found")) { - logger.debug(EELFLoggerDelegate.debugLogger, - " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB", - e.getMessage()); - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e); - } - } - } - - @Override - public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception { - boolean response = false; - String message = ""; - try { - EPApp app = getApp(uebkey).get(0); - addRoleInEcompDB(saveRole, app); - response = true; - } catch (Exception e) { - message = e.getMessage(); - logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e); - } - return new ExternalRequestFieldsValidator(response, message); - } - - @SuppressWarnings("unchecked") - @Override - public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception { - Session localSession = sessionFactory.openSession(); - Transaction transaction = null; - boolean result = false; - try { - List<EPRole> epRoleList = null; - EPApp app = getApp(uebkey).get(0); - final Map<String, String> deleteRoleParams = new HashMap<>(); - deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null); - } else { - deleteRoleParams.put(APP_ID, String.valueOf(app.getId())); - epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, - deleteRoleParams, null); - } - if (!epRoleList.isEmpty()) { - transaction = localSession.beginTransaction(); - // Delete app role functions before deleting role - deleteRoleFunction(app, epRoleList); - if (app.getId() == 1) { - // Delete fn_user_ role - dataAccessService.deleteDomainObjects(EPUserApp.class, - APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); - boolean isPortalRequest = false; - deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest); - } - deleteRoleInExternalAuthSystem(epRoleList, app); - transaction.commit(); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction"); - dataAccessService.deleteDomainObject(epRoleList.get(0), null); - } - result = true; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e); - result = false; - } finally { - localSession.close(); - } - return result; - } - - /** - * - * It deletes role for application in external auth system - * - * @param epRoleList contains role information - * @param app contains application information - * @throws Exception - */ - private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception { - ResponseEntity<String> deleteResponse; - ResponseEntity<String> res = getNameSpaceIfExists(app); - if (res.getStatusCode() == HttpStatus.OK) { - // Delete Role in External System - 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) { - EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode()); - logger.error(EELFLoggerDelegate.errorLogger, - "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ", - deleteResponse.getBody()); - } - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction"); - } - } - - /** - * - * It deletes application user role in external auth system - * - * @param role - * @param app - * @param LoginId - * @throws Exception - */ - private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception { - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - getNameSpaceIfExists(app); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity<String> getResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" - + LoginId - + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) - + "/" + app.getNameSpace() + "." - + role.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), - HttpMethod.GET, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, - "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", - getResponse.getBody()); - if (getResponse.getStatusCode().value() != 200) { - throw new ExternalAuthSystemException(getResponse.getBody()); - } - String res = getResponse.getBody(); - if (!res.equals(IS_EMPTY_JSON_STRING)) { - HttpEntity<String> userRoleentity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - ResponseEntity<String> deleteResponse = template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" - + LoginId - + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) - + "/" + app.getNameSpace() + "." - + role.getName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), - HttpMethod.DELETE, userRoleentity, String.class); - if (deleteResponse.getStatusCode().value() != 200) { - throw new ExternalAuthSystemException("Failed to delete user role"); - } - logger.debug(EELFLoggerDelegate.debugLogger, - "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", - deleteResponse.getStatusCode().value()); - } - } - - @SuppressWarnings("unchecked") - @Override - public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception { - List<CentralV2Role> roleList = new ArrayList<>(); - try { - List<EPApp> app = getApp(uebkey); - final Map<String, Long> params = new HashMap<>(); - // check if portal - Long appId = null; - if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { - appId = app.get(0).getId(); - } - List<Criterion> restrictionsList = new ArrayList<Criterion>(); - Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE); - Criterion appIdCrt; - if (appId == null) - appIdCrt = Restrictions.isNull("appId"); - else - appIdCrt = Restrictions.eq("appId", appId); - Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt); - restrictionsList.add(andCrit); - List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null); - roleList = createCentralRoleObject(app, epRole, roleList, params); - List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId()); - if (globalRoleList.size() > 0) - roleList.addAll(globalRoleList); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e); - throw e; - } - return roleList; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) - throws Exception { - Session localSession = sessionFactory.openSession(); - String message = ""; - Transaction transaction = null; - boolean response = false; - EPApp app = null; - try { - transaction = localSession.beginTransaction(); - List<EPRole> epRoleList = null; - app = getApp(uebkey).get(0); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epRoleList = getPortalAppRoleInfo(roleId); - } else { - epRoleList = getPartnerAppRoleInfo(roleId, app); - } - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - // Delete User Role in External System before deleting role - deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId); - } - // Delete user app roles - dataAccessService.deleteDomainObjects(EPUserApp.class, - APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); - boolean isPortalRequest = false; - deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest); - transaction.commit(); - if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - // Final call to delete role once all dependencies has been - // deleted - deleteRoleInExternalAuthSystem(epRoleList, app); - } - dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null); - logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction"); - response = true; - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - message = e.getMessage(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e); - EcompPortalUtils.rollbackTransaction(transaction, - "deleteDependencyRoleRecord rollback, exception = " + e.toString()); - message = e.getMessage(); - } finally { - localSession.close(); - } - return new ExternalRequestFieldsValidator(response, message); - } - - @Override - @SuppressWarnings("unchecked") - @Transactional - public void syncRoleFunctionFromExternalAccessSystem(EPApp app) { - try { - // get Permissions from External Auth System - JSONArray extPerms = getExtAuthPermissions(app); - List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms); - // get functions in DB - final Map<String, Long> params = new HashMap<>(); - final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>(); - params.put(APP_ID, app.getId()); - List<CentralV2RoleFunction> appFunctions = - dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); - if (!appFunctions.isEmpty()) { - for (CentralV2RoleFunction roleFunc : appFunctions) { - roleFuncMap.put(roleFunc.getCode(), roleFunc); - } - } - // get Roles for portal in DB - List<EPRole> portalRoleList = getGlobalRolesOfPortal(); - final Map<String, EPRole> existingPortalRolesMap = new HashMap<>(); - for (EPRole epRole : portalRoleList) { - existingPortalRolesMap.put(epRole.getName().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole); - } - // get Roles in DB - final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app); - // store External Permissions with Pipe and without Pipe (just - // instance) - final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>(); - final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>(); - for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) { - extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe); - String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance()); - extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe); - } - // Add if new functions and app role functions were added in - // external auth system - for (ExternalAccessPermsDetail permsDetail : permsDetailList) { - String code = permsDetail.getInstance(); - CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance()); - List<CentralV2RoleFunction> roleFunctionList = - addGetLocalFunction(app, roleFuncMap, permsDetail, code, getFunctionCodeKey); - List<String> roles = permsDetail.getRoles(); - if (roles != null) { - // Check if function has any roles and which does not exist - // in External Auth System. If exists delete in local - addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, - existingPortalRolesMap); - } - } - // Check if function does exits in External Auth System but exits in - // local then delete function and its dependencies - for (CentralV2RoleFunction roleFunc : appFunctions) { - try { - ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = - extAccessPermsContainsPipeMap.get(roleFunc.getCode()); - if (null == getFunctionCodeContainsPipeKey) { - ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode()); - if (null == getFunctionCodeKey) { - deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc); - } - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e); - } - } - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e); - } - } - - @SuppressWarnings("unchecked") - private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB, - List<CentralV2RoleFunction> roleFunctionList, List<String> roles, - Map<String, EPRole> existingPortalRolesMap) throws Exception { - if (!roleFunctionList.isEmpty()) { - final Map<String, String> appRoleFuncParams = new HashMap<>(); - final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>(); - final Map<String, String> currentRolesInExtSystem = new HashMap<>(); - appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode()); - appRoleFuncParams.put("appId", String.valueOf(app.getId())); - List<LocalRole> localRoleList = - dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions", appRoleFuncParams, null); - for (LocalRole localRole : localRoleList) { - currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll( - EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole); - } - for (String addRole : roles) { - currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole); - } - for (String extAuthrole : roles) { - String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE)); - boolean isNameSpaceMatching = - EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace()); - if (isNameSpaceMatching) { - if (!currentAppRoleFunctionsMap - .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) { - EPRole localAddFuntionRole = - currentRolesInDB.get(extAuthrole.substring(app.getNameSpace().length() + 1)); - if (localAddFuntionRole == null) { - checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole); - } else { - EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); - addAppRoleFunc.setAppId(app.getId()); - addAppRoleFunc.setCode(roleFunctionList.get(0).getCode()); - addAppRoleFunc.setRoleId(localAddFuntionRole.getId()); - dataAccessService.saveDomainObject(addAppRoleFunc, null); - } - } - // This block is to save global role function if exists - } else { - String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1); - boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName); - if (checkIfGlobalRoleExists) { - final Map<String, Long> params = new HashMap<>(); - EPRole role = existingPortalRolesMap.get(extAuthAppRoleName); - EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction(); - params.put("appId", app.getId()); - params.put("roleId", role.getId()); - List<EPAppRoleFunction> currentGlobalRoleFunctionsList = - dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null); - boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream() - .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode() - .equals(roleFunctionList.get(0).getCode())); - if (role != null && !checkIfRoleFunctionExists) { - addGlobalRoleFunctions.setAppId(app.getId()); - addGlobalRoleFunctions.setRoleId(role.getId()); - if (!app.getId().equals(role.getAppRoleId())) { - addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString()); - } else { - addGlobalRoleFunctions.setRoleAppId(null); - } - addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode()); - dataAccessService.saveDomainObject(addGlobalRoleFunctions, null); - } - } - } - } - for (LocalRole localRoleDelete : localRoleList) { - if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) { - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, - APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode() - + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(), - null); - } - } - } - } - - private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) { - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode()); - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, - APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode()); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode()); - dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class, - APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode()); - } - - private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB, - List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception { - if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) { - Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1)); - addRoleDescriptionInExtSystem(role, app); - if (!roleFunctionList.isEmpty()) { - try { - if (!roleFunctionList.isEmpty()) { - EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); - addAppRoleFunc.setAppId(app.getId()); - addAppRoleFunc.setCode(roleFunctionList.get(0).getCode()); - addAppRoleFunc.setRoleId(role.getId()); - dataAccessService.saveDomainObject(addAppRoleFunc, null); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e); - } - } - } - } - - @SuppressWarnings("unchecked") - private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, - final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code, - CentralV2RoleFunction getFunctionCodeKey) { - String finalFunctionCodeVal = - addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code, getFunctionCodeKey); - final Map<String, String> appSyncFuncsParams = new HashMap<>(); - appSyncFuncsParams.put("appId", String.valueOf(app.getId())); - appSyncFuncsParams.put("functionCd", finalFunctionCodeVal); - List<CentralV2RoleFunction> roleFunctionList = null; - roleFunctionList = - dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null); - if (roleFunctionList.isEmpty()) { - appSyncFuncsParams.put("functionCd", code); - roleFunctionList = - dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null); - } - return roleFunctionList; - } - - private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap, - ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) { - String finalFunctionCodeVal = ""; - if (null == getFunctionCodeKey) { - finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance()); - CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal); - // If function does not exist in local then add! - if (null == checkIfCodeStillExits) { - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code); - addFunctionInEcompDB(app, permsDetail, code); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code); - } - } - return finalFunctionCodeVal; - } - - @SuppressWarnings("unchecked") - @Override - public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) { - final Map<String, EPRole> currentRolesInDB = new HashMap<>(); - List<EPRole> getCurrentRoleList = null; - final Map<String, Long> appParams = new HashMap<>(); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null); - } else { - appParams.put("appId", app.getId()); - getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null); - } - for (EPRole role : getCurrentRoleList) { - currentRolesInDB.put(role.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role); - } - return currentRolesInDB; - } - - @SuppressWarnings("unchecked") - private Map<String, EPRole> getAppRoleNamesMap(EPApp app) { - final Map<String, EPRole> currentRolesInDB = new HashMap<>(); - List<EPRole> getCurrentRoleList = null; - final Map<String, Long> appParams = new HashMap<>(); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null); - } else { - appParams.put("appId", app.getId()); - getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null); - } - for (EPRole role : getCurrentRoleList) { - currentRolesInDB.put(role.getName(), role); - } - return currentRolesInDB; - } - - private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException { - ExternalAccessPermsDetail permDetails = null; - List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>(); - for (int i = 0; i < extPerms.length(); i++) { - String description = null; - if (extPerms.getJSONObject(i).has("description")) { - description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); - } else { - 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(); - JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); - List<String> list = rolesListMapper.readValue(resRoles.toString(), - TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); - permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), - extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) - + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE - + extPerms.getJSONObject(i).getString("action"), - extPerms.getJSONObject(i).getString("action"), list, description); - permsDetailList.add(permDetails); - } else { - permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), - extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) - + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE - + extPerms.getJSONObject(i).getString("action"), - extPerms.getJSONObject(i).getString("action"), description); - permsDetailList.add(permDetails); - } - } - return permsDetailList; - } - - private JSONArray getExtAuthPermissions(EPApp app) throws Exception { - ResponseEntity<String> response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); - String res = response.getBody(); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", - response.getBody()); - JSONObject jsonObj = new JSONObject(res); - JSONArray extPerms = jsonObj.getJSONArray("perm"); - for (int i = 0; i < extPerms.length(); i++) { - if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) { - extPerms.remove(i); - i--; - } - } - return extPerms; - } - - /** - * - * Add function into local DB - * - * @param app - * @param permsDetail - * @param code - */ - private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) { - try { - CentralV2RoleFunction addFunction = new CentralV2RoleFunction(); - addFunction.setAppId(app.getId()); - addFunction.setCode(code); - addFunction.setName(permsDetail.getDescription()); - dataAccessService.saveDomainObject(addFunction, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e); - } - } - - /** - * - * It updates description of a role in external auth system - * - * @param role - * @param app - * @throws Exception - */ - private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception { - boolean status = false; - try { - String addRoleNew = updateExistingRoleInExternalSystem(role, app); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", - HttpMethod.PUT, entity, String.class); - status = true; - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e); - } - return status; - } - - /** - * - * While sync functions form external auth system if new role found we should add in local and - * return Role.class object - * - * @param app - * @param role - * @return - */ - @SuppressWarnings("unchecked") - private Role addRoleInDBIfDoesNotExists(EPApp app, String role) { - Role setNewRole = new Role(); - try { - // functions can have new role created in External Auth System - // prevent - // duplication here - boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app); - final Map<String, String> getRoleByNameParams = new HashMap<>(); - List<EPRole> getRoleCreated = null; - getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role); - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - getRoleByNameParams.put("appId", String.valueOf(app.getId())); - List<EPRole> roleCreated = dataAccessService - .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null); - if (!isCreated) { - EPRole epUpdateRole = roleCreated.get(0); - epUpdateRole.setAppRoleId(epUpdateRole.getId()); - dataAccessService.saveDomainObject(epUpdateRole, null); - getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, - getRoleByNameParams, null); - } else { - getRoleCreated = roleCreated; - } - } else { - getRoleCreated = - dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams, null); - } - if (getRoleCreated != null && !getRoleCreated.isEmpty()) { - EPRole roleObject = getRoleCreated.get(0); - setNewRole.setId(roleObject.getId()); - setNewRole.setName(roleObject.getName()); - setNewRole.setActive(roleObject.getActive()); - setNewRole.setPriority(roleObject.getPriority()); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e); - } - return setNewRole; - } - - @SuppressWarnings("unchecked") - private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) { - boolean isCreated = false; - final Map<String, String> roleParams = new HashMap<>(); - roleParams.put(APP_ROLE_NAME_PARAM, role); - List<EPRole> roleCreated = null; - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null); - } else { - roleParams.put("appId", String.valueOf(app.getId())); - roleCreated = - dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null); - } - if (roleCreated == null || roleCreated.isEmpty()) { - roleParams.put("appId", String.valueOf(app.getId())); - EPRole epRoleNew = new EPRole(); - epRoleNew.setActive(true); - epRoleNew.setName(role); - if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - epRoleNew.setAppId(null); - } else { - epRoleNew.setAppId(app.getId()); - } - dataAccessService.saveDomainObject(epRoleNew, null); - isCreated = false; - } else { - isCreated = true; - } - return isCreated; - } - - @Override - @SuppressWarnings("unchecked") - public Integer bulkUploadFunctions(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null); - CentralV2RoleFunction cenRoleFunc = null; - Integer functionsAdded = 0; - try { - for (RoleFunction roleFunc : roleFuncList) { - cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName()); - addRoleFunctionInExternalSystem(cenRoleFunc, app); - functionsAdded++; - } - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e); - } - return functionsAdded; - } - - @Override - public Integer bulkUploadRoles(String uebkey) throws Exception { - List<EPApp> app = getApp(uebkey); - List<EPRole> roles = getAppRoles(app.get(0).getId()); - List<CentralV2Role> cenRoleList = new ArrayList<>(); - final Map<String, Long> params = new HashMap<>(); - Integer rolesListAdded = 0; - try { - cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); - String roleList = mapper.writeValueAsString(cenRoleList); - List<Role> roleObjectList = mapper.readValue(roleList, - TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); - for (Role role : roleObjectList) { - addRoleInExternalSystem(role, app.get(0)); - rolesListAdded++; - } - 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<String> 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; - } - return rolesListAdded; - } - - /** - * It creating new role in external auth system while doing bulk upload - * - * @param role - * @param app - * @throws Exception - */ - private void addRoleInExternalSystem(Role role, EPApp app) throws Exception { - String addRoleNew = updateExistingRoleInExternalSystem(role, app); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - try { - HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", - HttpMethod.POST, entity, String.class); - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", - e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, - "addRoleInExternalSystem: Role already exits but does not break functionality", e); - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage()); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public Integer bulkUploadRolesFunctions(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - List<EPRole> roles = getAppRoles(app.getId()); - final Map<String, Long> params = new HashMap<>(); - Integer roleFunctions = 0; - try { - for (EPRole role : roles) { - params.put("roleId", role.getId()); - List<BulkUploadRoleFunction> appRoleFunc = - dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null); - if (!appRoleFunc.isEmpty()) { - for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { - addRoleFunctionsInExternalSystem(addRoleFunc, role, app); - roleFunctions++; - } - } - } - } catch (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; - } - - /** - * Its adding a role function while doing bulk upload - * - * @param addRoleFunc - * @param role - * @param app - */ - private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) { - 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() + "." + type, instance, action, - addRoleFunc.getFunctionName()); - extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String updateRolePerms = mapper.writeValueAsString(extRolePerms); - HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", - HttpMethod.POST, entity, String.class); - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, - "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", - e); - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage()); - } - } - } - - @SuppressWarnings("unchecked") - @Override - public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - final Map<String, Long> params = new HashMap<>(); - params.put("appId", app.getId()); - List<CentralV2RoleFunction> 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<String> entity = new HttpEntity<>(addFunction, headers); - logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); - ResponseEntity<String> 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<Role> roleList) throws Exception { - EPApp app = getApp(uebkey).get(0); - for (Role role : roleList) { - addRoleInExternalSystem(role, app); - } - } - - @SuppressWarnings("unchecked") - @Override - public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - List<EPRole> roles = getAppRoles(app.getId()); - final Map<String, Long> params = new HashMap<>(); - Integer roleFunctions = 0; - try { - for (EPRole role : roles) { - params.put("roleId", role.getId()); - List<BulkUploadRoleFunction> appRoleFunc = - dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions", params, null); - if (!appRoleFunc.isEmpty()) { - for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { - addRoleFunctionsInExternalSystem(addRoleFunc, role, app); - roleFunctions++; - } - } - } - // 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<String, Long> params = new HashMap<>(); - params.put("appId", app.getId()); - List<GlobalRoleWithApplicationRoleFunction> 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 { - 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<String> 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 - @Transactional - public void syncApplicationRolesWithEcompDB(EPApp app) { - try { - logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started"); - // Sync functions and roles assigned to it which also creates new roles if does - // not exits in portal - syncRoleFunctionFromExternalAccessSystem(app); - logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished"); - ObjectMapper mapper = new ObjectMapper(); - logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem"); - // Get Permissions from External Auth System - JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app); - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList"); - // refactoring done - List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole); - List<EPRole> finalRoleList = new ArrayList<>(); - for (ExternalRoleDetails externalRole : externalRoleDetailsList) { - EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole); - finalRoleList.add(ecompRole); - } - List<EPRole> applicationRolesList; - applicationRolesList = getAppRoles(app.getId()); - List<String> applicationRoleIdList = new ArrayList<>(); - for (EPRole applicationRole : applicationRolesList) { - applicationRoleIdList.add(applicationRole.getName()); - } - List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>(); - for (EPRole aafRole : finalRoleList) { - if (!applicationRoleIdList.contains(aafRole.getName())) { - roleListToBeAddInEcompDB.add(aafRole); - } - } - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem"); - // Check if roles exits in external Access system and if not make inactive in DB - inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList); - logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem"); - // Add new roles in DB and updates role description in External Auth System - addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB); - logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished"); - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e); - } - } - - /** - * - * It adds new roles in DB and updates description in External Auth System - * - * @param app - * @param roleListToBeAddInEcompDB - */ - @SuppressWarnings("unchecked") - private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) { - EPRole roleToBeAddedInEcompDB; - for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { - try { - roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); - if (app.getId() == 1) { - roleToBeAddedInEcompDB.setAppRoleId(null); - } - dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); - List<EPRole> getRoleCreatedInSync = null; - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - final Map<String, String> globalRoleParams = new HashMap<>(); - globalRoleParams.put("appId", String.valueOf(app.getId())); - globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName()); - getRoleCreatedInSync = dataAccessService - .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null); - EPRole epUpdateRole = getRoleCreatedInSync.get(0); - epUpdateRole.setAppRoleId(epUpdateRole.getId()); - dataAccessService.saveDomainObject(epUpdateRole, null); - } - List<EPRole> roleList = new ArrayList<>(); - final Map<String, String> params = new HashMap<>(); - params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName()); - boolean isPortalRole = false; - if (app.getId() == 1) { - isPortalRole = true; - roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null); - } else { - isPortalRole = false; - params.put(APP_ID, app.getId().toString()); - roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, - null); - } - EPRole role = roleList.get(0); - Role aaFrole = new Role(); - aaFrole.setId(role.getId()); - aaFrole.setActive(role.getActive()); - aaFrole.setPriority(role.getPriority()); - aaFrole.setName(role.getName()); - updateRoleInExternalSystem(aaFrole, app, isPortalRole); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e); - } - } - } - - /** - * - * It checks description in External Auth System if found any changes updates in DB - * - * @param app - * @param finalRoleList contains list of External Auth System roles list which is converted to - * EPRole - */ - @SuppressWarnings("unchecked") - private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) { - for (EPRole roleItem : finalRoleList) { - final Map<String, String> roleParams = new HashMap<>(); - List<EPRole> currentList = null; - roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName()); - if (app.getId() == 1) { - currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null); - } else { - roleParams.put(APP_ID, app.getId().toString()); - currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, - roleParams, null); - } - if (!currentList.isEmpty()) { - try { - Boolean aafRoleActive; - Boolean localRoleActive; - boolean result; - aafRoleActive = Boolean.valueOf(roleItem.getActive()); - localRoleActive = Boolean.valueOf(currentList.get(0).getActive()); - result = aafRoleActive.equals(localRoleActive); - EPRole updateRole = currentList.get(0); - if (!result) { - updateRole.setActive(roleItem.getActive()); - dataAccessService.saveDomainObject(updateRole, null); - } - if (roleItem.getPriority() != null - && !currentList.get(0).getPriority().equals(roleItem.getPriority())) { - updateRole.setPriority(roleItem.getPriority()); - dataAccessService.saveDomainObject(updateRole, null); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "syncApplicationRolesWithEcompDB: Failed to update role ", e); - } - } - } - } - - /** - * - * It de-activates application roles in DB if not present in External Auth system - * - * @param app - * @param finalRoleList contains list of current roles present in External Auth System - * @param applicationRolesList contains list of current roles present in DB - */ - @SuppressWarnings("unchecked") - private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList, - List<EPRole> applicationRolesList) { - final Map<String, EPRole> checkRolesInactive = new HashMap<>(); - for (EPRole extrole : finalRoleList) { - checkRolesInactive.put(extrole.getName(), extrole); - } - for (EPRole role : applicationRolesList) { - try { - final Map<String, String> extRoleParams = new HashMap<>(); - List<EPRole> roleList = null; - extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName()); - if (!checkRolesInactive.containsKey(role.getName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) { - if (app.getId() == 1) { - roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null); - } else { - extRoleParams.put(APP_ID, app.getId().toString()); - roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, - extRoleParams, null); - } - if (!roleList.isEmpty()) { - EPRole updateRoleInactive = roleList.get(0); - updateRoleInactive.setActive(false); - dataAccessService.saveDomainObject(updateRoleInactive, null); - } - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e); - } - } - } - - @Override - @SuppressWarnings("unchecked") - public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole) - throws IOException { - List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>(); - ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); - List<String> functionCodelist = new ArrayList<>(); - Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app); - Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app); - for (int i = 0; i < extRole.length(); i++) { - ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); - EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); - JSONObject Role = (JSONObject) extRole.get(i); - String name = extRole.getJSONObject(i).getString(ROLE_NAME); - String actualRoleName = name.substring(app.getNameSpace().length() + 1); - if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { - actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); - } - SortedSet<ExternalAccessPerms> 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()); - if (isNamespaceMatching) { - externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), - perms.getString("instance"), perms.getString("action")); - ePAppRoleFunction.setCode(externalAccessPerms.getInstance()); - functionCodelist.add(ePAppRoleFunction.getCode()); - externalAccessPermsOfRole.add(externalAccessPerms); - } - } - } - externalRoleDetail.setActive(true); - externalRoleDetail.setName(actualRoleName); - if (app.getId() == 1) { - externalRoleDetail.setAppId(null); - } else { - externalRoleDetail.setAppId(app.getId()); - } - EPRole currRole = null; - currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) - ? curRolesUnderscoreMap.get(actualRoleName) - : curRolesMap.get(actualRoleName); - Long roleId = null; - if (currRole != null) - roleId = currRole.getId(); - final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>(); - final Map<String, Long> appRoleFuncsParams = new HashMap<>(); - if (roleId != null) { - appRoleFuncsParams.put("appId", app.getId()); - appRoleFuncsParams.put("roleId", roleId); - // get role functions from DB - List<EPAppRoleFunction> 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) { - EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance()); - if (checkRoleFunctionExits == null) { - String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1) - + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE - + externalpermission.getAction(); - EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode); - if (checkRoleFunctionPipeExits == null) { - try { - final Map<String, String> 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<CentralV2RoleFunction> roleFunction = null; - roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", - appFuncsParams, null); - if (roleFunction.isEmpty()) { - appFuncsParams.put("functionCd", funcCode); - roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", - appFuncsParams, null); - } - if (!roleFunction.isEmpty()) { - EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); - apRoleFunction.setAppId(app.getId()); - apRoleFunction.setRoleId(roleId); - apRoleFunction.setCode(roleFunction.get(0).getCode()); - dataAccessService.saveDomainObject(apRoleFunction, null); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "SyncApplicationRolesWithEcompDB: Failed to add role function", e); - } - } - } - } - } - externalRoleDetailsList.add(externalRoleDetail); - } - return externalRoleDetailsList; - } - - @Override - public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception { - ResponseEntity<String> response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); - String res = response.getBody(); - logger.debug(EELFLoggerDelegate.debugLogger, - "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :", - res); - JSONObject jsonObj = new JSONObject(res); - JSONArray extRole = jsonObj.getJSONArray("role"); - for (int i = 0; i < extRole.length(); i++) { - if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN) - || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER) - || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR) - && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { - extRole.remove(i); - i--; - } - } - return extRole; - } - - @Override - public JSONArray getAllUsersByRole(String roleName) throws Exception { - ResponseEntity<String> response = null; - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); - response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class); - String res = response.getBody(); - 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"); - return extRole; - } - - /** - * - * It converts from ExternalRoleDetails.class object to EPRole.class object - * - * @param externalRoleDetails - * @return EPRole object - */ - private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { - EPRole role = new EPRole(); - role.setActive(true); - role.setAppId(externalRoleDetails.getAppId()); - role.setAppRoleId(externalRoleDetails.getAppRoleId()); - role.setName(externalRoleDetails.getName()); - role.setPriority(externalRoleDetails.getPriority()); - return role; - } - - @SuppressWarnings("unchecked") - @Override - public Integer bulkUploadUserRoles(String uebkey) throws Exception { - EPApp app = getApp(uebkey).get(0); - final Map<String, String> params = new HashMap<>(); - params.put("uebKey", app.getUebKey()); - List<BulkUploadUserRoles> userRolesList = null; - Integer userRolesAdded = 0; - if (app.getCentralAuth()) { - userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null); - for (BulkUploadUserRoles userRolesUpload : userRolesList) { - if (!userRolesUpload.getOrgUserId().equals("su1234")) { - addUserRoleInExternalSystem(userRolesUpload); - userRolesAdded++; - } - } - } - return userRolesAdded; - } - - /** - * Its adding a user role in external auth system while doing bulk upload - * - * @param userRolesUpload - */ - private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) { - try { - String name = ""; - ObjectMapper mapper = new ObjectMapper(); - if (EPCommonSystemProperties - .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { - name = userRolesUpload.getOrgUserId() - + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); - } - ExternalAccessUser extUser = - new ExternalAccessUser(name, userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName() - .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String userRole = mapper.writeValueAsString(extUser); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(userRole, headers); - template.exchange( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", - HttpMethod.POST, entity, String.class); - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, - "addUserRoleInExternalSystem: UserRole already exits but does not break functionality"); - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e); - } - } - } - - @Override - public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) - throws Exception { - try { - String sql = ""; - Query query = null; - // It should delete only when it portal's roleId - if (appId.equals(PortalConstants.PORTAL_APP_ID)) { - // Delete from fn_role_function - sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - // Delete from fn_role_composite - sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - } - // Delete from ep_app_role_function - sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - // Delete from ep_role_notification - sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - // Delete from fn_user_pseudo_role - sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - // Delete form EP_WIDGET_CATALOG_ROLE - sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - // Delete form EP_WIDGET_CATALOG_ROLE - sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - if (!isPortalRequest) { - // Delete form fn_menu_functional_roles - sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - } - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e); - throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage()); - } - } - - @SuppressWarnings("unchecked") - @Override - public List<String> getMenuFunctionsList(String uebkey) throws Exception { - List<String> appMenuFunctionsList = null; - List<String> appMenuFunctionsFinalList = new ArrayList<>(); - try { - EPApp app = getApp(uebkey).get(0); - final Map<String, Long> 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 appMenuFunctionsFinalList; - } - return appMenuFunctionsFinalList; - } - - @SuppressWarnings({"unchecked"}) - @Override - public List<EcompUser> getAllAppUsers(String uebkey) throws Exception { - List<String> usersList = new ArrayList<>(); - List<EcompUser> usersfinalList = new ArrayList<>(); - try { - EPApp app = getApp(uebkey).get(0); - final Map<String, Long> appParams = new HashMap<>(); - appParams.put("appId", app.getId()); - List<EcompUserRoles> userList = - (List<EcompUserRoles>) dataAccessService.executeNamedQuery("ApplicationUserRoles", appParams, null); - for (EcompUserRoles ecompUserRole : userList) { - boolean found = false; - Set<EcompRole> 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<EcompRoleFunction> roleFunctionSet = new TreeSet<>(); - if (role != null) { - roleFunctionSet = (SortedSet<EcompRoleFunction>) 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<EcompRoleFunction> 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; - } - - @Override - 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) { - @SuppressWarnings("unchecked") - Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions(); - Set<RoleFunction> roleFunctionListNew = new HashSet<>(); - Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); - RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class); - roleFunctionListNew.add(roleFun); - } - newRole.setRoleFunctions(roleFunctionListNew); - } - return newRole; - } - - @Override - @SuppressWarnings("unchecked") - public List<CentralizedApp> getCentralizedAppsOfUser(String userId) { - Map<String, String> params = new HashMap<>(); - params.put("userId", userId); - List<CentralizedApp> centralizedAppsList = new ArrayList<>(); - try { - centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); - } - return centralizedAppsList; - } - - @SuppressWarnings("unchecked") - public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) { - Map<String, Long> params = new HashMap<>(); - params.put("appId", appId); - List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>(); - try { - globalRoles = - dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); - } - List<CentralV2Role> rolesfinalList = new ArrayList<>(); - if (globalRoles.size() > 0) - rolesfinalList = finalListOfCentralRoles(globalRoles); - return rolesfinalList; - } - - @SuppressWarnings("unchecked") - private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) { - CentralV2Role finalGlobalrole = null; - List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>(); - Map<String, Long> params = new HashMap<>(); - params.put("roleId", roleId); - params.put("requestedAppId", requestedAppId); - try { - roleWithApplicationRoleFucntions = - dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", params, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e); - } - if (roleWithApplicationRoleFucntions.size() > 0) { - List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions); - finalGlobalrole = rolesfinalList.get(0); - } else { - List<EPRole> roleList = getPortalAppRoleInfo(roleId); - finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0)); - } - return finalGlobalrole; - } - - private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) { - List<CentralV2Role> rolesfinalList = new ArrayList<>(); - for (GlobalRoleWithApplicationRoleFunction role : globalRoles) { - boolean found = false; - for (CentralV2Role cenRole : rolesfinalList) { - if (role.getRoleId().equals(cenRole.getId())) { - SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions(); - CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role); - roleFunctions.add(cenRoleFun); - cenRole.setRoleFunctions(roleFunctions); - found = true; - break; - } - } - if (!found) { - CentralV2Role cenrole = new CentralV2Role(); - cenrole.setName(role.getRoleName()); - cenrole.setId(role.getRoleId()); - cenrole.setActive(role.isActive()); - cenrole.setPriority(role.getPriority()); - SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>(); - CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role); - roleFunctions.add(cenRoleFun); - cenrole.setRoleFunctions(roleFunctions); - rolesfinalList.add(cenrole); - } - } - return rolesfinalList; - } - - private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) { - String instance; - String type; - String action; - CentralV2RoleFunction cenRoleFun; - if (role.getFunctionCd().contains(FUNCTION_PIPE)) { - instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd()); - type = EcompPortalUtils.getFunctionType(role.getFunctionCd()); - action = EcompPortalUtils.getFunctionAction(role.getFunctionCd()); - cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null); - } else { - type = getFunctionCodeType(role.getFunctionCd()); - action = getFunctionCodeAction(role.getFunctionCd()); - cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, - action, null); - } - return cenRoleFun; - } - - @SuppressWarnings("unchecked") - @Override - public List<EPRole> getGlobalRolesOfPortal() { - List<EPRole> globalRoles = new ArrayList<>(); - try { - globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e); - } - return globalRoles; - } - - private CentralV2Role convertRoleToCentralV2Role(EPRole role) { - return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), - role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(), - new TreeSet<>(), new TreeSet<>(), new TreeSet<>()); - } - - @Override - public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject( - List<CentralV2RoleFunction> answer) { - List<CentralRoleFunction> addRoleFuncList = new ArrayList<>(); - for (CentralV2RoleFunction cenRoleFunc : answer) { - CentralRoleFunction setRoleFunc = new CentralRoleFunction(); - setRoleFunc.setCode(cenRoleFunc.getCode()); - setRoleFunc.setName(cenRoleFunc.getName()); - addRoleFuncList.add(setRoleFunc); - } - return addRoleFuncList; - } - - @Override - public CentralUser getUserRoles(String loginId, String uebkey) throws Exception { - CentralUser sendUserRoles = null; - try { - CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey); - sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e); - throw e; - } - return sendUserRoles; - } - - /** - * - * It returns V2 CentralUser object if user has any roles and permissions - * - * @param loginId - * @param uebkey - * @return CentralUser object - * @throws Exception - */ - private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception { - EPApp app; - List<EPUser> epUserList; - List<EPApp> appList = getApp(uebkey); - app = appList.get(0); - epUserList = getUser(loginId); - EPUser user = epUserList.get(0); - Set<EPUserApp> userAppSet = user.getEPUserApps(); - return createEPUser(user, userAppSet, app); - } - - private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) { - final Map<String, Long> userParams = new HashMap<>(); - userParams.put("appId", app.getId()); - userParams.put("userId", user.getId()); - @SuppressWarnings("unchecked") - List<EPUserAppCurrentRoles> userAppsRolesList = - dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null); - List<EcompRole> setUserRoles = new ArrayList<>(); - for (EPUserAppCurrentRoles role : userAppsRolesList) { - logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}", - role.getRoleName()); - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(role.getRoleId()); - ecompRole.setName(role.getRoleName()); - setUserRoles.add(ecompRole); - } - logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}", - setUserRoles.size()); - return setUserRoles; - } - - @Override - public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles) - throws Exception { - List<EPApp> appList = getApp(uebkey); - EPApp app = appList.get(0); - List<EPUser> epUserList; - epUserList = getUser(loginId); - List<EcompRole> missingUserAppRoles = new ArrayList<>(); - List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList()); - logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList); - List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0)); - if (userApplicationsRolesfromDB.size() > 0) { - missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName())) - .collect(Collectors.toList()); - } - List<String> MissingroleNamesList = - missingUserAppRoles.stream().map(EcompRole::getName).collect(Collectors.toList()); - logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList); - - List<EcompRole> finalMissingRoleList = new ArrayList<>(); - if (missingUserAppRoles.size() > 0) { - final Map<String, Long> params = new HashMap<>(); - for (EcompRole role : missingUserAppRoles) { - params.put("roleId", role.getId()); - params.put(APP_ID, app.getId()); - - EcompRole epRole = new EcompRole(); - epRole.setId(role.getId()); - epRole.setName(role.getName()); - @SuppressWarnings("unchecked") - List<CentralV2RoleFunction> appRoleFunctionList = - dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>(); - for (CentralV2RoleFunction roleFunc : appRoleFunctionList) { - String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - String type = getFunctionCodeType(roleFunc.getCode()); - String action = getFunctionCodeAction(roleFunc.getCode()); - EcompRoleFunction fun = new EcompRoleFunction(); - fun.setAction(action); - fun.setCode(functionCode); - fun.setType(type); - fun.setName(roleFunc.getName()); - roleFunctionSet.add(fun); - - } - epRole.setRoleFunctions(roleFunctionSet); - finalMissingRoleList.add(epRole); - } - } - - return finalMissingRoleList; - } - - /** - * It converts V2 CentralUser object to old version CentralUser object - * - * @param cenV2User - * @return EPUser object - */ - private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) { - Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps(); - Set<CentralUserApp> userApps = new TreeSet<>(); - for (CentralV2UserApp userApp : userV2Apps) { - CentralApp app = userApp.getApp(); - CentralUserApp cua = new CentralUserApp(); - cua.setUserId(null); - cua.setApp(app); - SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>(); - for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) { - CentralRoleFunction cenRoleFunc = - new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName()); - cenRoleFunction.add(cenRoleFunc); - } - CentralRole role = new CentralRole.CentralRoleBuilder().setId(userApp.getRole().getId()) - .setName(userApp.getRole().getName()).setActive(userApp.getRole().getActive()) - .setPriority(userApp.getRole().getPriority()).setRoleFunctions(cenRoleFunction).createCentralRole(); - cua.setRole(role); - userApps.add(cua); - } - return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), - cenV2User.getCreatedId(), cenV2User.getModifiedId(), cenV2User.getRowNum(), cenV2User.getOrgId(), - cenV2User.getManagerId(), cenV2User.getFirstName(), cenV2User.getMiddleInitial(), - cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), cenV2User.getCellular(), - cenV2User.getEmail(), cenV2User.getAddressId(), cenV2User.getAlertMethodCd(), cenV2User.getHrid(), - cenV2User.getOrgUserId(), cenV2User.getOrgCode(), cenV2User.getAddress1(), cenV2User.getAddress2(), - cenV2User.getCity(), cenV2User.getState(), cenV2User.getZipCode(), cenV2User.getCountry(), - cenV2User.getOrgManagerUserId(), cenV2User.getLocationClli(), cenV2User.getBusinessCountryCode(), - cenV2User.getBusinessCountryName(), cenV2User.getBusinessUnit(), cenV2User.getBusinessUnitName(), - cenV2User.getDepartment(), cenV2User.getDepartmentName(), cenV2User.getCompanyCode(), - cenV2User.getCompany(), cenV2User.getZipCodeSuffix(), cenV2User.getJobTitle(), - cenV2User.getCommandChain(), cenV2User.getSiloStatus(), cenV2User.getCostCenter(), - cenV2User.getFinancialLocCode(), cenV2User.getLoginId(), cenV2User.getLoginPwd(), - cenV2User.getLastLoginDate(), cenV2User.isActive(), cenV2User.isInternal(), - cenV2User.getSelectedProfileId(), cenV2User.getTimeZoneId(), cenV2User.isOnline(), - cenV2User.getChatId(), userApps); - } - - @Override - public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) { - List<CentralRole> cenRoleList = new ArrayList<>(); - for (CentralV2Role v2CenRole : v2CenRoleList) { - SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>(); - for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) { - CentralRoleFunction roleFunc = - new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); - cenRoleFuncList.add(roleFunc); - } - CentralRole role = new CentralRole.CentralRoleBuilder().setId(v2CenRole.getId()) - .setName(v2CenRole.getName()).setActive(v2CenRole.getActive()).setPriority(v2CenRole.getPriority()) - .setRoleFunctions(cenRoleFuncList).createCentralRole(); - cenRoleList.add(role); - } - return cenRoleList; - } - - @Override - public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception { - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system"); - ResponseEntity<String> response = null; - try { - response = - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ", - response.getStatusCode().value()); - } catch (HttpClientErrorException e) { - logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e); - EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); - if (e.getStatusCode() == HttpStatus.NOT_FOUND) - throw new InvalidApplicationException("Invalid NameSpace"); - else - throw e; - } - return response; - } - - @Override - public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) { - SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>(); - for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) { - CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); - cenRoleFuncList.add(roleFunc); - } - return new CentralRole.CentralRoleBuilder().setId(v2CenRole.getId()).setName(v2CenRole.getName()) - .setActive(v2CenRole.getActive()).setPriority(v2CenRole.getPriority()).setRoleFunctions(cenRoleFuncList) - .createCentralRole(); - } - - @SuppressWarnings("unchecked") - @Override - public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception { - EPApp app = getApp(uebkey).get(0); - final Map<String, String> params = new HashMap<>(); - params.put("uebKey", app.getUebKey()); - params.put("roleId", String.valueOf(roleId)); - List<BulkUploadUserRoles> userRolesList = null; - Integer userRolesAdded = 0; - if (app.getCentralAuth()) { - userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null); - for (BulkUploadUserRoles userRolesUpload : userRolesList) { - userRolesUpload.setRoleName(modifiedRoleName); - if (!userRolesUpload.getOrgUserId().equals("su1234")) { - addUserRoleInExternalSystem(userRolesUpload); - userRolesAdded++; - } - } - } - return userRolesAdded; - } - - @Override - public String encodeFunctionCode(String funCode) { - String encodedString = funCode; - List<Pattern> encodingList = new ArrayList<>(); - encodingList.add(Pattern.compile("/")); - encodingList.add(Pattern.compile("-")); - for (Pattern xssInputPattern : encodingList) { - encodedString = xssInputPattern.matcher(encodedString) - .replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes())); - } - 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<String> 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<String> entity) { - logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}", - CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); - ResponseEntity<String> 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<String> getUserRolesEntity = new HttpEntity<>(headers); - ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity); - List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>(); - String res = getResponse.getBody(); - JSONObject jsonObj = null; - JSONArray extRoles = null; - if (!res.equals("{}")) { - jsonObj = new JSONObject(res); - extRoles = jsonObj.getJSONArray("role"); - } - updateUserRolesInLocal(userRoleDetailList, extRoles, loginId); - } - - @SuppressWarnings("unchecked") - private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles, - String loginId) throws InvalidUserException { - HashMap<String, String> userParams = new HashMap<>(); - userParams.put("orgUserId", loginId); - // Get all centralized applications existing user roles from local - List<CentralizedAppRoles> currentUserAppRoles = - dataAccessService.executeNamedQuery("getUserCentralizedAppRoles", userParams, null); - EPUser user = getUser(loginId).get(0); - // Get all centralized applications roles from local - HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList(); - HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = - getCurrentUserCentralizedAppRoles(currentUserAppRoles); - // Get all centralized applications + admin role from local - HashMap<String, EPApp> 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<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user, - HashMap<String, CentralizedAppRoles> cenAppRolesMap, - HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap, - HashMap<String, EPApp> 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<String, EPApp> getCentralizedAdminAppsInfo() { - List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null); - HashMap<String, EPApp> 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<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles( - List<CentralizedAppRoles> currentUserAppRoles) { - HashMap<String, CentralizedAppRoles> 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<String, CentralizedAppRoles> getCentralizedAppRoleList() { - List<CentralizedAppRoles> centralizedAppRoles = - dataAccessService.executeNamedQuery("getAllCentralizedAppsRoles", null, null); - HashMap<String, CentralizedAppRoles> 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<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) { - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); - ResponseEntity<String> getResponse = - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); - if (getResponse.getStatusCode().value() == 200) { - logger.debug(EELFLoggerDelegate.debugLogger, - "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; - } - - @Override - public Integer updateAppRoleDescription(String uebkey) { - Integer roleDescUpdated = 0; - EPApp app; - try { - app = getApp(uebkey).get(0); - List<EPRole> roles = getAppRoles(app.getId()); - for (EPRole epRole : roles) { - Role role = new Role(); - role.setName(epRole.getName()); - boolean status = addRoleDescriptionInExtSystem(role, app); - if (status) - roleDescUpdated++; - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e); - } - return roleDescUpdated; - } + private static final String APP_ROLE_NAME_PARAM = "appRoleName"; + private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem"; + private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles"; + private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction"; + private static final String FUNCTION_CODE_PARAMS = "functionCode"; + private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '"; + private static final String OWNER = ".owner"; + private static final String ADMIN = ".admin"; + private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator"; + private static final String FUNCTION_PIPE = "|"; + private static final String EXTERNAL_AUTH_PERMS = "perms"; + private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description"; + private static final String IS_EMPTY_JSON_STRING = "{}"; + private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system"; + private static final String APP_ID = "appId"; + private static final String ROLE_NAME = "name"; + private static final String APP_ID_EQUALS = " app_id = "; + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class); + @Autowired + private DataAccessService dataAccessService; + @Autowired + private EPAppService epAppService; + @Autowired + private SessionFactory sessionFactory; + @Autowired + EPRoleService ePRoleService; + RestTemplate template = new RestTemplate(); + // These decode values are based on HexDecoder + static final String decodeValueOfForwardSlash = "2f"; + static final String decodeValueOfHiphen = "2d"; + static final String decodeValueOfStar = "2a"; + + @SuppressWarnings("unchecked") + @Override + public List<EPRole> getAppRoles(Long appId) throws Exception { + List<EPRole> applicationRoles = null; + final Map<String, Long> appParams = new HashMap<>(); + try { + if (appId == 1) { + applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null); + } else { + appParams.put("appId", appId); + applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e); + throw e; + } + return applicationRoles; + } + + @SuppressWarnings("unchecked") + @Override + public List<EPApp> getApp(String uebkey) throws Exception { + List<EPApp> app = null; + try { + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", uebkey); + app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null); + if (!app.isEmpty() && !app.get(0).getEnabled() + && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e); + throw e; + } + return app; + } + + /** + * It returns single application role from external auth system + * + * @param addRole + * @param app + * @return JSON string which contains application role details + * @throws Exception + */ + private String getSingleAppRole(String addRole, EPApp app) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + ResponseEntity<String> response = null; + logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system"); + response = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" + + app.getNameSpace() + "." + addRole + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ", + response.getStatusCode().value()); + return response.getBody(); + } + + @Override + public boolean addRole(Role addRole, String uebkey) throws Exception { + boolean response = false; + ResponseEntity<String> addResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + EPApp app = getApp(uebkey).get(0); + String newRole = updateExistingRoleInExternalSystem(addRole, app); + HttpEntity<String> entity = new HttpEntity<>(newRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system"); + addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() == 201) { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, + "addRole: Finished adding role in the External Auth system and response code: {} ", + addResponse.getStatusCode().value()); + } + if (addResponse.getStatusCode().value() == 406) { + logger.error(EELFLoggerDelegate.errorLogger, + "addRole: Failed to add in the External Auth system due to {} and status code: {}", + addResponse.getBody(), addResponse.getStatusCode().value()); + } + return response; + } + + /** + * + * It deletes record in external auth system + * + * @param delRole + * @return JSON String which has status code and response body + * @throws Exception + */ + private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception { + ResponseEntity<String> delResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(delRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole); + delResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true", + HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", + delRole, delResponse.getStatusCode().value()); + return delResponse; + } + + /** + * It updates role in external auth system + * + * @param updateExtRole + * @param app + * @return true if success else false + * @throws Exception If updateRoleInExternalSystem fails we catch it in logger + * for detail message + */ + private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception { + boolean response = false; + ObjectMapper mapper = new ObjectMapper(); + ResponseEntity<String> deleteResponse = null; + List<EPRole> epRoleList = null; + if (app.getId().equals(PortalConstants.PORTAL_APP_ID) + || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { + epRoleList = getPortalAppRoleInfo(updateExtRole.getId()); + } else { + epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app); + } + // Assigning functions to global role + if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { + List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); + EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID); + addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo); + response = true; + } else { + String appRole = getSingleAppRole(epRoleList.get(0).getName(), app); + List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); + if (!appRole.equals(IS_EMPTY_JSON_STRING)) { + JSONObject jsonObj = new JSONObject(appRole); + JSONArray extRole = jsonObj.getJSONArray("role"); + if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { + String roleName = extRole.getJSONObject(0).getString(ROLE_NAME); + Map<String, String> delRoleKeyMapper = new HashMap<>(); + delRoleKeyMapper.put(ROLE_NAME, roleName); + String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper); + deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue); + if (deleteResponse.getStatusCode().value() != 200) { + throw new ExternalAuthSystemException(deleteResponse.getBody()); + } + addRole(updateExtRole, app.getUebKey()); + } else { + String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); + String name = extRole.getJSONObject(0).getString(ROLE_NAME); + List<ExternalAccessPerms> list = new ArrayList<>(); + if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) { + JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS); + list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance() + .constructCollectionType(List.class, ExternalAccessPerms.class)); + } + // If role name or role functions are updated then delete + // record in External System and add new record to avoid + // conflicts + boolean isRoleNameChanged = false; + if (!desc.equals(updateExtRole.getName())) { + isRoleNameChanged = true; + 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); + } + 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); + } + // Delete role in External System if role is inactive + if (!updateExtRole.getActive()) { + deleteRoleInExtSystem(mapper, name); + } + if (!isRoleNameChanged) { + response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, + list); + } + } + } else { + // It seems like role exists in local DB but not in External + // Access system + if (updateExtRole.getActive()) { + addRole(updateExtRole, app.getUebKey()); + ExternalAccessRolePerms extAddRolePerms = null; + ExternalAccessPerms extAddPerms = null; + List<RoleFunction> 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<String> deleteResponse; + Map<String, String> 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<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception { + boolean response; + Map<String, RoleFunction> updateRoleFunc = new HashMap<>(); + for (RoleFunction addPerm : roleFunctionListNew) { + updateRoleFunc.put(addPerm.getCode(), addPerm); + } + final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>(); + final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>(); + list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())); + // Update permissions in the ExternalAccess System + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + if (!list.isEmpty()) { + for (ExternalAccessPerms perm : list) { + RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1) + + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction()); + if (roleFunc == null) { + RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance()); + if (roleFuncPipeFilter == null) + removePermForRole(perm, mapper, name, headers); + } + extRolePermMap.put(perm.getInstance(), perm); + extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE + + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm); + } + } + response = true; + if (!roleFunctionListNew.isEmpty()) { + for (RoleFunction roleFunc : roleFunctionListNew) { + if (roleFunc.getCode().contains(FUNCTION_PIPE)) { + ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode()); + if (perm == null) { + response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers, + roleFunc); + } + } else { + if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) { + response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers, + roleFunc); + } + } + } + } + return response; + } + + /* + * Adds function to the role in the external auth system while editing a role or + * updating new functions to a role + * + */ + private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper, + HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException { + boolean response; + ExternalAccessRolePerms extRolePerms; + ExternalAccessPerms extPerms; + String code = ""; + String type = ""; + String action = ""; + if (roleFunc.getCode().contains(FUNCTION_PIPE)) { + code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + type = EcompPortalUtils.getFunctionType(roleFunc.getCode()); + action = getFunctionCodeAction(roleFunc.getCode()); + } else { + code = roleFunc.getCode(); + type = roleFunc.getCode().contains("menu") ? "menu" : "url"; + action = "*"; + } + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action); + extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity<String> 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, + "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}", + addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", + updateRolePerms, addResponse.getStatusCode().value()); + } + return response; + } + + private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper, + EPApp app, Role updateExtRole) throws Exception { + for (ExternalAccessPerms perm : permslist) { + if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) { + ExternalAccessRolePerms extAddGlobalRolePerms = null; + ExternalAccessPerms extAddPerms = null; + extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction()); + extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms, + app.getNameSpace() + "." + updateExtRole.getName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(addPerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + try { + ResponseEntity<String> addResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201) { + logger.debug(EELFLoggerDelegate.debugLogger, + "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in External Auth system something went wrong! due to {} and statuscode: {}", + addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, + "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ", + addResponse.getStatusCode().value()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e); + } + } + } + } + + @SuppressWarnings("unchecked") + private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, + List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo) + throws Exception { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole"); + // GET Permissions from External Auth System + JSONArray extPerms = getExtAuthPermissions(app); + List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms); + final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>(); + final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>(); + final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>(); + final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>(); + for (ExternalAccessPermsDetail permDetail : permsDetailList) { + existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail); + existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail); + } + // Add If function does not exists for role in External Auth System + for (RoleFunction roleFunc : roleFunctionListNew) { + String roleFuncCode = ""; + ExternalAccessPermsDetail permsDetail; + if (roleFunc.getCode().contains(FUNCTION_PIPE)) { + roleFuncCode = roleFunc.getCode(); + permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode()); + } else { + roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + permsDetail = existingPermsWithRoles.get(roleFuncCode); + } + if (null == permsDetail.getRoles() + || !permsDetail.getRoles() + .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + + epRoleList.get(0).getName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_"))) { + addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo); + } + userRquestedFunctionsMap.put(roleFuncCode, roleFunc); + userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc); + } + // Delete functions if exists in External Auth System but not in + // incoming + // request + final Map<String, Long> epAppRoleFuncParams = new HashMap<>(); + epAppRoleFuncParams.put("requestedAppId", app.getId()); + epAppRoleFuncParams.put("roleId", updateExtRole.getId()); + List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService + .executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null); + for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) { + String globalRoleFuncWithoutPipes = ""; + RoleFunction roleFunc = null; + if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) { + globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd(); + roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes); + } else { + globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd()); + roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes); + } + if (roleFunc == null) { + ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) + ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) + : existingPermsWithRoles.get(globalRoleFuncWithoutPipes); + ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), + EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), + permDetailFromMap.getAction()); + String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + removePermForRole(perm, mapper, roleName, headers); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e); + throw e; + } + } + + private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, + ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem"); + ExternalAccessRolePerms extAddRolePerms = null; + ExternalAccessPerms extAddPerms = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String code = ""; + String type = ""; + String action = ""; + if (addFunction.getCode().contains(FUNCTION_PIPE)) { + code = EcompPortalUtils.getFunctionCode(addFunction.getCode()); + type = getFunctionCodeType(addFunction.getCode()); + action = getFunctionCodeAction(addFunction.getCode()); + } else { + code = addFunction.getCode(); + type = addFunction.getCode().contains("menu") ? "menu" : "url"; + action = "*"; + } + extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action); + extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole + .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String updateRolePerms = mapper.writeValueAsString(extAddRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201) { + 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 { + logger.debug(EELFLoggerDelegate.debugLogger, + "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ", + addResponse.getStatusCode().value()); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e); + throw e; + } + } + + private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms, + HttpHeaders headers) throws JsonProcessingException { + boolean response; + String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity<String> 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; + } + + /** + * + * It converts list of functions in updateExtRole parameter to the RoleFunction + * object + * + * @param updateExtRole + * @return list of functions + */ + @SuppressWarnings("unchecked") + private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) { + Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions(); + List<RoleFunction> roleFunctionList = new ArrayList<>(); + ObjectMapper roleFuncMapper = new ObjectMapper(); + Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class); + roleFunctionList.add(roleFunction); + } + return roleFunctionList.stream().distinct().collect(Collectors.toList()); + } + + /** + * It delete permissions/functions in the external auth system + * + * @param perm + * @param permMapper + * @param name + * @param headers + * @throws JsonProcessingException + * @throws Exception + */ + private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers) + throws ExternalAuthSystemException, JsonProcessingException { + ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name); + String permDetails = permMapper.writeValueAsString(extAccessRolePerms); + try { + HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails); + ResponseEntity<String> deletePermResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class); + if (deletePermResponse.getStatusCode().value() != 200) { + throw new ExternalAuthSystemException(deletePermResponse.getBody()); + } + logger.debug(EELFLoggerDelegate.debugLogger, + "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}", + permDetails, deletePermResponse.getStatusCode().value()); + } catch (Exception e) { + if (e.getMessage().contains("404")) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", + permDetails, e.getMessage()); + } else { + throw e; + } + } + } + + /** + * It will create new role in the External Auth System + * + * @param newRole + * @param app + * @return true if successfully added in the system else false + * @throws Exception If fails to add role in the system + */ + private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) + throws Exception, HttpClientErrorException { + try { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + ObjectMapper mapper = new ObjectMapper(); + String addNewRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + extRole.setDescription(String.valueOf(newRole.get(0).getName())); + addNewRole = mapper.writeValueAsString(extRole); + HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole); + ResponseEntity<String> addNewRoleInExternalSystem = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, postEntity, String.class); + if (addNewRoleInExternalSystem.getStatusCode().value() == 201) { + logger.debug(EELFLoggerDelegate.debugLogger, + "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}", + addNewRole, addNewRoleInExternalSystem.getStatusCode().value()); + } + } catch (HttpClientErrorException ht) { + dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null); + logger.error(EELFLoggerDelegate.debugLogger, + "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht); + throw new HttpClientErrorException(ht.getStatusCode()); + } + } + + /** + * + * It updates existing role in the External Auth System + * + * @param addRole It Contains role information + * @param app + * @return string which is formatted to match with the external auth system + * @throws JsonProcessingException + */ + private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + String addNewRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + extRole.setName(app.getNameSpace() + "." + addRole.getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + extRole.setDescription(String.valueOf(addRole.getName())); + addNewRole = mapper.writeValueAsString(extRole); + return addNewRole; + } + + /** + * It create a role in the external auth system and then in our local + * + * @param addRoleInDB + * @param app + * @return true else false + * @throws Exception + */ + @SuppressWarnings("unchecked") + @Transactional(rollbackFor = Exception.class) + public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { + boolean result = false; + EPRole epRole = null; + Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions(); + List<RoleFunction> roleFunctionListNew = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFunction); + } + List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList()); + try { + if (addRoleInDB.getId() == null) { // check if it is new role + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + checkIfRoleExitsInExternalSystem(addRoleInDB, app); + } + EPRole epRoleNew = new EPRole(); + epRoleNew.setActive(addRoleInDB.getActive()); + epRoleNew.setName(addRoleInDB.getName()); + epRoleNew.setPriority(addRoleInDB.getPriority()); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleNew.setAppId(null); + } else { + epRoleNew.setAppId(app.getId()); + } + dataAccessService.saveDomainObject(epRoleNew, null); + List<EPRole> getRoleCreated = null; + final Map<String, String> epAppRoleParams = new HashMap<>(); + final Map<String, String> epAppPortalRoleParams = new HashMap<>(); + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epAppRoleParams.put("appId", String.valueOf(app.getId())); + epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName()); + List<EPRole> roleCreated = dataAccessService + .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null); + EPRole epUpdateRole = roleCreated.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + epAppRoleParams, null); + } else { + epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName()); + getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, + epAppPortalRoleParams, null); + } + // Add role in External Auth system + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + addNewRoleInExternalSystem(getRoleCreated, app); + } + result = true; + } else { // if role already exists then update it + EPRole globalRole = null; + List<EPRole> applicationRoles; + List<EPRole> globalRoleList = getGlobalRolesOfPortal(); + boolean isGlobalRole = false; + if (!globalRoleList.isEmpty()) { + EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny() + .orElse(null); + if (role != null) { + globalRole = role; + isGlobalRole = true; + } + } + if (app.getId().equals(PortalConstants.PORTAL_APP_ID) + || (globalRole != null && app.getId() != globalRole.getAppId())) { + applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId()); + } else { + applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app); + } + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole); + // Add all user to the re-named role in external auth system + if (!applicationRoles.isEmpty() + && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) { + bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(), + addRoleInDB.getName()); + } + } + deleteRoleFunction(app, applicationRoles); + if (!applicationRoles.isEmpty()) { + epRole = applicationRoles.get(0); + epRole.setName(addRoleInDB.getName()); + epRole.setPriority(addRoleInDB.getPriority()); + epRole.setActive(addRoleInDB.getActive()); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRole.setAppId(null); + epRole.setAppRoleId(null); + } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) + && applicationRoles.get(0).getAppRoleId() == null) { + epRole.setAppRoleId(epRole.getId()); + } + dataAccessService.saveDomainObject(epRole, null); + } + Long roleAppId = null; + if (globalRole != null && !app.getId().equals(globalRole.getAppId())) + roleAppId = PortalConstants.PORTAL_APP_ID; + saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId); + result = true; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e); + throw e; + } + return result; + } + + /** + * + * It validates whether role exists in external auth system + * + * @param checkRole + * @param app + * @throws Exception If role exits + */ + private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception { + getNameSpaceIfExists(app); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String roleName = app.getNameSpace() + "." + checkRole.getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"); + HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> checkRoleInExternalSystem = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" + + roleName, HttpMethod.GET, checkRoleEntity, String.class); + if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) { + logger.debug( + "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", + checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value()); + throw new ExternalAuthSystemException(" Role already exists in external system"); + } + } + + /** + * It saves list of functions to the role in portal + * + * @param roleFunctionListNew + * @param app + * @param applicationRoles + * @throws Exception + */ + @SuppressWarnings("unchecked") + private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles, + Long roleAppId) throws Exception { + final Map<String, String> getAppFunctionParams = new HashMap<>(); + for (RoleFunction roleFunc : roleFunctionListNew) { + String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + EPAppRoleFunction appRoleFunc = new EPAppRoleFunction(); + appRoleFunc.setAppId(app.getId()); + appRoleFunc.setRoleId(applicationRoles.get(0).getId()); + appRoleFunc.setRoleAppId(String.valueOf(roleAppId)); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + // query to check if function code has pipes + List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, + getAppFunctionParams, null); + if (roleFunction.isEmpty()) { + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code); + roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null); + } + if (roleFunction.size() > 1) { + CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction); + appRoleFunc.setCode(getExactFunctionCode.getCode()); + } else { + appRoleFunc.setCode(roleFunction.get(0).getCode()); + } + dataAccessService.saveDomainObject(appRoleFunc, null); + } + } + + /** + * + * It filters the app functions which starts with similar name in the result set + * + * @param roleFunc + * @param roleFunction + * @return CentralRoleFunction + */ + private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) { + final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>(); + final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>(); + CentralV2RoleFunction getExactFunctionCode = null; + for (CentralV2RoleFunction cenRoleFunction : roleFunction) { + appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction); + appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction); + } + getExactFunctionCode = appFunctionsFilter.get(roleFuncCode); + if (getExactFunctionCode == null) { + getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode); + } + return getExactFunctionCode; + } + + /** + * It deletes all EPAppRoleFunction records in the portal + * + * @param app + * @param role + */ + @SuppressWarnings("unchecked") + private void deleteRoleFunction(EPApp app, List<EPRole> role) { + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", role.get(0).getId()); + List<EPAppRoleFunction> appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null); + if (!appRoleFunctionList.isEmpty()) { + for (EPAppRoleFunction approleFunction : appRoleFunctionList) { + dataAccessService.deleteDomainObject(approleFunction, null); + } + } + } + + @Override + @SuppressWarnings("unchecked") + public List<EPUser> getUser(String loginId) throws InvalidUserException { + final Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", loginId); + List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null); + if (userList.isEmpty()) { + throw new InvalidUserException("User not found"); + } + return userList; + } + + @Override + public String getV2UserWithRoles(String loginId, String uebkey) throws Exception { + final Map<String, String> params = new HashMap<>(); + List<EPUser> userList = null; + CentralV2User cenV2User = null; + String result = null; + try { + params.put("orgUserIdValue", loginId); + List<EPApp> appList = getApp(uebkey); + if (!appList.isEmpty()) { + userList = getUser(loginId); + if (!userList.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + cenV2User = getV2UserAppRoles(loginId, uebkey); + result = mapper.writeValueAsString(cenV2User); + } else if (userList.isEmpty()) { + throw new InvalidUserException("User not found"); + } + } else { + throw new InactiveApplicationException("Application not found"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e); + throw e; + } + return result; + } + + @Override + public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp"); + List<CentralV2Role> roleList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + try { + List<EPApp> app = getApp(uebkey); + List<EPRole> appRolesList = getAppRoles(app.get(0).getId()); + roleList = createCentralRoleObject(app, appRolesList, roleList, params); + if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) { + List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId()); + List<EPRole> globalRolesList = getGlobalRolesOfPortal(); + List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>(); + if (!globalRolesList.isEmpty()) { + for (EPRole eprole : globalRolesList) { + CentralV2Role cenRole = convertRoleToCentralV2Role(eprole); + portalsGlobalRolesFinlaList.add(cenRole); + } + roleList.addAll(globalRoleList); + for (CentralV2Role role : portalsGlobalRolesFinlaList) { + CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny() + .orElse(null); + if (result == null) + roleList.add(role); + } + } else { + for (EPRole role : globalRolesList) { + CentralV2Role cenRole = convertRoleToCentralV2Role(role); + roleList.add(cenRole); + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e); + throw e; + } + logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!"); + return roleList.stream().distinct().collect(Collectors.toList()); + } + + @SuppressWarnings("unchecked") + @Override + public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<CentralV2RoleFunction> finalRoleList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, + null); + for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) { + String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode()); + String type = ""; + if (roleFuncItem.getCode().contains("|")) + type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode()); + else + type = getFunctionCodeType(roleFuncItem.getCode()); + String action = getFunctionCodeAction(roleFuncItem.getCode()); + roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code)); + roleFuncItem.setType(type); + roleFuncItem.setAction(action); + finalRoleList.add(roleFuncItem); + } + return finalRoleList; + } + + @Override + public String getFunctionCodeAction(String roleFuncItem) { + return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem); + } + + @Override + public String getFunctionCodeType(String roleFuncItem) { + String type = null; + if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu")) + || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) { + type = "menu"; + } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem) + || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) { + type = "url"; + } else if (roleFuncItem.contains(FUNCTION_PIPE) + && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) { + type = EcompPortalUtils.getFunctionType(roleFuncItem); + } + return type; + } + + /** + * + * It check whether function code has no pipes and no url string in it + * + * @param roleFuncItem + * @return true or false + */ + private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) { + return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url"); + } + + /** + * + * It check whether function code has pipes and url string in it + * + * @param roleFuncItem + * @return true or false + */ + private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) { + return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url"); + } + + /** + * + * It check whether function code has no pipes and has url string in it + * + * @param roleFuncItem + * @return true or false + */ + private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) { + return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url"); + } + + /** + * It returns user detail information which is deep copy of EPUser.class object + * + * @param userInfo + * @param userAppSet + * @param app + * @return + * @throws Exception + */ + @SuppressWarnings("unchecked") + private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception { + final Map<String, Long> params = new HashMap<>(); + CentralV2User userAppList = new CentralV2User(); + CentralV2User user1 = null; + final Map<String, Long> params1 = new HashMap<>(); + List<EPRole> globalRoleList = new ArrayList<>(); + try { + if (app.getId() != PortalConstants.PORTAL_APP_ID) { + params1.put("userId", userInfo.getId()); + params1.put("appId", app.getId()); + globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null); + } + userAppList.setUserApps(new TreeSet<CentralV2UserApp>()); + for (EPUserApp userApp : userAppSet) { + if (userApp.getRole().getActive()) { + EPApp epApp = userApp.getApp(); + String globalRole = userApp.getRole().getName().toLowerCase(); + if (((epApp.getId().equals(app.getId())) + && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))) + || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) + && (globalRole.toLowerCase().startsWith("global_")))) { + CentralV2UserApp cua = new CentralV2UserApp(); + cua.setUserId(null); + CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(), + epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(), + epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(), + epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(), + epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(), + String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()), + epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(), + epApp.getUebTopicName()); + cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); + cua.setApp(cenApp); + Long appId = null; + if (globalRole.toLowerCase().startsWith("global_") + && epApp.getId().equals(PortalConstants.PORTAL_APP_ID) + && !epApp.getId().equals(app.getId())) { + appId = app.getId(); + EPRole result = null; + if (globalRoleList.size() > 0) + result = globalRoleList.stream() + .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny() + .orElse(null); + if (result == null) + continue; + } else { + appId = userApp.getApp().getId(); + } + params.put("roleId", userApp.getRole().getId()); + params.put(APP_ID, appId); + List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet<CentralV2RoleFunction> 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, type, action, null); + roleFunctionSet.add(cenRoleFunc); + } + Long userRoleId = null; + if (globalRole.toLowerCase().startsWith("global_") + || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) { + userRoleId = userApp.getRole().getId(); + } else { + userRoleId = userApp.getRole().getAppRoleId(); + } + CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(), + userApp.getRole().getModified(), userApp.getRole().getCreatedId(), + userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(), + userApp.getRole().getName(), userApp.getRole().getActive(), + userApp.getRole().getPriority(), roleFunctionSet, null, null); + cua.setRole(cenRole); + userAppList.getUserApps().add(cua); + } + } + } + user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(), + userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(), + userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(), + userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(), + userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(), + userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(), + userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(), + userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(), + userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(), + userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(), + userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(), + userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(), + userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(), + userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(), + userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e); + throw e; + } + return user1; + } + + @Override + public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception { + final Map<String, Long> params = new HashMap<>(); + List<CentralV2Role> roleList = new ArrayList<>(); + CentralV2Role cenRole = new CentralV2Role(); + List<EPRole> roleInfo = null; + List<EPApp> app = null; + try { + app = getApp(uebkey); + if (app.isEmpty()) { + throw new InactiveApplicationException("Application not found"); + } + if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) { + List<EPRole> globalRoleList = new ArrayList<>(); + globalRoleList = getGlobalRolesOfPortal(); + if (globalRoleList.size() > 0) { + EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny() + .orElse(null); + if (result != null) + return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId); + } + } + if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + roleInfo = getPortalAppRoleInfo(roleId); + } else { + roleInfo = getPartnerAppRoleInfo(roleId, app.get(0)); + } + roleList = createCentralRoleObject(app, roleInfo, roleList, params); + if (roleList.isEmpty()) { + return cenRole; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e); + throw e; + } + return roleList.get(0); + } + + @SuppressWarnings("unchecked") + private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) { + List<EPRole> roleInfo; + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", roleId); + getPartnerAppRoleParams.put("appId", app.getId()); + roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null); + if (roleInfo.isEmpty()) { + getPartnerAppRoleParams.put("appRoleId", roleId); + roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null); + } + return roleInfo; + } + + @SuppressWarnings("unchecked") + private List<EPRole> getPortalAppRoleInfo(Long roleId) { + List<EPRole> roleInfo; + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", roleId); + roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null); + return roleInfo; + } + + /** + * + * It returns list of app roles along with role functions and which went through + * deep copy + * + * @param app + * @param roleInfo + * @param roleList + * @param params + * @return + * @throws DecoderException + */ + @SuppressWarnings("unchecked") + @Override + public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo, + List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException { + for (EPRole role : roleInfo) { + params.put("roleId", role.getId()); + params.put(APP_ID, app.get(0).getId()); + List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList", + params, null); + SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>(); + for (CentralV2RoleFunction roleFunc : cenRoleFuncList) { + String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + functionCode = EPUserUtils.decodeFunctionCode(functionCode); + String type = getFunctionCodeType(roleFunc.getCode()); + String action = getFunctionCodeAction(roleFunc.getCode()); + CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode, + roleFunc.getName(), null, type, action, null); + roleFunctionSet.add(cenRoleFunc); + } + SortedSet<CentralV2Role> childRoles = new TreeSet<>(); + SortedSet<CentralV2Role> parentRoles = new TreeSet<>(); + CentralV2Role cenRole = null; + if (role.getAppRoleId() == null) { + cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), + role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(), + roleFunctionSet, childRoles, parentRoles); + } else { + cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(), + role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), + role.getPriority(), roleFunctionSet, childRoles, parentRoles); + } + roleList.add(cenRole); + } + return roleList; + } + + @SuppressWarnings("unchecked") + @Override + public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception { + String code = EcompPortalUtils.getFunctionCode(functionCode); + String encodedCode = EcompPortalUtils.encodeFunctionCode(code); + CentralV2RoleFunction roleFunc = null; + EPApp app = getApp(uebkey).get(0); + List<CentralV2RoleFunction> getRoleFuncList = null; + final Map<String, String> params = new HashMap<>(); + try { + params.put(FUNCTION_CODE_PARAMS, functionCode); + params.put(APP_ID, String.valueOf(app.getId())); + getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); + if (getRoleFuncList.isEmpty()) { + params.put(FUNCTION_CODE_PARAMS, encodedCode); + getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); + if (getRoleFuncList.isEmpty()) { + return roleFunc; + } + } + if (getRoleFuncList.size() > 1) { + CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList); + if (cenV2RoleFunction == null) + return roleFunc; + roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction); + } else { + // 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); + throw e; + } + return roleFunc; + } + + private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) { + CentralV2RoleFunction roleFunc; + String functionCodeFormat = getRoleFuncList.getCode(); + if (functionCodeFormat.contains(FUNCTION_PIPE)) { + String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat); + String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat); + String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat); + roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat, + getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, + newfunctionActionFormat, getRoleFuncList.getEditUrl()); + } else { + roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(), + getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl()); + } + return roleFunc; + } + + @Override + public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + boolean saveOrUpdateFunction = false; + try { + if(EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getCode())) + domainCentralRoleFunction.setCode(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getCode())); + final Map<String, String> functionParams = new HashMap<>(); + functionParams.put("appId", String.valueOf(app.getId())); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + addRoleFunctionInExternalSystem(domainCentralRoleFunction, app); + } + if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) { + domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE + + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction()); + } + domainCentralRoleFunction.setAppId(app.getId()); + dataAccessService.saveDomainObject(domainCentralRoleFunction, null); + saveOrUpdateFunction = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e); + throw e; + } + return saveOrUpdateFunction; + } + + /** + * It creates application permission in external auth system + * + * @param domainCentralRoleFunction + * @param app + * @throws Exception + */ + private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String type = ""; + String instance = ""; + String action = ""; + if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) + || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) { + type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) + ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) + : domainCentralRoleFunction.getType(); + instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) + ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) + : domainCentralRoleFunction.getCode(); + action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) + ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) + : domainCentralRoleFunction.getAction(); + } else { + type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + instance = domainCentralRoleFunction.getCode(); + action = "*"; + } + // get Permissions from External Auth System + JSONArray extPermsList = getExtAuthPermissions(app); + List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList); + String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action; + boolean checkIfFunctionsExits = permsDetailList.stream() + .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm)); + if (!checkIfFunctionsExits) { + try { + extPerms.setAction(action); + extPerms.setInstance(instance); + extPerms.setType(app.getNameSpace() + "." + type); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String addFunction = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(addFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); + ResponseEntity<String> addPermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "addRoleFunctionInExternalSystem: 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, + "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e); + throw e; + } + } else { + try { + extPerms.setAction(action); + extPerms.setInstance(instance); + extPerms.setType(app.getNameSpace() + "." + type); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRoleFunction = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction); + ResponseEntity<String> updatePermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.PUT, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", + updateRoleFunction, updatePermResponse.getStatusCode().value()); + } 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, + "addRoleFunctionInExternalSystem: Failed to update function in external central auth system", + e); + throw e; + } + } + } + + @SuppressWarnings("unchecked") + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteCentralRoleFunction(String code, EPApp app) { + boolean deleteFunctionResponse = false; + try { + final Map<String, String> params = new HashMap<>(); + params.put(FUNCTION_CODE_PARAMS, code); + params.put(APP_ID, String.valueOf(app.getId())); + List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService + .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); + CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + deleteRoleFunctionInExternalSystem(appFunctionCode, app); + // Delete role function dependency records + deleteAppRoleFunctions(appFunctionCode.getCode(), app); + } + dataAccessService.deleteDomainObject(appFunctionCode, null); + deleteFunctionResponse = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e); + } + return deleteFunctionResponse; + } + + /** + * It deletes app function record in portal + * + * @param code + * @param app + */ + private void deleteAppRoleFunctions(String code, EPApp app) { + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, + APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null); + } + + /** + * + * It deletes permission in the external auth system + * + * @param domainCentralRoleFunction + * @param app + * @throws Exception + */ + private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + try { + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()); + String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode()); + String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode()); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + extPerms.setAction(actionValue); + extPerms.setInstance(instanceValue); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String deleteRoleFunction = mapper.writeValueAsString(extPerms); + HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction); + ResponseEntity<String> delPermResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "perm?force=true", HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ", + deleteRoleFunction, delPermResponse.getStatusCode().value()); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to delete functions in External System", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, + " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system but exists in local DB", + e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e); + } + } + } + + @Override + public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception { + boolean response = false; + String message = ""; + try { + EPApp app = getApp(uebkey).get(0); + addRoleInEcompDB(saveRole, app); + response = true; + } catch (Exception e) { + message = e.getMessage(); + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e); + } + return new ExternalRequestFieldsValidator(response, message); + } + + @SuppressWarnings("unchecked") + @Override + public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception { + Session localSession = sessionFactory.openSession(); + Transaction transaction = null; + boolean result = false; + try { + List<EPRole> epRoleList = null; + EPApp app = getApp(uebkey).get(0); + final Map<String, String> deleteRoleParams = new HashMap<>(); + deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null); + } else { + deleteRoleParams.put(APP_ID, String.valueOf(app.getId())); + epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + deleteRoleParams, null); + } + if (!epRoleList.isEmpty()) { + transaction = localSession.beginTransaction(); + // Delete app role functions before deleting role + deleteRoleFunction(app, epRoleList); + if (app.getId() == 1) { + // Delete fn_user_ role + dataAccessService.deleteDomainObjects(EPUserApp.class, + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + boolean isPortalRequest = false; + deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest); + } + deleteRoleInExternalAuthSystem(epRoleList, app); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction"); + dataAccessService.deleteDomainObject(epRoleList.get(0), null); + } + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e); + result = false; + } finally { + localSession.close(); + } + return result; + } + + /** + * + * It deletes role for application in external auth system + * + * @param epRoleList contains role information + * @param app contains application information + * @throws Exception + */ + private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception { + ResponseEntity<String> deleteResponse; + ResponseEntity<String> res = getNameSpaceIfExists(app); + if (res.getStatusCode() == HttpStatus.OK) { + // Delete Role in External System + 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) { + EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode()); + logger.error(EELFLoggerDelegate.errorLogger, + "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ", + deleteResponse.getBody()); + } + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction"); + } + } + + /** + * + * It deletes application user role in external auth system + * + * @param role + * @param app + * @param LoginId + * @throws Exception + */ + private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + getNameSpaceIfExists(app); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> getResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" + + LoginId + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + + "/" + app.getNameSpace() + "." + + role.getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", + getResponse.getBody()); + if (getResponse.getStatusCode().value() != 200) { + throw new ExternalAuthSystemException(getResponse.getBody()); + } + String res = getResponse.getBody(); + if (!res.equals(IS_EMPTY_JSON_STRING)) { + HttpEntity<String> userRoleentity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + ResponseEntity<String> deleteResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" + + LoginId + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + + "/" + app.getNameSpace() + "." + + role.getName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + HttpMethod.DELETE, userRoleentity, String.class); + if (deleteResponse.getStatusCode().value() != 200) { + throw new ExternalAuthSystemException("Failed to delete user role"); + } + logger.debug(EELFLoggerDelegate.debugLogger, + "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", + deleteResponse.getStatusCode().value()); + } + } + + @SuppressWarnings("unchecked") + @Override + public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception { + List<CentralV2Role> roleList = new ArrayList<>(); + try { + List<EPApp> app = getApp(uebkey); + final Map<String, Long> params = new HashMap<>(); + // check if portal + Long appId = null; + if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + appId = app.get(0).getId(); + } + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE); + Criterion appIdCrt; + if (appId == null) + appIdCrt = Restrictions.isNull("appId"); + else + appIdCrt = Restrictions.eq("appId", appId); + Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt); + restrictionsList.add(andCrit); + List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null); + roleList = createCentralRoleObject(app, epRole, roleList, params); + List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId()); + if (globalRoleList.size() > 0) + roleList.addAll(globalRoleList); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e); + throw e; + } + return roleList; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) + throws Exception { + Session localSession = sessionFactory.openSession(); + String message = ""; + Transaction transaction = null; + boolean response = false; + EPApp app = null; + try { + transaction = localSession.beginTransaction(); + List<EPRole> epRoleList = null; + app = getApp(uebkey).get(0); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleList = getPortalAppRoleInfo(roleId); + } else { + epRoleList = getPartnerAppRoleInfo(roleId, app); + } + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Delete User Role in External System before deleting role + deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId); + } + // Delete user app roles + dataAccessService.deleteDomainObjects(EPUserApp.class, + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + boolean isPortalRequest = false; + deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest); + transaction.commit(); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Final call to delete role once all dependencies has been + // deleted + deleteRoleInExternalAuthSystem(epRoleList, app); + } + dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction"); + response = true; + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + message = e.getMessage(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e); + EcompPortalUtils.rollbackTransaction(transaction, + "deleteDependencyRoleRecord rollback, exception = " + e.toString()); + message = e.getMessage(); + } finally { + localSession.close(); + } + return new ExternalRequestFieldsValidator(response, message); + } + + @Override + @SuppressWarnings("unchecked") + @Transactional + public void syncRoleFunctionFromExternalAccessSystem(EPApp app) { + try { + // get Permissions from External Auth System + JSONArray extPerms = getExtAuthPermissions(app); + List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms); + // get functions in DB + final Map<String, Long> params = new HashMap<>(); + final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", + params, null); + if (!appFunctions.isEmpty()) { + for (CentralV2RoleFunction roleFunc : appFunctions) { + roleFuncMap.put(roleFunc.getCode(), roleFunc); + } + } + // get Roles for portal in DB + List<EPRole> portalRoleList = getGlobalRolesOfPortal(); + final Map<String, EPRole> existingPortalRolesMap = new HashMap<>(); + for (EPRole epRole : portalRoleList) { + existingPortalRolesMap.put(epRole.getName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole); + } + // get Roles in DB + final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app); + // store External Permissions with Pipe and without Pipe (just + // instance) + final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>(); + final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>(); + for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) { + extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe); + String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance()); + extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe); + } + // Add if new functions and app role functions were added in + // external auth system + for (ExternalAccessPermsDetail permsDetail : permsDetailList) { + String code = permsDetail.getInstance(); + CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance()); + List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code, + getFunctionCodeKey); + List<String> roles = permsDetail.getRoles(); + if (roles != null) { + // Check if function has any roles and which does not exist + // in External Auth System. If exists delete in local + addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, + existingPortalRolesMap); + } + } + // Check if function does exits in External Auth System but exits in + // local then delete function and its dependencies + for (CentralV2RoleFunction roleFunc : appFunctions) { + try { + ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap + .get(roleFunc.getCode()); + if (null == getFunctionCodeContainsPipeKey) { + ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode()); + if (null == getFunctionCodeKey) { + deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e); + } + } + + @SuppressWarnings("unchecked") + private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB, + List<CentralV2RoleFunction> roleFunctionList, List<String> roles, + Map<String, EPRole> existingPortalRolesMap) throws Exception { + if (!roleFunctionList.isEmpty()) { + final Map<String, String> appRoleFuncParams = new HashMap<>(); + final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>(); + final Map<String, String> currentRolesInExtSystem = new HashMap<>(); + appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode()); + appRoleFuncParams.put("appId", String.valueOf(app.getId())); + List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions", + appRoleFuncParams, null); + for (LocalRole localRole : localRoleList) { + currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole); + } + for (String addRole : roles) { + currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole); + } + for (String extAuthrole : roles) { + String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE)); + boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, + app.getNameSpace()); + if (isNameSpaceMatching) { + if (!currentAppRoleFunctionsMap + .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) { + EPRole localAddFuntionRole = currentRolesInDB + .get(extAuthrole.substring(app.getNameSpace().length() + 1)); + if (localAddFuntionRole == null) { + checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole); + } else { + EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); + addAppRoleFunc.setAppId(app.getId()); + addAppRoleFunc.setCode(roleFunctionList.get(0).getCode()); + addAppRoleFunc.setRoleId(localAddFuntionRole.getId()); + dataAccessService.saveDomainObject(addAppRoleFunc, null); + } + } + // This block is to save global role function if exists + } else { + String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1); + boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName); + if (checkIfGlobalRoleExists) { + final Map<String, Long> params = new HashMap<>(); + EPRole role = existingPortalRolesMap.get(extAuthAppRoleName); + EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction(); + params.put("appId", app.getId()); + params.put("roleId", role.getId()); + List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService + .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null); + boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream() + .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode() + .equals(roleFunctionList.get(0).getCode())); + if (role != null && !checkIfRoleFunctionExists) { + addGlobalRoleFunctions.setAppId(app.getId()); + addGlobalRoleFunctions.setRoleId(role.getId()); + if (!app.getId().equals(role.getAppRoleId())) { + addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString()); + } else { + addGlobalRoleFunctions.setRoleAppId(null); + } + addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode()); + dataAccessService.saveDomainObject(addGlobalRoleFunctions, null); + } + } + } + } + for (LocalRole localRoleDelete : localRoleList) { + if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) { + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, + APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode() + + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(), + null); + } + } + } + } + + private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) { + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode()); + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, + APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode()); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode()); + dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class, + APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode()); + } + + private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB, + List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception { + if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) { + Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1)); + addRoleDescriptionInExtSystem(role, app); + if (!roleFunctionList.isEmpty()) { + try { + if (!roleFunctionList.isEmpty()) { + EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); + addAppRoleFunc.setAppId(app.getId()); + addAppRoleFunc.setCode(roleFunctionList.get(0).getCode()); + addAppRoleFunc.setRoleId(role.getId()); + dataAccessService.saveDomainObject(addAppRoleFunc, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e); + } + } + } + } + + @SuppressWarnings("unchecked") + private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, + final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code, + CentralV2RoleFunction getFunctionCodeKey) { + String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code, + getFunctionCodeKey); + final Map<String, String> appSyncFuncsParams = new HashMap<>(); + appSyncFuncsParams.put("appId", String.valueOf(app.getId())); + appSyncFuncsParams.put("functionCd", finalFunctionCodeVal); + List<CentralV2RoleFunction> roleFunctionList = null; + roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, + null); + if (roleFunctionList.isEmpty()) { + appSyncFuncsParams.put("functionCd", code); + roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, + null); + } + return roleFunctionList; + } + + private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap, + ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) { + String finalFunctionCodeVal = ""; + if (null == getFunctionCodeKey) { + finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance()); + CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal); + // If function does not exist in local then add! + if (null == checkIfCodeStillExits) { + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code); + addFunctionInEcompDB(app, permsDetail, code); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code); + } + } + return finalFunctionCodeVal; + } + + @SuppressWarnings("unchecked") + @Override + public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) { + final Map<String, EPRole> currentRolesInDB = new HashMap<>(); + List<EPRole> getCurrentRoleList = null; + final Map<String, Long> appParams = new HashMap<>(); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null); + } else { + appParams.put("appId", app.getId()); + getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null); + } + for (EPRole role : getCurrentRoleList) { + currentRolesInDB.put(role.getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role); + } + return currentRolesInDB; + } + + @SuppressWarnings("unchecked") + private Map<String, EPRole> getAppRoleNamesMap(EPApp app) { + final Map<String, EPRole> currentRolesInDB = new HashMap<>(); + List<EPRole> getCurrentRoleList = null; + final Map<String, Long> appParams = new HashMap<>(); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null); + } else { + appParams.put("appId", app.getId()); + getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null); + } + for (EPRole role : getCurrentRoleList) { + currentRolesInDB.put(role.getName(), role); + } + return currentRolesInDB; + } + + private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException { + ExternalAccessPermsDetail permDetails = null; + List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>(); + for (int i = 0; i < extPerms.length(); i++) { + String description = null; + if (extPerms.getJSONObject(i).has("description")) { + description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); + } else { + description = extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + "|" + + extPerms.getJSONObject(i).getString("instance") + "|" + + extPerms.getJSONObject(i).getString("action"); + } + if (extPerms.getJSONObject(i).has("roles")) { + ObjectMapper rolesListMapper = new ObjectMapper(); + JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); + List<String> list = rolesListMapper.readValue(resRoles.toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE + + extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString("action"), list, description); + permsDetailList.add(permDetails); + } else { + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE + + extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString("action"), description); + permsDetailList.add(permDetails); + } + } + return permsDetailList; + } + + private JSONArray getExtAuthPermissions(EPApp app) throws Exception { + ResponseEntity<String> response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ", + response.getBody()); + JSONObject jsonObj = new JSONObject(res); + JSONArray extPerms = jsonObj.getJSONArray("perm"); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) { + extPerms.remove(i); + i--; + } + } + return extPerms; + } + + /** + * + * Add function into local DB + * + * @param app + * @param permsDetail + * @param code + */ + private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) { + try { + CentralV2RoleFunction addFunction = new CentralV2RoleFunction(); + addFunction.setAppId(app.getId()); + addFunction.setCode(code); + addFunction.setName(permsDetail.getDescription()); + dataAccessService.saveDomainObject(addFunction, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e); + } + } + + /** + * + * It updates description of a role in external auth system + * + * @param role + * @param app + * @throws Exception + */ + private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception { + boolean status = false; + try { + String addRoleNew = updateExistingRoleInExternalSystem(role, app); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.PUT, entity, String.class); + status = true; + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e); + } + return status; + } + + /** + * + * While sync functions form external auth system if new role found we should + * add in local and return Role.class object + * + * @param app + * @param role + * @return + */ + @SuppressWarnings("unchecked") + private Role addRoleInDBIfDoesNotExists(EPApp app, String role) { + Role setNewRole = new Role(); + try { + // functions can have new role created in External Auth System + // prevent + // duplication here + boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app); + final Map<String, String> getRoleByNameParams = new HashMap<>(); + List<EPRole> getRoleCreated = null; + getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role); + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getRoleByNameParams.put("appId", String.valueOf(app.getId())); + List<EPRole> roleCreated = dataAccessService + .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null); + if (!isCreated) { + EPRole epUpdateRole = roleCreated.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getRoleByNameParams, null); + } else { + getRoleCreated = roleCreated; + } + } else { + getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams, + null); + } + if (getRoleCreated != null && !getRoleCreated.isEmpty()) { + EPRole roleObject = getRoleCreated.get(0); + setNewRole.setId(roleObject.getId()); + setNewRole.setName(roleObject.getName()); + setNewRole.setActive(roleObject.getActive()); + setNewRole.setPriority(roleObject.getPriority()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e); + } + return setNewRole; + } + + @SuppressWarnings("unchecked") + private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) { + boolean isCreated = false; + final Map<String, String> roleParams = new HashMap<>(); + roleParams.put(APP_ROLE_NAME_PARAM, role); + List<EPRole> roleCreated = null; + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null); + } else { + roleParams.put("appId", String.valueOf(app.getId())); + roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, + null); + } + if (roleCreated == null || roleCreated.isEmpty()) { + roleParams.put("appId", String.valueOf(app.getId())); + EPRole epRoleNew = new EPRole(); + epRoleNew.setActive(true); + epRoleNew.setName(role); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleNew.setAppId(null); + } else { + epRoleNew.setAppId(app.getId()); + } + dataAccessService.saveDomainObject(epRoleNew, null); + isCreated = false; + } else { + isCreated = true; + } + return isCreated; + } + + @Override + @SuppressWarnings("unchecked") + public Integer bulkUploadFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null); + CentralV2RoleFunction cenRoleFunc = null; + Integer functionsAdded = 0; + try { + for (RoleFunction roleFunc : roleFuncList) { + cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName()); + addRoleFunctionInExternalSystem(cenRoleFunc, app); + functionsAdded++; + } + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e); + } + return functionsAdded; + } + + @Override + public Integer bulkUploadRoles(String uebkey) throws Exception { + List<EPApp> app = getApp(uebkey); + List<EPRole> roles = getAppRoles(app.get(0).getId()); + List<CentralV2Role> cenRoleList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + Integer rolesListAdded = 0; + try { + cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); + String roleList = mapper.writeValueAsString(cenRoleList); + List<Role> roleObjectList = mapper.readValue(roleList, + TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); + for (Role role : roleObjectList) { + addRoleInExternalSystem(role, app.get(0)); + rolesListAdded++; + } + 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<String> 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; + } + return rolesListAdded; + } + + /** + * It creating new role in external auth system while doing bulk upload + * + * @param role + * @param app + * @throws Exception + */ + private void addRoleInExternalSystem(Role role, EPApp app) throws Exception { + String addRoleNew = updateExistingRoleInExternalSystem(role, app); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try { + HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", + e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "addRoleInExternalSystem: Role already exits but does not break functionality", e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage()); + } + } + } + + @Override + @SuppressWarnings("unchecked") + public Integer bulkUploadRolesFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<EPRole> roles = getAppRoles(app.getId()); + final Map<String, Long> params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", + params, null); + if (!appRoleFunc.isEmpty()) { + for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { + addRoleFunctionsInExternalSystem(addRoleFunc, role, app); + roleFunctions++; + } + } + } + } catch (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; + } + + /** + * Its adding a role function while doing bulk upload + * + * @param addRoleFunc + * @param role + * @param app + */ + private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) { + 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() + "." + type, instance, action, + addRoleFunc.getFunctionName()); + extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", + HttpMethod.POST, entity, String.class); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", + e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage()); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", app.getId()); + List<CentralV2RoleFunction> 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<String> entity = new HttpEntity<>(addFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); + ResponseEntity<String> 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<Role> roleList) throws Exception { + EPApp app = getApp(uebkey).get(0); + for (Role role : roleList) { + addRoleInExternalSystem(role, app); + } + } + + @SuppressWarnings("unchecked") + @Override + public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List<EPRole> roles = getAppRoles(app.getId()); + final Map<String, Long> params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List<BulkUploadRoleFunction> appRoleFunc = dataAccessService + .executeNamedQuery("uploadPartnerRoleFunctions", params, null); + if (!appRoleFunc.isEmpty()) { + for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { + addRoleFunctionsInExternalSystem(addRoleFunc, role, app); + roleFunctions++; + } + } + } + // 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<String, Long> params = new HashMap<>(); + params.put("appId", app.getId()); + List<GlobalRoleWithApplicationRoleFunction> 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 { + 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<String> 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 + @Transactional + public void syncApplicationRolesWithEcompDB(EPApp app) { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started"); + // Sync functions and roles assigned to it which also creates new roles if does + // not exits in portal + syncRoleFunctionFromExternalAccessSystem(app); + logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished"); + ObjectMapper mapper = new ObjectMapper(); + logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem"); + // Get Permissions from External Auth System + JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app); + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList"); + // refactoring done + List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole); + List<EPRole> finalRoleList = new ArrayList<>(); + for (ExternalRoleDetails externalRole : externalRoleDetailsList) { + EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole); + finalRoleList.add(ecompRole); + } + List<EPRole> applicationRolesList; + applicationRolesList = getAppRoles(app.getId()); + List<String> applicationRoleIdList = new ArrayList<>(); + for (EPRole applicationRole : applicationRolesList) { + applicationRoleIdList.add(applicationRole.getName()); + } + List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>(); + for (EPRole aafRole : finalRoleList) { + if (!applicationRoleIdList.contains(aafRole.getName())) { + roleListToBeAddInEcompDB.add(aafRole); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem"); + // Check if roles exits in external Access system and if not make inactive in DB + inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList); + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem"); + // Add new roles in DB and updates role description in External Auth System + addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB); + logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished"); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e); + } + } + + /** + * + * It adds new roles in DB and updates description in External Auth System + * + * @param app + * @param roleListToBeAddInEcompDB + */ + @SuppressWarnings("unchecked") + private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) { + EPRole roleToBeAddedInEcompDB; + for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { + try { + roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); + if (app.getId() == 1) { + roleToBeAddedInEcompDB.setAppRoleId(null); + } + dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); + List<EPRole> getRoleCreatedInSync = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + final Map<String, String> globalRoleParams = new HashMap<>(); + globalRoleParams.put("appId", String.valueOf(app.getId())); + globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName()); + getRoleCreatedInSync = dataAccessService + .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null); + EPRole epUpdateRole = getRoleCreatedInSync.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + } + List<EPRole> roleList = new ArrayList<>(); + final Map<String, String> params = new HashMap<>(); + params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName()); + boolean isPortalRole = false; + if (app.getId() == 1) { + isPortalRole = true; + roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null); + } else { + isPortalRole = false; + params.put(APP_ID, app.getId().toString()); + roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, + null); + } + EPRole role = roleList.get(0); + Role aaFrole = new Role(); + aaFrole.setId(role.getId()); + aaFrole.setActive(role.getActive()); + aaFrole.setPriority(role.getPriority()); + aaFrole.setName(role.getName()); + updateRoleInExternalSystem(aaFrole, app, isPortalRole); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e); + } + } + } + + /** + * + * It de-activates application roles in DB if not present in External Auth + * system + * + * @param app + * @param finalRoleList contains list of current roles present in + * External Auth System + * @param applicationRolesList contains list of current roles present in DB + */ + @SuppressWarnings("unchecked") + private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList, + List<EPRole> applicationRolesList) { + final Map<String, EPRole> checkRolesInactive = new HashMap<>(); + for (EPRole extrole : finalRoleList) { + checkRolesInactive.put(extrole.getName(), extrole); + } + for (EPRole role : applicationRolesList) { + try { + final Map<String, String> extRoleParams = new HashMap<>(); + List<EPRole> roleList = null; + extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName()); + if (!checkRolesInactive.containsKey(role.getName())) { + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null); + } else { + extRoleParams.put(APP_ID, app.getId().toString()); + roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + extRoleParams, null); + } + if (!roleList.isEmpty()) { + EPRole updateRoleInactive = roleList.get(0); + updateRoleInactive.setActive(false); + dataAccessService.saveDomainObject(updateRoleInactive, null); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e); + } + } + } + + @Override + @SuppressWarnings("unchecked") + public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole) + throws IOException { + List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>(); + ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); + List<String> functionCodelist = new ArrayList<>(); + Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app); + Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app); + for (int i = 0; i < extRole.length(); i++) { + ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); + EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); + JSONObject Role = (JSONObject) extRole.get(i); + String name = extRole.getJSONObject(i).getString(ROLE_NAME); + String actualRoleName = name.substring(app.getNameSpace().length() + 1); + if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) { + actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); + } + SortedSet<ExternalAccessPerms> 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()); + if (isNamespaceMatching) { + externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), + perms.getString("instance"), perms.getString("action")); + ePAppRoleFunction.setCode(externalAccessPerms.getInstance()); + functionCodelist.add(ePAppRoleFunction.getCode()); + externalAccessPermsOfRole.add(externalAccessPerms); + } + } + } + externalRoleDetail.setActive(true); + externalRoleDetail.setName(actualRoleName); + if (app.getId() == 1) { + externalRoleDetail.setAppId(null); + } else { + externalRoleDetail.setAppId(app.getId()); + } + EPRole currRole = null; + currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) + ? curRolesUnderscoreMap.get(actualRoleName) + : curRolesMap.get(actualRoleName); + Long roleId = null; + if (currRole != null) + roleId = currRole.getId(); + final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + if (roleId != null) { + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", roleId); + // get role functions from DB + List<EPAppRoleFunction> 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) { + EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance()); + if (checkRoleFunctionExits == null) { + String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1) + + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE + + externalpermission.getAction(); + EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode); + if (checkRoleFunctionPipeExits == null) { + try { + final Map<String, String> 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<CentralV2RoleFunction> roleFunction = null; + roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", + appFuncsParams, null); + if (roleFunction.isEmpty()) { + appFuncsParams.put("functionCd", funcCode); + roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", + appFuncsParams, null); + } + if (!roleFunction.isEmpty()) { + EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); + apRoleFunction.setAppId(app.getId()); + apRoleFunction.setRoleId(roleId); + apRoleFunction.setCode(roleFunction.get(0).getCode()); + dataAccessService.saveDomainObject(apRoleFunction, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "SyncApplicationRolesWithEcompDB: Failed to add role function", e); + } + } + } + } + } + externalRoleDetailsList.add(externalRoleDetail); + } + return externalRoleDetailsList; + } + + @Override + public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception { + ResponseEntity<String> response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :", + res); + JSONObject jsonObj = new JSONObject(res); + JSONArray extRole = jsonObj.getJSONArray("role"); + for (int i = 0; i < extRole.length(); i++) { + if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN) + || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER) + || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR) + && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { + extRole.remove(i); + i--; + } + } + return extRole; + } + + @Override + public JSONArray getAllUsersByRole(String roleName) throws Exception { + ResponseEntity<String> response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class); + String res = response.getBody(); + 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"); + return extRole; + } + + /** + * + * It converts from ExternalRoleDetails.class object to EPRole.class object + * + * @param externalRoleDetails + * @return EPRole object + */ + private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { + EPRole role = new EPRole(); + role.setActive(true); + role.setAppId(externalRoleDetails.getAppId()); + role.setAppRoleId(externalRoleDetails.getAppRoleId()); + role.setName(externalRoleDetails.getName()); + role.setPriority(externalRoleDetails.getPriority()); + return role; + } + + @SuppressWarnings("unchecked") + @Override + public Integer bulkUploadUserRoles(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + List<BulkUploadUserRoles> userRolesList = null; + Integer userRolesAdded = 0; + if (app.getCentralAuth()) { + userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null); + for (BulkUploadUserRoles userRolesUpload : userRolesList) { + if (!userRolesUpload.getOrgUserId().equals("su1234")) { + addUserRoleInExternalSystem(userRolesUpload); + userRolesAdded++; + } + } + } + return userRolesAdded; + } + + /** + * Its adding a user role in external auth system while doing bulk upload + * + * @param userRolesUpload + */ + private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) { + try { + String name = ""; + ObjectMapper mapper = new ObjectMapper(); + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = userRolesUpload.getOrgUserId() + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ExternalAccessUser extUser = new ExternalAccessUser(name, + userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String userRole = mapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, entity, String.class); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "addUserRoleInExternalSystem: UserRole already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e); + } + } + } + + @Override + public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) + throws Exception { + try { + String sql = ""; + Query query = null; + // It should delete only when it portal's roleId + if (appId.equals(PortalConstants.PORTAL_APP_ID)) { + // Delete from fn_role_function + sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + } + // Delete from ep_app_role_function + sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + // Delete from ep_role_notification + sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + // Delete from fn_user_pseudo_role + sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + // Delete form EP_WIDGET_CATALOG_ROLE + sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + // Delete form EP_WIDGET_CATALOG_ROLE + sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + if (!isPortalRequest) { + // Delete form fn_menu_functional_roles + sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + } + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e); + throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getMenuFunctionsList(String uebkey) throws Exception { + List<String> appMenuFunctionsList = null; + List<String> appMenuFunctionsFinalList = new ArrayList<>(); + try { + EPApp app = getApp(uebkey).get(0); + final Map<String, Long> 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 appMenuFunctionsFinalList; + } + return appMenuFunctionsFinalList; + } + + @SuppressWarnings({ "unchecked" }) + @Override + public List<EcompUser> getAllAppUsers(String uebkey) throws Exception { + List<String> usersList = new ArrayList<>(); + List<EcompUser> usersfinalList = new ArrayList<>(); + try { + EPApp app = getApp(uebkey).get(0); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService + .executeNamedQuery("ApplicationUserRoles", appParams, null); + for (EcompUserRoles ecompUserRole : userList) { + boolean found = false; + Set<EcompRole> 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<EcompRoleFunction> roleFunctionSet = new TreeSet<>(); + if (role != null) { + roleFunctionSet = (SortedSet<EcompRoleFunction>) 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<EcompRoleFunction> 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; + } + + @Override + 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) { + @SuppressWarnings("unchecked") + Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions(); + Set<RoleFunction> roleFunctionListNew = new HashSet<>(); + Iterator<RoleFunction> itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFun); + } + newRole.setRoleFunctions(roleFunctionListNew); + } + return newRole; + } + + @Override + @SuppressWarnings("unchecked") + public List<CentralizedApp> getCentralizedAppsOfUser(String userId) { + Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + List<CentralizedApp> centralizedAppsList = new ArrayList<>(); + try { + centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); + } + return centralizedAppsList; + } + + @SuppressWarnings("unchecked") + public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) { + Map<String, Long> params = new HashMap<>(); + params.put("appId", appId); + List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>(); + try { + globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params, + null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e); + } + List<CentralV2Role> rolesfinalList = new ArrayList<>(); + if (globalRoles.size() > 0) + rolesfinalList = finalListOfCentralRoles(globalRoles); + return rolesfinalList; + } + + @SuppressWarnings("unchecked") + private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) { + CentralV2Role finalGlobalrole = null; + List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>(); + Map<String, Long> params = new HashMap<>(); + params.put("roleId", roleId); + params.put("requestedAppId", requestedAppId); + try { + roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", + params, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e); + } + if (roleWithApplicationRoleFucntions.size() > 0) { + List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions); + finalGlobalrole = rolesfinalList.get(0); + } else { + List<EPRole> roleList = getPortalAppRoleInfo(roleId); + finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0)); + } + return finalGlobalrole; + } + + private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) { + List<CentralV2Role> rolesfinalList = new ArrayList<>(); + for (GlobalRoleWithApplicationRoleFunction role : globalRoles) { + boolean found = false; + for (CentralV2Role cenRole : rolesfinalList) { + if (role.getRoleId().equals(cenRole.getId())) { + SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions(); + CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role); + roleFunctions.add(cenRoleFun); + cenRole.setRoleFunctions(roleFunctions); + found = true; + break; + } + } + if (!found) { + CentralV2Role cenrole = new CentralV2Role(); + cenrole.setName(role.getRoleName()); + cenrole.setId(role.getRoleId()); + cenrole.setActive(role.isActive()); + cenrole.setPriority(role.getPriority()); + SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>(); + CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role); + roleFunctions.add(cenRoleFun); + cenrole.setRoleFunctions(roleFunctions); + rolesfinalList.add(cenrole); + } + } + return rolesfinalList; + } + + private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) { + String instance; + String type; + String action; + CentralV2RoleFunction cenRoleFun; + if (role.getFunctionCd().contains(FUNCTION_PIPE)) { + instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd()); + type = EcompPortalUtils.getFunctionType(role.getFunctionCd()); + action = EcompPortalUtils.getFunctionAction(role.getFunctionCd()); + cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null); + } else { + type = getFunctionCodeType(role.getFunctionCd()); + action = getFunctionCodeAction(role.getFunctionCd()); + cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, + action, null); + } + return cenRoleFun; + } + + @SuppressWarnings("unchecked") + @Override + public List<EPRole> getGlobalRolesOfPortal() { + List<EPRole> globalRoles = new ArrayList<>(); + try { + globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e); + } + return globalRoles; + } + + private CentralV2Role convertRoleToCentralV2Role(EPRole role) { + return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), + role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(), + new TreeSet<>(), new TreeSet<>(), new TreeSet<>()); + } + + @Override + public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject( + List<CentralV2RoleFunction> answer) { + List<CentralRoleFunction> addRoleFuncList = new ArrayList<>(); + for (CentralV2RoleFunction cenRoleFunc : answer) { + CentralRoleFunction setRoleFunc = new CentralRoleFunction(); + setRoleFunc.setCode(cenRoleFunc.getCode()); + setRoleFunc.setName(cenRoleFunc.getName()); + addRoleFuncList.add(setRoleFunc); + } + return addRoleFuncList; + } + + @Override + public CentralUser getUserRoles(String loginId, String uebkey) throws Exception { + CentralUser sendUserRoles = null; + try { + CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey); + sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e); + throw e; + } + return sendUserRoles; + } + + /** + * + * It returns V2 CentralUser object if user has any roles and permissions + * + * @param loginId + * @param uebkey + * @return CentralUser object + * @throws Exception + */ + private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception { + EPApp app; + List<EPUser> epUserList; + List<EPApp> appList = getApp(uebkey); + app = appList.get(0); + epUserList = getUser(loginId); + EPUser user = epUserList.get(0); + Set<EPUserApp> userAppSet = user.getEPUserApps(); + return createEPUser(user, userAppSet, app); + } + + private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) { + final Map<String, Long> userParams = new HashMap<>(); + userParams.put("appId", app.getId()); + userParams.put("userId", user.getId()); + @SuppressWarnings("unchecked") + List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", + userParams, null); + List<EcompRole> setUserRoles = new ArrayList<>(); + for (EPUserAppCurrentRoles role : userAppsRolesList) { + logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}", + role.getRoleName()); + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getRoleId()); + ecompRole.setName(role.getRoleName()); + setUserRoles.add(ecompRole); + } + logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}", + setUserRoles.size()); + return setUserRoles; + } + + @Override + public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles) + throws Exception { + List<EPApp> appList = getApp(uebkey); + EPApp app = appList.get(0); + List<EPUser> epUserList; + epUserList = getUser(loginId); + List<EcompRole> missingUserAppRoles = new ArrayList<>(); + List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList()); + logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList); + List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0)); + if (userApplicationsRolesfromDB.size() > 0) { + missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName())) + .collect(Collectors.toList()); + } + List<String> MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName) + .collect(Collectors.toList()); + logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList); + + List<EcompRole> finalMissingRoleList = new ArrayList<>(); + if (missingUserAppRoles.size() > 0) { + final Map<String, Long> params = new HashMap<>(); + for (EcompRole role : missingUserAppRoles) { + params.put("roleId", role.getId()); + params.put(APP_ID, app.getId()); + + EcompRole epRole = new EcompRole(); + epRole.setId(role.getId()); + epRole.setName(role.getName()); + @SuppressWarnings("unchecked") + List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>(); + for (CentralV2RoleFunction roleFunc : appRoleFunctionList) { + String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + String type = getFunctionCodeType(roleFunc.getCode()); + String action = getFunctionCodeAction(roleFunc.getCode()); + EcompRoleFunction fun = new EcompRoleFunction(); + fun.setAction(action); + fun.setCode(functionCode); + fun.setType(type); + fun.setName(roleFunc.getName()); + roleFunctionSet.add(fun); + + } + epRole.setRoleFunctions(roleFunctionSet); + finalMissingRoleList.add(epRole); + } + } + + return finalMissingRoleList; + } + + /** + * It converts V2 CentralUser object to old version CentralUser object + * + * @param cenV2User + * @return EPUser object + */ + private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) { + Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps(); + Set<CentralUserApp> userApps = new TreeSet<>(); + for (CentralV2UserApp userApp : userV2Apps) { + CentralApp app = userApp.getApp(); + CentralUserApp cua = new CentralUserApp(); + cua.setUserId(null); + cua.setApp(app); + SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>(); + for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) { + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), + cenV2RoleFunc.getName()); + cenRoleFunction.add(cenRoleFunc); + } + CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), + userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction); + cua.setRole(role); + userApps.add(cua); + } + return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), + cenV2User.getCreatedId(), cenV2User.getModifiedId(), cenV2User.getRowNum(), cenV2User.getOrgId(), + cenV2User.getManagerId(), cenV2User.getFirstName(), cenV2User.getMiddleInitial(), + cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), cenV2User.getCellular(), + cenV2User.getEmail(), cenV2User.getAddressId(), cenV2User.getAlertMethodCd(), cenV2User.getHrid(), + cenV2User.getOrgUserId(), cenV2User.getOrgCode(), cenV2User.getAddress1(), cenV2User.getAddress2(), + cenV2User.getCity(), cenV2User.getState(), cenV2User.getZipCode(), cenV2User.getCountry(), + cenV2User.getOrgManagerUserId(), cenV2User.getLocationClli(), cenV2User.getBusinessCountryCode(), + cenV2User.getBusinessCountryName(), cenV2User.getBusinessUnit(), cenV2User.getBusinessUnitName(), + cenV2User.getDepartment(), cenV2User.getDepartmentName(), cenV2User.getCompanyCode(), + cenV2User.getCompany(), cenV2User.getZipCodeSuffix(), cenV2User.getJobTitle(), + cenV2User.getCommandChain(), cenV2User.getSiloStatus(), cenV2User.getCostCenter(), + cenV2User.getFinancialLocCode(), cenV2User.getLoginId(), cenV2User.getLoginPwd(), + cenV2User.getLastLoginDate(), cenV2User.isActive(), cenV2User.isInternal(), + cenV2User.getSelectedProfileId(), cenV2User.getTimeZoneId(), cenV2User.isOnline(), + cenV2User.getChatId(), userApps); + } + + @Override + public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) { + List<CentralRole> cenRoleList = new ArrayList<>(); + for (CentralV2Role v2CenRole : v2CenRoleList) { + SortedSet<CentralRoleFunction> 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.getActive(), + v2CenRole.getPriority(), cenRoleFuncList); + cenRoleList.add(role); + } + return cenRoleList; + } + + @Override + public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity<String> entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system"); + ResponseEntity<String> response = null; + try { + response = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ", + response.getStatusCode().value()); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + if (e.getStatusCode() == HttpStatus.NOT_FOUND) + throw new InvalidApplicationException("Invalid NameSpace"); + else + throw e; + } + return response; + } + + @Override + public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) { + SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>(); + for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) { + CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); + cenRoleFuncList.add(roleFunc); + } + return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), + cenRoleFuncList); + } + + @SuppressWarnings("unchecked") + @Override + public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception { + EPApp app = getApp(uebkey).get(0); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(roleId)); + List<BulkUploadUserRoles> userRolesList = null; + Integer userRolesAdded = 0; + if (app.getCentralAuth()) { + userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null); + for (BulkUploadUserRoles userRolesUpload : userRolesList) { + userRolesUpload.setRoleName(modifiedRoleName); + if (!userRolesUpload.getOrgUserId().equals("su1234")) { + addUserRoleInExternalSystem(userRolesUpload); + userRolesAdded++; + } + } + } + return userRolesAdded; + } + + @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(), + EcompPortalUtils.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<String> 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<String> entity) { + logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity<String> 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<String> getUserRolesEntity = new HttpEntity<>(headers); + ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj = null; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + updateUserRolesInLocal(userRoleDetailList, extRoles, loginId); + } + + @SuppressWarnings("unchecked") + private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles, + String loginId) throws InvalidUserException { + HashMap<String, String> userParams = new HashMap<>(); + userParams.put("orgUserId", loginId); + // Get all centralized applications existing user roles from local + List<CentralizedAppRoles> currentUserAppRoles = dataAccessService + .executeNamedQuery("getUserCentralizedAppRoles", userParams, null); + EPUser user = getUser(loginId).get(0); + // Get all centralized applications roles from local + HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList(); + HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles( + currentUserAppRoles); + // Get all centralized applications + admin role from local + HashMap<String, EPApp> 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<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user, + HashMap<String, CentralizedAppRoles> cenAppRolesMap, + HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap, + HashMap<String, EPApp> 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<String, EPApp> getCentralizedAdminAppsInfo() { + List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null); + HashMap<String, EPApp> 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<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles( + List<CentralizedAppRoles> currentUserAppRoles) { + HashMap<String, CentralizedAppRoles> 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<String, CentralizedAppRoles> getCentralizedAppRoleList() { + List<CentralizedAppRoles> centralizedAppRoles = dataAccessService + .executeNamedQuery("getAllCentralizedAppsRoles", null, null); + HashMap<String, CentralizedAppRoles> 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<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity<String> getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if (getResponse.getStatusCode().value() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, + "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; + } + + @Override + public Integer updateAppRoleDescription(String uebkey) { + Integer roleDescUpdated = 0; + EPApp app; + try { + app = getApp(uebkey).get(0); + List<EPRole> roles = getAppRoles(app.getId()); + for (EPRole epRole : roles) { + Role role = new Role(); + role.setName(epRole.getName()); + boolean status = addRoleDescriptionInExtSystem(role, app); + if (status) + roleDescUpdated++; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e); + } + return roleDescUpdated; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/LanguageServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/LanguageServiceImpl.java index b0d8c424..1aa12b21 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/LanguageServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/LanguageServiceImpl.java @@ -16,6 +16,9 @@ package org.onap.portalapp.portal.service; import com.alibaba.fastjson.JSONObject; + +import antlr.StringUtils; + import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.Language; import org.onap.portalsdk.core.service.DataAccessService; @@ -53,23 +56,31 @@ public class LanguageServiceImpl implements LanguageService { public JSONObject getUserLanguage(String loginId) { // get language_id from fn_user by loginId JSONObject result = new com.alibaba.fastjson.JSONObject(); - HashMap params = new HashMap(); - params.put("login_id",loginId); + HashMap getUserParams = new HashMap(); + getUserParams.put("login_id", loginId); + List<EPUser> userList= null; - List<EPUser> list = null; - list = dataAccessService.executeNamedQuery("getEPUserByLoginId",params,new HashMap()); - for (EPUser user : list) { - int languageId = user.getLanguageId(); - HashMap<String,String> params1 = new HashMap(); - params1.put("language_id", String.valueOf(languageId)); - List<Language> languages = dataAccessService.executeNamedQuery("queryLanguageByLanguageId",params1,new HashMap()); - for (Language language : languages) { - result.put("languageId",languageId); - result.put("languageName",language.getLanguageName()); - result.put("languageAlias",language.getLanguageAlias()); + try { + userList = dataAccessService.executeNamedQuery("getEPUserByLoginId", getUserParams, new HashMap()); + if (userList != null && userList.size() > 0) { + EPUser user = userList.get(0); + int languageId = user.getLanguageId(); + result.put("languageId", languageId); + + // get language name and alias from fn_language by languageId + HashMap<String,String> getLangParams = new HashMap(); + getLangParams.put("language_id", String.valueOf(languageId)); + List<Language> languageList = null; + + languageList = dataAccessService.executeNamedQuery("queryLanguageByLanguageId", getLangParams, new HashMap()); + if (languageList != null && languageList.size() > 0) { + result.put("languageName", languageList.get(0).getLanguageName()); + result.put("languageAlias", languageList.get(0).getLanguageAlias()); + } } - return result; + } catch (Exception e) { + e.printStackTrace(); } - return null; + return result; } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java index e90aeb74..b41d898a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -42,8 +44,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.crypto.BadPaddingException; - import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.onap.portalapp.portal.domain.MicroserviceData; @@ -75,9 +75,8 @@ public class MicroserviceServiceImpl implements MicroserviceService { return newService.getId(); } - public void saveServiceParameters(long serviceId, List<MicroserviceParameter> list) throws Exception { - for (int i = 0; i < list.size(); i++) { - MicroserviceParameter para = list.get(i); + public void saveServiceParameters(long serviceId, List<MicroserviceParameter> list) { + for (MicroserviceParameter para : list) { para.setServiceId(serviceId); getDataAccessService().saveDomainObject(para, null); } @@ -85,9 +84,9 @@ public class MicroserviceServiceImpl implements MicroserviceService { @Override public MicroserviceData getMicroserviceDataById(long id) { - MicroserviceData data = null; + MicroserviceData data; try { - List<Criterion> restrictionsList = new ArrayList<Criterion>(); + List<Criterion> restrictionsList = new ArrayList<>(); Criterion idCriterion = Restrictions.eq("id", id); restrictionsList.add(idCriterion); data = (MicroserviceData) dataAccessService.getList(MicroserviceData.class, null, restrictionsList, null).get(0); @@ -102,34 +101,35 @@ public class MicroserviceServiceImpl implements MicroserviceService { @SuppressWarnings("unchecked") @Override - public List<MicroserviceData> getMicroserviceData() throws Exception { + public List<MicroserviceData> getMicroserviceData() { List<MicroserviceData> list = (List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null); - for (int i = 0; i < list.size(); i++) { - if (list.get(i).getPassword() != null) - list.get(i).setPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request - list.get(i).setParameterList(getServiceParameters(list.get(i).getId())); + for (MicroserviceData microserviceData : list) { + if (microserviceData.getPassword() != null) { + microserviceData + .setPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request + } + microserviceData.setParameterList(getServiceParameters(microserviceData.getId())); } return list; } private List<MicroserviceParameter> getServiceParameters(long serviceId) { - List<MicroserviceParameter> list = getMicroServiceParametersList(serviceId); - return list; + return getMicroServiceParametersList(serviceId); } @SuppressWarnings("unchecked") private List<MicroserviceParameter> getMicroServiceParametersList(long serviceId) { - List<Criterion> restrictionsList = new ArrayList<Criterion>(); + List<Criterion> restrictionsList = new ArrayList<>(); Criterion serviceIdCriterion = Restrictions.eq("serviceId", serviceId); restrictionsList.add(serviceIdCriterion); return (List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList, null); } @Override - public void deleteMicroservice(long serviceId) throws Exception { + public void deleteMicroservice(long serviceId) { try { - Map<String, String> params = new HashMap<String, String>(); + Map<String, String> params = new HashMap<>(); params.put("serviceId", Long.toString(serviceId)); dataAccessService.executeNamedQuery("deleteMicroserviceParameter", params, null); @@ -156,17 +156,16 @@ public class MicroserviceServiceImpl implements MicroserviceService { getDataAccessService().saveDomainObject(newService, null); List<MicroserviceParameter> oldService = getServiceParameters(serviceId); boolean foundParam; - for (int i = 0; i < oldService.size(); i++) { + for (MicroserviceParameter microserviceParameter : oldService) { foundParam = false; for (int n = 0; n < newService.getParameterList().size(); n++) { - if (newService.getParameterList().get(n).getId().equals(oldService.get(i).getId())) { + if (newService.getParameterList().get(n).getId().equals(microserviceParameter.getId())) { foundParam = true; break; } } - if (foundParam == false) { - MicroserviceParameter pd = oldService.get(i); - getDataAccessService().deleteDomainObject(pd, null); + if (!foundParam) { + getDataAccessService().deleteDomainObject(microserviceParameter, null); } } for (int i = 0; i < newService.getParameterList().size(); i++) { @@ -184,7 +183,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { @Override @SuppressWarnings("unchecked") public List<MicroserviceParameter> getParametersById(long serviceId) { - List<Criterion> restrictionsList = new ArrayList<Criterion>(); + List<Criterion> restrictionsList = new ArrayList<>(); Criterion contextIdCrit = Restrictions.eq("serviceId", serviceId); restrictionsList.add(contextIdCrit); List<MicroserviceParameter> list = (List<MicroserviceParameter>) dataAccessService @@ -196,7 +195,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { private String decryptedPassword(String encryptedPwd) throws Exception { String result = ""; - if (encryptedPwd != null & encryptedPwd.length() > 0) { + if (encryptedPwd != null && !encryptedPwd.isEmpty()) { try { result = CipherUtil.decryptPKC(encryptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); @@ -210,7 +209,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { private String encryptedPassword(String decryptedPwd) throws Exception { String result = ""; - if (decryptedPwd != null & decryptedPwd.length() > 0) { + if (decryptedPwd != null && !decryptedPwd.isEmpty()) { try { result = CipherUtil.encryptPKC(decryptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java index 5e6f1d9a..a2165647 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -114,6 +114,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; @@ -176,7 +177,7 @@ public class UserRolesCommonServiceImpl { * * @param userId */ - protected void createLocalUserIfNecessary(String userId) { + protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) { if (StringUtils.isEmpty(userId)) { logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); return; @@ -188,9 +189,20 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); @SuppressWarnings("unchecked") List<EPUser> userList = localSession - .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + .createQuery("from :name where orgUserId=:userId") + .setParameter("name",EPUser.class.getName()) + .setParameter("userId",userId) + .list(); if (userList.size() == 0) { - EPUser client = searchService.searchUserByUserId(userId); + EPUser client = null; + if (!isSystemUser) { + client = searchService.searchUserByUserId(userId); + } else { + client = new EPUser(); + client.setOrgUserId(userId); + client.setSystemUser(true); + client.setFirstName(userId.substring(0,userId.indexOf("@"))); + } if (client == null) { String msg = "createLocalUserIfNecessary: cannot create user " + userId + ", because not found in phonebook"; @@ -271,7 +283,10 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); @SuppressWarnings("unchecked") List<EPUser> userList = localSession - .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + .createQuery("from :name where orgUserId=:userId") + .setParameter("name",EPUser.class.getName()) + .setParameter("userId",userId) + .list(); if (userList.size() > 0) { EPUser client = userList.get(0); roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; @@ -486,9 +501,13 @@ public class UserRolesCommonServiceImpl { transaction = localSession.beginTransaction(); // Attention! All roles from remote application supposed to be // active! + @SuppressWarnings("unchecked") - List<EPRole> currentAppRoles = localSession - .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId") + .setParameter("name",EPRole.class.getName()) + .setParameter("appId",appId) + .list(); + List<EPRole> obsoleteRoles = new ArrayList<EPRole>(); for (int i = 0; i < currentAppRoles.size(); i++) { EPRole oldAppRole = currentAppRoles.get(i); @@ -526,7 +545,10 @@ public class UserRolesCommonServiceImpl { // Delete from fn_user_role @SuppressWarnings("unchecked") List<EPUserApp> userRoles = localSession.createQuery( - "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + "from :name where app.id=:appId and role_id=:roleId") + .setParameter("name",EPUserApp.class.getName()) + .setParameter("appId",appId) + .setParameter("roleId",roleId) .list(); logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size()); @@ -541,7 +563,9 @@ public class UserRolesCommonServiceImpl { // Delete from fn_menu_functional_roles @SuppressWarnings("unchecked") List<FunctionalMenuRole> funcMenuRoles = localSession - .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .createQuery("from :name where roleId=:roleId") + .setParameter("name",FunctionalMenuRole.class.getName()) + .setParameter("roleId",roleId) .list(); int numMenuRoles = funcMenuRoles.size(); logger.debug(EELFLoggerDelegate.debugLogger, @@ -553,7 +577,9 @@ public class UserRolesCommonServiceImpl { // so must null out the url too, to be consistent @SuppressWarnings("unchecked") List<FunctionalMenuRole> funcMenuRoles2 = localSession - .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .createQuery("from :name where menuId=:menuId") + .setParameter("name",FunctionalMenuRole.class.getName()) + .setParameter("menuId",menuId) .list(); int numMenuRoles2 = funcMenuRoles2.size(); logger.debug(EELFLoggerDelegate.debugLogger, @@ -567,8 +593,9 @@ public class UserRolesCommonServiceImpl { "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url"); @SuppressWarnings("unchecked") List<FunctionalMenuItem> funcMenuItems = localSession - .createQuery( - "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId) + .createQuery("from :name where menuId=:menuId") + .setParameter("name",FunctionalMenuItem.class.getName()) + .setParameter("menuId",menuId) .list(); if (funcMenuItems.size() > 0) { logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); @@ -628,6 +655,7 @@ public class UserRolesCommonServiceImpl { result = new RolesInAppForUser(); result.appId = appId; result.orgUserId = userId; + for (EcompRole role : userRolesInRemoteApp) { RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); roleInAppForUser.roleId = role.getId(); @@ -665,7 +693,7 @@ public class UserRolesCommonServiceImpl { * @throws HTTPException */ protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, - ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser) throws JsonProcessingException, HTTPException { Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); @@ -742,13 +770,13 @@ public class UserRolesCommonServiceImpl { * set to false if requests from Users page otherwise true * @return true on success, false otherwise */ - protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception { + protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception { boolean result = false; String userId = rolesInAppForUser.orgUserId; Long appId = rolesInAppForUser.appId; synchronized (syncRests) { if (rolesInAppForUser != null) { - createLocalUserIfNecessary(userId); + createLocalUserIfNecessary(userId, isSystemUser); } if (rolesInAppForUser != null) { @@ -855,22 +883,42 @@ public class UserRolesCommonServiceImpl { return addRemoteUser; } + @SuppressWarnings("unchecked") protected void pushUserOnRemoteApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService, SearchService searchService, ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception { - EPUser client = searchService.searchUserByUserId(userId); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + EPUser client = null; + client = searchService.searchUserByUserId(userId); - if (client == null) { - String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook."; - logger.error(EELFLoggerDelegate.errorLogger, msg); - throw new Exception(msg); - } + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + if (client == null) { + String msg = "cannot create user " + userId + ", because he/she cannot be found in directory."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + // throw new Exception(msg); + final Map<String, String> loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", userId); + List<EPUser> userList = new ArrayList<>(); + userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null); + if (userList.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + userList.get(0).getOrgUserId() + " User was found in Portal"); + client = userList.get(0); + SortedSet<EPUserApp> userApps = new TreeSet<>(); + client.setEPUserApps(userApps); + client.setSystemUser(false); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal"); + throw new Exception(msg); + } + } + client.setLoginId(userId); - client.setActive(true); + client.setActive(true); + client.setOrgUserId(userId); + + roleInAppForUserList.removeIf(role -> role.isApplied.equals(false)); SortedSet<Role> roles = new TreeSet<>(); @@ -971,12 +1019,12 @@ public class UserRolesCommonServiceImpl { boolean epRequestValue = false; String userId = ""; String reqMessage = ""; - if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { - userId = newAppRolesForUser.orgUserId.trim(); + if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) { + userId = newAppRolesForUser.getOrgUserId().trim(); } - Long appId = newAppRolesForUser.appId; - List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles; - if (userId.length() > 0) { + Long appId = newAppRolesForUser.getAppId(); + List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles(); + if (userId.length() > 0 ) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -984,7 +1032,27 @@ public class UserRolesCommonServiceImpl { EPApp app = appsService.getApp(appId); applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - // if centralized app + boolean systemUser = newAppRolesForUser.isSystemUser(); + if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) { + + Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles; + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, + epRequestValue, systemUser); + } + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", + systemUser); + + }else if (!app.getCentralAuth() && systemUser) + { + throw new Exception("For non-centralized application we cannot add systemUser"); + } + else{ // if centralized app if (app.getCentralAuth()) { if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, @@ -999,9 +1067,9 @@ public class UserRolesCommonServiceImpl { if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { // Apply changes in external Access system updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, - epRequestValue); + epRequestValue,false); } - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser); } // In case if portal is not centralized then follow existing approach else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ @@ -1009,7 +1077,7 @@ public class UserRolesCommonServiceImpl { applicationsRestClientService, appId, userId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false); } else{// remote app EPUser remoteAppUser = null; if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ @@ -1020,10 +1088,10 @@ public class UserRolesCommonServiceImpl { remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, appId, userId); + applicationsRestClientService, appId, userId,systemUser); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInRemoteApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false); // If no roles remain, request app to set user inactive. if (userRolesInRemoteApp.size() == 0) { @@ -1035,6 +1103,7 @@ public class UserRolesCommonServiceImpl { } } } + } } catch (Exception e) { /*String message = String.format( "Failed to create user or update user roles for User %s, AppId %s", @@ -1065,7 +1134,7 @@ public class UserRolesCommonServiceImpl { * @param roleInAppUser Contains list of active roles */ @SuppressWarnings("unchecked") - private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception { try { // check if user exists @@ -1073,13 +1142,15 @@ public class UserRolesCommonServiceImpl { userParams.put("orgUserIdValue", orgUserId); List<EPUser> userInfo = checkIfUserExists(userParams); if (userInfo.isEmpty()) { - createLocalUserIfNecessary(orgUserId); + createLocalUserIfNecessary(orgUserId, isSystemUser); } String name = ""; if (EPCommonSystemProperties - .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) { name = orgUserId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } else { + name = orgUserId; } ObjectMapper mapper = new ObjectMapper(); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); @@ -1171,7 +1242,7 @@ public class UserRolesCommonServiceImpl { for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { if (!(currentUserRolesInExternalSystem .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) { - ExternalAccessUser extUser = new ExternalAccessUser(name, + ExternalAccessUser extUser = new ExternalAccessUser(name, app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); String formattedUserRole = mapper.writeValueAsString(extUser); HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers); @@ -1191,7 +1262,23 @@ public class UserRolesCommonServiceImpl { } } } - } catch (Exception e) { + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", + app.getId(), e); + if (e.getStatusCode() == HttpStatus.FORBIDDEN) { + logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId); + throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser"); + } + if (e.getStatusCode() == HttpStatus.NOT_FOUND) { + logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role"); + throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role"); + } + EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); + throw e; + } + + catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e); EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST); throw e; @@ -1487,11 +1574,11 @@ public class UserRolesCommonServiceImpl { List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles; if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { // Apply changes in external Access system - updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest); + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false); } logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false); } // If local application is not centralized else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ @@ -1499,7 +1586,7 @@ public class UserRolesCommonServiceImpl { applicationsRestClientService, app.getId(), orgUserId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false); } else {// remote app // If adding just account admin role don't do remote application user call if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) { @@ -1512,7 +1599,7 @@ public class UserRolesCommonServiceImpl { } Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, app.getId(), orgUserId); + applicationsRestClientService, app.getId(), orgUserId,false); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); @@ -1520,7 +1607,7 @@ public class UserRolesCommonServiceImpl { "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, - reqType); + reqType,false); // If no roles remain, request app to set user inactive. /* * if (userRolesInRemoteApp.size() == 0) { @@ -1543,7 +1630,7 @@ public class UserRolesCommonServiceImpl { logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, - reqType); + reqType,false); } if(!result){ reqMessage = "Failed to save the user app role(s)"; @@ -1987,17 +2074,18 @@ public class UserRolesCommonServiceImpl { List<EPUserAppRoles> appRole= null; try { logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined"); - boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId()); + boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, + userAppRolesData.getAppId(), user.getId()); logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result); - params.put("appId", userAppRolesData.appId); + params.put("appId", userAppRolesData.getAppId()); EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest(); epAppRolesRequestData.setCreatedDate(new Date()); epAppRolesRequestData.setUpdatedDate(new Date()); epAppRolesRequestData.setUserId(user.getId()); - epAppRolesRequestData.setAppId(userAppRolesData.appId); + epAppRolesRequestData.setAppId(userAppRolesData.getAppId()); epAppRolesRequestData.setRequestStatus("P"); - List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles; + List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles(); Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>(); dataAccessService.saveDomainObject(epAppRolesRequestData, null); for (RoleInAppForUser userAppRoles : appRoleIdList) { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java index 60bc7fce..cbfe1787 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -38,53 +38,24 @@ package org.onap.portalapp.portal.transport; import java.util.List; - +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode +@ToString public class AppWithRolesForUser { - - public String orgUserId; - - public Long appId; - - public String appName; - - public List<RoleInAppForUser> appRoles; - - public String getOrgUserId() { - return orgUserId; - } - - public void setOrgUserId(String orgUserId) { - this.orgUserId = orgUserId; - } - - public Long getAppId() { - return appId; - } - - public void setAppId(Long appId) { - this.appId = appId; - } - - public String getAppName() { - return appName; - } - - public void setAppName(String appName) { - this.appName = appName; - } - - public List<RoleInAppForUser> getAppRoles() { - return appRoles; - } - - public void setAppRoles(List<RoleInAppForUser> appRoles) { - this.appRoles = appRoles; - } - - @Override - public String toString() { - return "AppWithRolesForUser [orgUserId=" + orgUserId + ", appId=" + appId + ", appName=" + appName - + ", appRoles=" + appRoles + "]"; - } + private String orgUserId; + private boolean isSystemUser; + private Long appId; + private String appName; + private List<RoleInAppForUser> appRoles; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java index 2ada8ed1..17007a5f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2UserApp.java @@ -38,6 +38,7 @@ package org.onap.portalapp.portal.transport; import java.io.Serializable; +import java.util.Objects; @SuppressWarnings("rawtypes") public class CentralV2UserApp implements Serializable, Comparable{ @@ -99,7 +100,20 @@ public class CentralV2UserApp implements Serializable, Comparable{ this.priority = priority; } - + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof CentralV2UserApp)) { + return false; + } + CentralV2UserApp castOther = (CentralV2UserApp) other; + return Objects.equals(this.userId, castOther.userId) && + Objects.equals(this.app, castOther.app) && + Objects.equals(this.role, castOther.role) && + Objects.equals(this.priority, castOther.priority); + } public int compareTo(Object other){ CentralV2UserApp castOther = (CentralV2UserApp) other; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java index ec27d987..3fbdc3e8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidget.java @@ -44,6 +44,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.hibernate.validator.constraints.SafeHtml; import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonInclude; @@ -63,28 +64,33 @@ public class CommonWidget extends DomainVo{ private Long id; @Column(name = "category") + @SafeHtml public String category; @Column(name = "href") + @SafeHtml public String href; @Column(name = "title") + @SafeHtml public String title; @Column(name = "content") + @SafeHtml public String content; @Column(name = "event_date") + @SafeHtml public String eventDate; @Column(name = "sort_order") public Integer sortOrder; - + public CommonWidget(){ - + } - + public CommonWidget(String category, String href, String title, String content, String eventDate, Integer sortOrder){ this.category = category; this.href = href; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java index 55dfc91a..51a02652 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CommonWidgetMeta.java @@ -38,14 +38,17 @@ package org.onap.portalapp.portal.transport; import java.util.List; +import javax.validation.Valid; +import org.hibernate.validator.constraints.SafeHtml; public class CommonWidgetMeta { - + @SafeHtml private String category; + @Valid private List<CommonWidget> items; - - public CommonWidgetMeta(){ - + + public CommonWidgetMeta(){ + } public CommonWidgetMeta(String category, List<CommonWidget> items){ diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FavoritesFunctionalMenuItem.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FavoritesFunctionalMenuItem.java index 57f65379..493e57fa 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FavoritesFunctionalMenuItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FavoritesFunctionalMenuItem.java @@ -43,6 +43,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; +import javax.validation.constraints.Digits; /** @@ -55,9 +56,11 @@ public class FavoritesFunctionalMenuItem implements Serializable { @Id @Column(name = "user_id") + @Digits(integer = 11, fraction = 0) public Long userId; @Id @Column(name = "menu_id") + @Digits(integer = 11, fraction = 0) public Long menuId; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java index 06acdb7b..14ad2f4c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java @@ -47,37 +47,62 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; +import javax.validation.constraints.Digits; +import javax.validation.constraints.Max; +import javax.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.SafeHtml; @Entity @Table(name="fn_menu_functional") +@NoArgsConstructor +@AllArgsConstructor public class FunctionalMenuItem implements Serializable { - public FunctionalMenuItem(){}; - private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "MENU_ID") + @Digits(integer = 11, fraction = 0) public Long menuId; - + @Column(name = "COLUMN_NUM") + @Digits(integer = 2, fraction = 0) + @NotNull public Integer column; - + @Column(name = "TEXT") + @Max(value = 100) + @SafeHtml + @NotNull public String text; - + @Column(name = "PARENT_MENU_ID") + @Digits(integer = 11, fraction = 0) public Integer parentMenuId; - + @Column(name = "URL") + @Max(value = 128) + @SafeHtml + @NotNull public String url; - + @Column(name="ACTIVE_YN") + @Max(value = 1) + @SafeHtml + @NotNull public String active_yn; @Transient public Integer appid; + @Transient + private List<Integer> roles; + + @Transient + public Boolean restrictedApp; + public List<Integer> getRoles() { return roles; } @@ -86,18 +111,12 @@ public class FunctionalMenuItem implements Serializable { this.roles = roles; } - @Transient - private List<Integer> roles; - - @Transient - public Boolean restrictedApp; - public void normalize() { if (this.column == null) - this.column = new Integer(1); + this.column = 1; this.text = (this.text == null) ? "" : this.text.trim(); if (this.parentMenuId == null) - this.parentMenuId = new Integer(-1); + this.parentMenuId = -1; this.url = (this.url == null) ? "" : this.url.trim(); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java index f2503b42..37ad5add 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/OnboardingApp.java @@ -37,6 +37,8 @@ */ package org.onap.portalapp.portal.transport; +import org.hibernate.validator.constraints.SafeHtml; + /** * Model of rows in the fn_app table; serialized as a message add or update an * on-boarded application. @@ -44,21 +46,21 @@ package org.onap.portalapp.portal.transport; public class OnboardingApp { public Long id; - + @SafeHtml public String name; - + @SafeHtml public String imageUrl; - + @SafeHtml public String imageLink; - + @SafeHtml public String description; - + @SafeHtml public String notes; - + @SafeHtml public String url; - + @SafeHtml public String alternateUrl; - + @SafeHtml public String restUrl; public Boolean isOpen; @@ -66,27 +68,27 @@ public class OnboardingApp { public Boolean isEnabled; public Long motsId; - + @SafeHtml public String myLoginsAppName; - + @SafeHtml public String myLoginsAppOwner; - + @SafeHtml public String username; - + @SafeHtml public String appPassword; - + @SafeHtml public String thumbnail; - + @SafeHtml public String uebTopicName; - + @SafeHtml public String uebKey; - + @SafeHtml public String uebSecret; public Boolean restrictedApp; public Boolean isCentralAuth; - + @SafeHtml public String nameSpace; /** diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/PortalAdminUserRole.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/PortalAdminUserRole.java index 01cc6941..dd0142c9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/PortalAdminUserRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/PortalAdminUserRole.java @@ -43,6 +43,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; +import javax.validation.constraints.Digits; /** * This is to handle portal admins @@ -54,13 +55,16 @@ public class PortalAdminUserRole implements Serializable{ @Id @Column(name = "user_id") + @Digits(integer = 10, fraction = 0) public Long userId; @Id @Column(name = "role_id") + @Digits(integer = 10, fraction = 0) public Long roleId; @Column(name = "app_id") + @Digits(integer = 11, fraction = 0) public Long appId; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java index 1b5613ca..30eeac04 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java @@ -47,10 +47,12 @@ import java.util.Arrays; import java.util.Base64; import java.util.Date; import java.util.List; +import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.DatatypeConverter; +import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.Transaction; @@ -70,19 +72,21 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class EcompPortalUtils { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class); - + private static final String FUNCTION_PIPE = "|"; - + // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor. // It should be defined in SystemProperties. private static final String GLOBAL_LOGIN_URL = "global-login-url"; - - // It is a regular expression used for while creating a External Central Auth Role + + // It is a regular expression used for while creating a External Central Auth + // Role public static final String EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS = "([^A-Z^a-z^0-9^\\.^%^(^)^=^:])"; - + + public static final String slash = "/"; + /** - * @param orgUserId - * User ID to validate + * @param orgUserId User ID to validate * @return true if orgUserId is not empty and contains only alphanumeric, false * otherwise */ @@ -94,10 +98,8 @@ public class EcompPortalUtils { * Splits the string into a list of tokens using the specified regular * expression * - * @param source - * String to split - * @param regex - * tokens + * @param source String to split + * @param regex tokens * @return List of tokens split from the source */ public static List<String> parsingByRegularExpression(String source, String regex) { @@ -116,10 +118,8 @@ public class EcompPortalUtils { /** * Builds a JSON object with error code and message information. * - * @param errorCode - * error code - * @param errorMessage - * message + * @param errorCode error code + * @param errorMessage message * @return JSON object as a String */ public static String jsonErrorMessageResponse(int errorCode, String errorMessage) { @@ -129,8 +129,7 @@ public class EcompPortalUtils { /** * Builds a JSON object with the specified message * - * @param message - * Message to embed + * @param message Message to embed * @return JSON object as a String */ public static String jsonMessageResponse(String message) { @@ -141,15 +140,11 @@ public class EcompPortalUtils { * Serializes the specified object as JSON and writes the result to the debug * log. If serialization fails, logs a message to the error logger. * - * @param logger - * Logger for the class where the object was built; the logger - * carries the class name. - * @param source - * First portion of the log message - * @param msg - * Second portion of the log message - * @param obj - * Object to serialize as JSON + * @param logger Logger for the class where the object was built; the logger + * carries the class name. + * @param source First portion of the log message + * @param msg Second portion of the log message + * @param obj Object to serialize as JSON */ public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) { try { @@ -169,12 +164,9 @@ public class EcompPortalUtils { * Serializes the specified object as JSON and writes the result to the debug * log. If serialization fails, logs a message to the error logger. * - * @param source - * First portion of the log message - * @param msg - * Second portion of the log message - * @param obj - * Object to serialize as JSON + * @param source First portion of the log message + * @param msg Second portion of the log message + * @param obj Object to serialize as JSON */ public static void logAndSerializeObject(String source, String msg, Object obj) { logAndSerializeObject(logger, source, msg, obj); @@ -209,12 +201,9 @@ public class EcompPortalUtils { * Set response status to Unauthorized if user == null and to Forbidden in all * (!) other cases. Logging is not performed if invocator == null * - * @param user - * User object - * @param response - * HttpServletResponse - * @param invocator - * may be null + * @param user User object + * @param response HttpServletResponse + * @param invocator may be null */ public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) { if (user == null) { @@ -248,13 +237,15 @@ public class EcompPortalUtils { // This method might be just for testing purposes. public static void setExternalAppResponseCode(int responseCode) { try { - /*String code = String.valueOf(responseCode); - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code ); - code=StringUtils.EMPTY;*/ + /* + * String code = String.valueOf(responseCode); + * MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code ); + * code=StringUtils.EMPTY; + */ String code = Integer.toString(responseCode); - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,code ); - char[] chars=code.toCharArray(); - Arrays.fill(chars, ' '); + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, code); + char[] chars = code.toCharArray(); + Arrays.fill(chars, ' '); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "setExternalAppResponseCode failed", e); } @@ -337,10 +328,8 @@ public class EcompPortalUtils { /** * Returns a default property if the expected one is not available * - * @param property - * Key - * @param defaultValue - * default Value + * @param property Key + * @param defaultValue default Value * @return Default value if property is not defined or yields the empty string; * else the property value. */ @@ -360,10 +349,8 @@ public class EcompPortalUtils { * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean up * the record in MDC * - * @param beginDateTime - * the given begin time for the call - * @param endDateTime - * the given end time for the call + * @param beginDateTime the given begin time for the call + * @param endDateTime the given end time for the call * */ public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) { @@ -405,8 +392,7 @@ public class EcompPortalUtils { * * @return header which contains external central auth username and password * base64 encoded - * @throws Exception - * if unable to decrypt the password + * @throws Exception if unable to decrypt the password */ public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception { String userName = ""; @@ -429,7 +415,8 @@ public class EcompPortalUtils { String result = ""; if (encrypted != null && encrypted.length() > 0) { try { - result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key)); + result = CipherUtil.decryptPKC(encrypted, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e); throw e; @@ -438,8 +425,8 @@ public class EcompPortalUtils { return result; } - public static String truncateString(String originString, int size){ - if(originString.length()>=size){ + public static String truncateString(String originString, int size) { + if (originString.length() >= size) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(originString); stringBuilder.setLength(size); @@ -448,11 +435,10 @@ public class EcompPortalUtils { } return originString; } - + /** * - * If function code value has any pipes it does pipe filter and - * returns value. + * If function code value has any pipes it does pipe filter and returns value. * * @param functionCode * @return function instance without pipe @@ -462,22 +448,19 @@ public class EcompPortalUtils { if (functionCode.contains(FUNCTION_PIPE)) { int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE); if (count == 2) - finalFunctionCodeVal = functionCode.substring( - functionCode.indexOf(FUNCTION_PIPE) + 1, + finalFunctionCodeVal = functionCode.substring(functionCode.indexOf(FUNCTION_PIPE) + 1, functionCode.lastIndexOf(FUNCTION_PIPE)); else - finalFunctionCodeVal = functionCode - .substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1); - } else{ + finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1); + } else { finalFunctionCodeVal = functionCode; } return finalFunctionCodeVal; } - + /** * - * If function code value has any pipes it does pipe filter and - * returns value. + * If function code value has any pipes it does pipe filter and returns value. * * @param functionCode * @return function Type without pipe @@ -486,20 +469,19 @@ public class EcompPortalUtils { String finalFunctionCodeVal = ""; if (functionCode.contains(FUNCTION_PIPE)) { int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE); - if (count == 2){ - String[] getTypeValue = functionCode.split("\\"+FUNCTION_PIPE); + if (count == 2) { + String[] getTypeValue = functionCode.split("\\" + FUNCTION_PIPE); finalFunctionCodeVal = getTypeValue[0]; } - } else{ + } else { finalFunctionCodeVal = functionCode; } return finalFunctionCodeVal; } - + /** * - * If function code value has any pipes it does pipe filter and - * returns value. + * If function code value has any pipes it does pipe filter and returns value. * * @param functionCode * @return function Action without pipe @@ -509,17 +491,17 @@ public class EcompPortalUtils { if (functionCode.contains(FUNCTION_PIPE)) { int count = StringUtils.countMatches(functionCode, FUNCTION_PIPE); if (count == 2) - finalFunctionCodeVal = functionCode.substring( - functionCode.lastIndexOf(FUNCTION_PIPE)+1); - } else{ + finalFunctionCodeVal = functionCode.substring(functionCode.lastIndexOf(FUNCTION_PIPE) + 1); + } else { finalFunctionCodeVal = functionCode; } return finalFunctionCodeVal; } - + /** * - * It check whether the external auth namespace is matching with current namespace exists in local DB + * It check whether the external auth namespace is matching with current + * namespace exists in local DB * * @param permTypeVal * @param appNamespaceVal @@ -539,20 +521,22 @@ public class EcompPortalUtils { } return isNamespaceMatching; } - + public static boolean checkIfRemoteCentralAccessAllowed() { boolean result = false; - String rmtCentralAccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS); - if(rmtCentralAccess == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Please check in system.properties whether the property exists or not!"); + String rmtCentralAccess = SystemProperties + .getProperty(EPCommonSystemProperties.REMOTE_CENTRALISED_SYSTEM_ACCESS); + if (rmtCentralAccess == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Please check in system.properties whether the property exists or not!"); return false; - }else if(new Boolean(rmtCentralAccess)){ - logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}",rmtCentralAccess); + } else if (new Boolean(rmtCentralAccess)) { + logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRemoteCentralAccessAllowed: {}", rmtCentralAccess); result = true; } return result; } - + /** * * It validates whether given string is JSON or not @@ -560,28 +544,48 @@ public class EcompPortalUtils { * @param jsonInString * @return true or false */ - public static boolean isJSONValid(String jsonInString ) { - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e); - return false; - } - } - /** - * - * It retrieves account information from input String - * - * @param authValue - * @return Array of Account information - * - */ - public static String[] getUserNamePassword(String authValue) { - String base64Credentials = authValue.substring("Basic".length()).trim(); - String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); - final String[] values = credentials.split(":", 2); - return values; + public static boolean isJSONValid(String jsonInString) { + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(jsonInString); + return true; + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to parse Json!", e); + return false; } + } + + /** + * + * It retrieves account information from input String + * + * @param authValue + * @return Array of Account information + * + */ + public static String[] getUserNamePassword(String authValue) { + String base64Credentials = authValue.substring("Basic".length()).trim(); + String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); + final String[] values = credentials.split(":", 2); + return values; + } + + /** + * It encodes the function code based on Hex encoding + * + * @param funCode + * + */ + public static String encodeFunctionCode(String funCode) { + String encodedString = funCode; + Pattern encodePattern = Pattern.compile(EcompPortalUtils.slash); + return encodedString = encodePattern.matcher(encodedString) + .replaceAll("%" + Hex.encodeHexString(encodePattern.toString().getBytes())) + .replaceAll("\\*", "%" + Hex.encodeHexString("*".getBytes())); + } + + public static boolean checkFunctionCodeHasEncodePattern(String code) { + return code.contains(EcompPortalUtils.slash); + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/DateUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/DateUtil.java new file mode 100644 index 00000000..211f8ab9 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/DateUtil.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (c) 2019 Samsung. 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.portalapp.util; + +import java.text.SimpleDateFormat; + +public class DateUtil { + + private DateUtil() { + throw new IllegalStateException("Utility class"); + } + + public static SimpleDateFormat getDateFormat() { + return new SimpleDateFormat("HH:mm:ss:SSSS"); + } + + public static SimpleDateFormat getRequestDateFormat(){ + return new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java index 51f48b16..99a29116 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java @@ -45,7 +45,9 @@ import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; +import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -398,4 +400,40 @@ public class EPUserUtils { return ""; } + public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) { + String[] path = portalApiPath.split("/"); + List<String> roleFunList = new ArrayList<>(); + if (path.length > 1) { + roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList()); + if (roleFunList.size() >= 1) { + for (String roleFunction : roleFunList) { + String[] roleFunctionArray = roleFunction.split("/"); + boolean b = true; + if (roleFunctionArray.length == path.length) { + for (int i = 0; i < roleFunctionArray.length; i++) { + if (b) { + if (!roleFunctionArray[i].equals("*")) { + Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(roleFunctionArray[i]); + b = m.matches(); + + } + } + } + if (b) + return b; + } + } + } + } else { + for (String roleFunction : roleFunctions) { + if (roleFunction.equals(("*"))) { + return true; + } else if (portalApiPath.matches(roleFunction)) { + return true; + } + } + } + return false; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java new file mode 100644 index 00000000..46a60c81 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/DataValidator.java @@ -0,0 +1,63 @@ +/*- + * ============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.portalapp.validation; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import org.springframework.stereotype.Component; + +@Component +public class DataValidator { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + + public <E> Set<ConstraintViolation<E>> getConstraintViolations(E classToValid){ + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<E>> constraintViolations = validator.validate(classToValid); + return constraintViolations; + } + + public <E> boolean isValid(E classToValid){ + Set<ConstraintViolation<E>> constraintViolations = getConstraintViolations(classToValid); + return constraintViolations.isEmpty(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/SecureString.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/SecureString.java new file mode 100644 index 00000000..2afbddac --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/validation/SecureString.java @@ -0,0 +1,55 @@ +/*- + * ============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.portalapp.validation; + +import org.hibernate.validator.constraints.SafeHtml; + +public class SecureString { + + @SafeHtml + private String data; + + public SecureString(String string) { + this.data = string; + } + + public String getString() { + return data; + } +} diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index 4e8943ce..e03c9762 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -229,6 +229,7 @@ <property name="createdId" column="created_id" /> <property name="modifiedId" column="modified_id" /> <property name="timeZoneId" column="timezone" /> + <property name="systemUser" column="is_system_user" type="yes_no"/> <property name="languageId" column="language_id" /> <set name="EPUserApps" table="FN_USER_ROLE" lazy="false" sort="natural" @@ -1160,7 +1161,7 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y <sql-query name="getAppsAdmins"> <return alias="adminUserApp" class="org.onap.portalapp.portal.domain.AdminUserApp" /> <![CDATA[ - SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.org_user_id FROM fn_user_role userrole INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID WHERE user.active_yn='Y' AND userrole.ROLE_ID = :accountAdminRoleId AND (apps.ENABLED = 'Y' OR apps.APP_ID=1) + SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.org_user_id FROM fn_user_role userrole INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID WHERE user.active_yn='Y' AND userrole.ROLE_ID = :accountAdminRoleId ]]> </sql-query> @@ -2548,4 +2549,36 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y ]]> </sql-query> + + <sql-query name="getAllAdminAppsofTheUser"> + <![CDATA[ + select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 + + ]]> + </sql-query> + <sql-query name="getAllAppsFunctionsOfUser"> + <![CDATA[ + select distinct ep.function_cd from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_app fa , fn_role fr + where fu.role_id = ep.role_id + and fu.app_id = ep.app_id + and fu.user_id =:userId + and ea.function_cd = ep.function_cd + and ((fu.app_id = fa.app_id and fa.enabled = 'Y' ) or (fa.app_id = 1)) + and fr.role_id = fu.role_id and fr.active_yn='Y' + union + select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f + where role_id = 999 + and app_r_f.function_cd = a_f.function_cd + and exists + ( + select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id + and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y' + ); + ]]> + </sql-query> + <sql-query name="updateFnUser"> + <![CDATA[ + UPDATE fn_user fu SET fu.language_id=:language_id WHERE fu.login_id=:login_id + ]]> + </sql-query> </hibernate-mapping> diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java index 847d4744..9d3c7785 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java @@ -133,6 +133,24 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } @Test + public void postPortalAdminXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("“><script>alert(“XSS”)</script>"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenThrow(nullPointerException); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + } + + @Test public void postPortalAdminCreateUserIfNotFoundTest() throws Exception { PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); expectedportalRestResponse.setMessage(null); @@ -277,6 +295,36 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } @Test + public void postOnboardAppExternalXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage( + "Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp();; + expectedOnboardingApp.name = "test"; + expectedOnboardingApp.url="test.com"; + expectedOnboardingApp.restUrl="<script>alert(/XSS”)</script>"; + expectedOnboardingApp.myLoginsAppOwner="testUser"; + expectedOnboardingApp.restrictedApp=false; + expectedOnboardingApp.isOpen=true; + expectedOnboardingApp.isEnabled=true; + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postOnboardAppExternal(mockedRequest, mockedResponse, expectedOnboardingApp); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + + } + + @Test public void putOnboardAppExternalifAppNullTest() { PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); expectedportalRestResponse.setMessage("Unexpected value for field: id"); @@ -293,6 +341,38 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } @Test + public void putOnboardAppExternalXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage( + "Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp();; + expectedOnboardingApp.name = "test"; + expectedOnboardingApp.url="test.com"; + expectedOnboardingApp.restUrl="<script>alert(/XSS”)</script>"; + expectedOnboardingApp.myLoginsAppOwner="testUser"; + expectedOnboardingApp.restrictedApp=false; + expectedOnboardingApp.isOpen=true; + expectedOnboardingApp.isEnabled=true; + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + + Long appId = (long) 1; + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .putOnboardAppExternal(mockedRequest, mockedResponse, appId, expectedOnboardingApp); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + + } + + @Test public void putOnboardAppExternalIfOnboardingAppDetailsNullTest() { PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); expectedportalRestResponse.setMessage( diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java index ff37fd50..4df1c2ac 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java @@ -1,9 +1,11 @@ /*- - * ============LICENSE_START========================================== + * ============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"); @@ -88,7 +90,10 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; @RunWith(PowerMockRunner.class) @PrepareForTest({SystemProperties.class,AppUtils.class, EPUserUtils.class, MediaType.class}) @@ -546,7 +551,7 @@ public class AppsControllerTest extends MockitoTestSuite{ List<AppsResponse> atualApps = new ArrayList<AppsResponse>(); Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); - Mockito.when(appService.getAllApps(false)).thenReturn(expectedApps); + Mockito.when(appService.getAllApplications(false)).thenReturn(expectedApps); atualApps = appsController.getApps(mockedRequest, mockedResponse); assertEquals(expectedApps, atualApps); } @@ -564,7 +569,7 @@ public class AppsControllerTest extends MockitoTestSuite{ EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); - Mockito.when(appService.getAllApps(false)).thenThrow(nullPointerException); + Mockito.when(appService.getAllApplications(false)).thenThrow(nullPointerException); assertNull(appsController.getApps(mockedRequest, mockedResponse)); } @@ -723,23 +728,110 @@ public class AppsControllerTest extends MockitoTestSuite{ } @Test - public void putOnboardingAppTest() { + public void putOnboardingAppTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); OnboardingApp OnboardingApp = new OnboardingApp(); + OnboardingApp.isCentralAuth = true; + OnboardingApp.nameSpace = "test1"; FieldsValidator expectedFieldValidator = new FieldsValidator(); expectedFieldValidator.setHttpStatusCode((long) 200); expectedFieldValidator.setFields(null); expectedFieldValidator.setErrorCode(null); + EPApp OnboardingApp1 = new EPApp(); + OnboardingApp1.setCentralAuth(false); + OnboardingApp1.setNameSpace("test"); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(OnboardingApp1); Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(appService.checkIfNameSpaceIsValid(Matchers.anyString())).thenReturn(response); Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, OnboardingApp, mockedResponse); assertEquals(expectedFieldValidator, actualFieldValidator); } + + @Test + public void putOnboardingApp2Test() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.isCentralAuth = true; + onboardingApp.nameSpace = "com.test1"; + EPApp app = new EPApp(); + app.setNameSpace("com.test "); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdminOfApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenReturn(response); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); + Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp, + mockedResponse); + } + + + @Test - public void putOnboardingAppIfSuperAdminTest() { + public void putOnboardingApp4Test() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.isCentralAuth = false; + onboardingApp.nameSpace = "com.test1"; + EPApp app = new EPApp(); + app.setCentralAuth(false); + app.setNameSpace("com.test "); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 404); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdminOfAnyActiveorInactiveApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + + HttpClientErrorException exception = new HttpClientErrorException(HttpStatus.FORBIDDEN); + Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenThrow(exception); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); + Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp, + mockedResponse); + assertEquals(expectedFieldValidator.getHttpStatusCode(), actualFieldValidator.getHttpStatusCode()); + } + + @Test + public void putOnboardingApp5Test() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.isCentralAuth = true; + onboardingApp.nameSpace = "com.test1"; + EPApp app = new EPApp(); + app.setNameSpace("com.test "); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 400); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdminOfApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + + HttpClientErrorException exception = new HttpClientErrorException(HttpStatus.BAD_REQUEST); + Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenThrow(exception); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app); + Mockito.when(mockedResponse.getStatus()).thenReturn(400); + Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp, + mockedResponse); + } + + + @Test + public void putOnboardingAppIfSuperAdminTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); FieldsValidator expectedFieldValidator = null; @@ -750,7 +842,7 @@ public class AppsControllerTest extends MockitoTestSuite{ } @Test - public void putOnboardingAppExceptionTest() { + public void putOnboardingAppExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); OnboardingApp OnboardingApp = new OnboardingApp(); @@ -758,6 +850,13 @@ public class AppsControllerTest extends MockitoTestSuite{ Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenThrow(nullPointerException); assertNull(appsController.putOnboardingApp(mockedRequest, OnboardingApp, mockedResponse)); } + + @Test + public void putOnboardingAppNullUserTest() throws Exception { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenThrow(nullPointerException); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); + assertNull(appsController.putOnboardingApp(mockedRequest, new OnboardingApp(), mockedResponse)); + } @Test public void postOnboardingAppTest() { diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java index 9d3ac1e2..e7303313 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java @@ -639,7 +639,7 @@ public class AuxApiRequestMapperControllerTest { Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false); Mockito.when(mockedRequest.getMethod()).thenReturn("POST"); EpNotificationItem notificationItem = new EpNotificationItem(); - assertNull(auxApiRequestMapperController.publishNotification(mockedRequest, notificationItem, mockedResponse)); + assertNotNull(auxApiRequestMapperController.publishNotification(mockedRequest, notificationItem, mockedResponse)); } @Test diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java index 839b9fd5..34667853 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java @@ -93,7 +93,7 @@ public class DashboardSearchResultControllerTest { @Test public void getWidgetDataTest() { String resourceType = "test"; - PortalRestResponse<CommonWidgetMeta> ecpectedPortalRestResponse = new PortalRestResponse<CommonWidgetMeta>(); + PortalRestResponse<CommonWidgetMeta> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -105,8 +105,21 @@ public class DashboardSearchResultControllerTest { } @Test + public void getWidgetDataXSSTest() { + String resourceType = "\"<IMG SRC=\\\"jav\\tascript:alert('XSS');\\\">\""; + PortalRestResponse expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("resourceType: String string is not valid"); + expectedPortalRestResponse.setResponse(""); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + Mockito.when(searchService.getWidgetData(resourceType)).thenReturn(null); + PortalRestResponse acutualPoratlRestResponse = dashboardSearchResultController + .getWidgetData(mockedRequest, resourceType); + assertEquals(expectedPortalRestResponse,acutualPoratlRestResponse); + } + + @Test public void saveWidgetDataBulkTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -114,7 +127,7 @@ public class DashboardSearchResultControllerTest { CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); commonWidgetMeta.setCategory("test"); - List<CommonWidget> commonWidgetList = new ArrayList<CommonWidget>(); + List<CommonWidget> commonWidgetList = new ArrayList<>(); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId((long) 1); commonWidget.setCategory("test"); @@ -136,8 +149,39 @@ public class DashboardSearchResultControllerTest { } @Test + public void saveWidgetDataBulkXSSTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); + ecpectedPortalRestResponse.setMessage("ERROR"); + ecpectedPortalRestResponse.setResponse("Category is not valid"); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + + CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); + commonWidgetMeta.setCategory("test"); + + List<CommonWidget> commonWidgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("\"<IMG SRC=\\\"jav\\tascript:alert('XSS');\\\">\""); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + commonWidgetList.add(commonWidget); + + commonWidgetMeta.setItems(commonWidgetList); + + Mockito.when(searchService.saveWidgetDataBulk(commonWidgetMeta)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetDataBulk(commonWidgetMeta); + assertEquals(ecpectedPortalRestResponse, actualPortalRestResponse); + } + + @Test public void saveWidgetDataBulkIfCategoryNullTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -145,7 +189,7 @@ public class DashboardSearchResultControllerTest { CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); commonWidgetMeta.setCategory("test"); - List<CommonWidget> commonWidgetList = new ArrayList<CommonWidget>(); + List<CommonWidget> commonWidgetList = new ArrayList<>(); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId(null); commonWidget.setCategory(null); @@ -166,7 +210,7 @@ public class DashboardSearchResultControllerTest { @Test public void saveWidgetDataTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -188,10 +232,33 @@ public class DashboardSearchResultControllerTest { } @Test + public void saveWidgetDataXSSTest() { + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("Category is not valid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("\"<IMG SRC=\"jav\\tascript:alert('XSS');\">\""); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetData(commonWidget); + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + + } + + @Test public void saveWidgetDataExceptionTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("ERROR"); - ecpectedPortalRestResponse.setResponse("Cateogry cannot be null or empty"); + ecpectedPortalRestResponse.setResponse("Category cannot be null or empty"); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId((long) 1); @@ -212,7 +279,7 @@ public class DashboardSearchResultControllerTest { @Test public void saveWidgetDataDateErrorTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -233,8 +300,9 @@ public class DashboardSearchResultControllerTest { } + @Test public void deleteWidgetDataTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -255,14 +323,36 @@ public class DashboardSearchResultControllerTest { } @Test + public void deleteWidgetDataXSSTest() { + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("CommonWidget is not valid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("\"<IMG SRC=\"jav\\tascript:alert('XSS');\">\""); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + Mockito.when(searchService.deleteWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .deleteWidgetData(commonWidget); + + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + } + + @Test public void searchPortalIfUserIsNull() { EPUser user = null; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("searchPortal: User object is null? - check logs"); - expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController .searchPortal(mockedRequest, searchString); @@ -272,13 +362,12 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchStringNullTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = null; - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("searchPortal: String string is null"); - expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController @@ -289,10 +378,9 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - List<SearchResultItem> searchResultItemList = new ArrayList<SearchResultItem>(); + List<SearchResultItem> searchResultItemList = new ArrayList<>(); SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setId((long) 1); @@ -301,10 +389,10 @@ public class DashboardSearchResultControllerTest { searchResultItem.setTarget("test_target"); searchResultItem.setUuid("test_UUId"); searchResultItemList.add(searchResultItem); - Map<String, List<SearchResultItem>> expectedResultMap = new HashMap<String, List<SearchResultItem>>(); + Map<String, List<SearchResultItem>> expectedResultMap = new HashMap<>(); expectedResultMap.put(searchString, searchResultItemList); - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("success"); expectedResult.setResponse(expectedResultMap); expectedResult.setStatus(PortalRestStatusEnum.OK); @@ -319,13 +407,12 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchExcptionTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("null - check logs."); - expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(searchService.searchResults(user.getLoginId(), searchString)).thenThrow(nullPointerException); @@ -336,9 +423,8 @@ public class DashboardSearchResultControllerTest { @Test public void getActiveUsersTest() { - List<String> expectedActiveUsers = new ArrayList<String>(); + List<String> expectedActiveUsers = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String userId = user.getOrgUserId(); Mockito.when(searchService.getRelatedUsers(userId)).thenReturn(expectedActiveUsers); @@ -349,7 +435,7 @@ public class DashboardSearchResultControllerTest { @Test public void getActiveUsersExceptionTest() { - List<String> expectedActiveUsers = new ArrayList<String>(); + List<String> expectedActiveUsers = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String userId = user.getOrgUserId(); @@ -363,7 +449,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersTest() { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("success"); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.OK); @@ -377,7 +463,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersIfUserNullTest() { EPUser user = null; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("User object is null? - check logs"); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); @@ -390,7 +476,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersExceptionTest() { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("null - check logs."); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java index 73978a33..d8f98bb9 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -38,8 +40,9 @@ package org.onap.portalapp.portal.controller; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; import java.util.ArrayList; import java.util.Calendar; @@ -54,18 +57,15 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.portalapp.portal.controller.ExternalAppsRestfulController; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; -import org.onap.portalapp.portal.domain.UserRole; -import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; -import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.service.AdminRolesServiceImpl; @@ -82,7 +82,6 @@ import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; import org.onap.portalapp.portal.transport.FunctionalMenuItem; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; -import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.DataAccessServiceImpl; @@ -247,88 +246,124 @@ public class ExternalAppsRestfulControllerTest { .getFavoritesForUser(mockedRequest, mockedResponse); assertEquals(actaulFavorites.size(), 1); } - - @Test(expected=NullPointerException.class) - public void publishNotificationTest() throws Exception{ - EPApp appTest=new EPApp(); - Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn("RxH3983AHiyBOQmj"); - appTest.setUebKey("123456"); - String appKey="123456"; - EpNotificationItem notificationItem=new EpNotificationItem(); - List<Long> roleList = new ArrayList<Long>(); - Long role1 = (long) 1; - roleList.add(role1); - notificationItem.setRoleIds(roleList); - notificationItem.setIsForAllRoles("N"); - notificationItem.setIsForOnlineUsers("N"); - notificationItem.setActiveYn("Y"); - notificationItem.setPriority(1L); - notificationItem.setMsgHeader("testHeader"); - notificationItem.setMsgDescription("Test Description"); - Date currentDate = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(currentDate); - c.add(Calendar.DATE, 1); - Date currentDatePlusOne = c.getTime(); - notificationItem.setStartTime(currentDate); - notificationItem.setEndTime(currentDatePlusOne); - notificationItem.setCreatedDate(c.getTime()); - - PortalAPIResponse actualPortalRestResponse = new PortalAPIResponse(true, appKey); - PortalAPIResponse expectedPortalRestResponse = new PortalAPIResponse(true, appKey); - expectedPortalRestResponse.setMessage("SUCCESS"); - expectedPortalRestResponse.setStatus("ok"); - Map<String, String> params = new HashMap<>(); - params.put("appKey", "1234567"); - - Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)).thenReturn(null); - Mockito.when(userNotificationService.saveNotification(notificationItem)).thenReturn("Test"); - actualPortalRestResponse = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); - assertTrue(actualPortalRestResponse.equals(expectedPortalRestResponse)); - - } - - @Test(expected=NullPointerException.class) - public void publishNotificationTest1() throws Exception{ - EpNotificationItem notificationItem=new EpNotificationItem(); - List<Long> roleList = new ArrayList<Long>(); - Long role1 = (long) 1; - roleList.add(role1); - notificationItem.setRoleIds(roleList); - notificationItem.setIsForAllRoles("N"); - notificationItem.setIsForOnlineUsers("N"); - notificationItem.setActiveYn("Y"); - notificationItem.setPriority(1L); - notificationItem.setMsgHeader("testHeader"); - notificationItem.setMsgDescription("Test Description"); - Date currentDate = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(currentDate); - c.add(Calendar.DATE, 1); - Date currentDatePlusOne = c.getTime(); - notificationItem.setStartTime(currentDate); - notificationItem.setEndTime(currentDatePlusOne); - notificationItem.setCreatedDate(c.getTime()); - - //PowerMockito.mockStatic(EPApp.class); - - List<EPApp> appList = new ArrayList<>(); - EPApp app = mockApp(); - app.setId((long) 1); - appList.add(app); - - final Map<String, String> appUebkeyParams = new HashMap<>(); - appUebkeyParams.put("appKey", "test-ueb-key"); - - Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) - .thenReturn(appList); - //EPApp epApp=new EPApp(); - - Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn("RxH3983AHiyBOQmj"); + @Test + public void publishNotificationTest_Success() throws Exception { + // input + EpNotificationItem notificationItem = new EpNotificationItem(); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = 1L; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + notificationItem.setPriority(1L); + notificationItem.setMsgHeader("testHeader"); + notificationItem.setMsgDescription("Test Description"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); - externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + // mock calls + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn("RxH3983AHiyBOQmj"); + Map<String, String> params = new HashMap<>(); + params.put("appKey", "RxH3983AHiyBOQmj"); + List<EPApp> apps = new ArrayList<>(); + EPApp app = new EPApp(); + app.setId(123L); + apps.add(app); + Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)).thenReturn(apps); + EPRole role = new EPRole(); + role.setId(543L); + Mockito.when(epRoleService.getRole(123L, 1L)).thenReturn(role); + + // run + Mockito.when(userNotificationService.saveNotification(notificationItem)).thenReturn("Test"); + PortalAPIResponse response = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + // verify answer + assertNotNull(response); + assertEquals("ok", response.getStatus()); + assertEquals("success", response.getMessage()); + ArgumentCaptor<EpNotificationItem> capture = ArgumentCaptor.forClass(EpNotificationItem.class); + Mockito.verify(userNotificationService).saveNotification(capture.capture()); + assertNotNull(capture.getValue()); + EpNotificationItem createdNofification = capture.getValue(); + assertNotNull(createdNofification.getRoleIds()); + assertEquals(1, createdNofification.getRoleIds().size()); + assertEquals(543L, createdNofification.getRoleIds().get(0).longValue()); + } + + @Test + public void publishNotificationTest_EmptyAppHeader() throws Exception { + // input + EpNotificationItem notificationItem = new EpNotificationItem(); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = 1L; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + notificationItem.setPriority(1L); + notificationItem.setMsgHeader("testHeader"); + notificationItem.setMsgDescription("Test Description"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); + + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(null); + final Map<String, String> params = new HashMap<>(); + params.put("appKey", null); + Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)) + .thenThrow(NullPointerException.class); + + PortalAPIResponse response = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + assertNotNull(response); + assertEquals("ok", response.getStatus()); + assertEquals("success", response.getMessage()); + ArgumentCaptor<EpNotificationItem> capture = ArgumentCaptor.forClass(EpNotificationItem.class); + Mockito.verify(userNotificationService).saveNotification(capture.capture()); + assertNotNull(capture.getValue()); + EpNotificationItem createdNofification = capture.getValue(); + assertNotNull(createdNofification.getRoleIds()); + assertEquals(0, createdNofification.getRoleIds().size()); + } + + @Test + public void publishNotificationTest_ErrorResponse() throws Exception { + // input + EpNotificationItem notificationItem = new EpNotificationItem(); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = 1L; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + notificationItem.setPriority(1L); + notificationItem.setMsgHeader("testHeader"); + notificationItem.setMsgDescription("Test Description"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); + + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(null); + final Map<String, String> params = new HashMap<>(); + params.put("appKey", null); + Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)) + .thenThrow(NullPointerException.class); + Mockito.when(userNotificationService.saveNotification(any(EpNotificationItem.class))). + thenThrow(new NullPointerException("expected message")); + + PortalAPIResponse response = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + assertNotNull(response); + assertEquals("error", response.getStatus()); + assertEquals("expected message", response.getMessage()); + } - } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java index 21d0cf70..81e1f8b2 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java @@ -96,7 +96,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("rawtypes") @Mock - ResponseEntity<List<WidgetCatalog>> ans = new ResponseEntity<List<WidgetCatalog>>(HttpStatus.OK); + ResponseEntity<List<WidgetCatalog>> ans = new ResponseEntity<>(HttpStatus.OK); @Before public void setup() { @@ -114,11 +114,10 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @Test public void createMicroserviceIfServiceDataNullTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); MicroserviceData microserviceData = null; PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, mockedResponse, microserviceData); @@ -127,23 +126,35 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @Test public void createMicroserviceTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, mockedResponse, microserviceData); assertEquals(actualportalRestResponse, expectedportalRestResponse); } @Test + public void createMicroserviceXSSTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); + expectedportalRestResponse.setMessage("ERROR"); + expectedportalRestResponse.setResponse("MicroserviceData is not valid"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + MicroserviceData XSSMicroserviceData = new MicroserviceData(); + XSSMicroserviceData.setActive("<script>alert(123);</script>"); + XSSMicroserviceData.setName("<script>alert(/XSS”)</script>"); + PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, + mockedResponse, XSSMicroserviceData); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test public void createMicroserviceExceptionTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse(null); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(microserviceService.saveMicroservice(microserviceData)).thenReturn((long) 1); Mockito.when(microserviceData.getParameterList()).thenThrow(nullPointerException); PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, @@ -159,12 +170,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void updateMicroserviceIfServiceISNullTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void updateMicroserviceIfServiceISNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); MicroserviceData microserviceData = null; PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData); @@ -172,24 +182,36 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void updateMicroserviceTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void updateMicroserviceTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, - mockedResponse, 1, microserviceData); + mockedResponse, 1, microserviceData); assertEquals(actualportalRestResponse, expectedportalRestResponse); } @Test - public void updateMicroserviceExceptionTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void updateMicroserviceXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); + expectedportalRestResponse.setMessage("ERROR"); + expectedportalRestResponse.setResponse("MicroserviceData is not valid"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + MicroserviceData XSSMicroserviceData = new MicroserviceData(); + XSSMicroserviceData.setActive("<script>alert(123);</script>"); + XSSMicroserviceData.setName("<script>alert(/XSS”)</script>"); + PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, + mockedResponse, 1, XSSMicroserviceData); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void updateMicroserviceExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse(null); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData)) .thenThrow(nullPointerException); PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, @@ -198,14 +220,14 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void deleteMicroserviceExceptionTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void deleteMicroserviceExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); PowerMockito.mockStatic(EcompPortalUtils.class); expectedportalRestResponse.setResponse( - "I/O error on GET request for \"" + EcompPortalUtils.widgetMsProtocol() + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + "I/O error on GET request for \"" + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); PowerMockito.mockStatic(WidgetServiceHeaders.class); PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, mockedResponse, 1); @@ -215,13 +237,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("unchecked") @Test public void deleteMicroserviceTest() throws Exception { - String HTTPS = "https://"; - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SOME WIDGETS ASSOICATE WITH THIS SERVICE"); expectedportalRestResponse.setResponse("'null' ,'null' "); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.WARN); - List<WidgetCatalog> List = new ArrayList<WidgetCatalog>(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.WARN); + List<WidgetCatalog> List = new ArrayList<>(); WidgetCatalog widgetCatalog = new WidgetCatalog(); widgetCatalog.setId(1); WidgetCatalog widgetCatalog1 = new WidgetCatalog(); @@ -236,7 +256,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { }; Mockito.when(template.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + 1, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); @@ -248,12 +268,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("unchecked") @Test public void deleteMicroserviceWhenNoWidgetsAssociatedTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); - List<WidgetCatalog> List = new ArrayList<WidgetCatalog>(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + List<WidgetCatalog> List = new ArrayList<>(); PowerMockito.mockStatic(WidgetServiceHeaders.class); PowerMockito.mockStatic(EcompPortalUtils.class); String whatService = "widgets-service"; @@ -262,7 +281,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { }; Mockito.when(template.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + 1, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java index ff9fcffc..9673cb2c 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -76,6 +78,7 @@ import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.service.EPAppService; @@ -368,6 +371,48 @@ public class RoleManageControllerTest { } @Test + public void saveRoleFunctionXSSTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); + CentralV2RoleFunction addNewFunc = new CentralV2RoleFunction(); + addNewFunc.setCode("“><script>alert(“XSS”)</script>"); + addNewFunc.setType("Test"); + addNewFunc.setAction("Test"); + addNewFunc.setName("Test"); + CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); + roleFunction.setCode("Test|Test|Test"); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); + Mockito.when(externalAccessRolesService.saveCentralRoleFunction(Matchers.anyObject(), Matchers.anyObject())) + .thenReturn(true); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionType(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionAction(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPUser> userList = new ArrayList<>(); + userList.add(user); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + Mockito.when(externalAccessRolesService.getUser("guestT")).thenReturn(userList); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + PortalRestResponse<String> actual = roleManageController.saveRoleFunction(mockedRequest, mockedResponse, + addNewFunc, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + "Data is not valid", "ERROR"); + assertEquals(expected, actual); + } + + @Test public void saveRoleFunctionExceptionTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); @@ -418,6 +463,36 @@ public class RoleManageControllerTest { } @Test + public void removeRoleFunctionXSSTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + String roleFun = "<script>alert(/XSS”)</script>"; + CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(externalAccessRolesService.deleteCentralRoleFunction(Matchers.anyString(), Matchers.anyObject())) + .thenReturn(true); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + PortalRestResponse<String> actual = roleManageController.removeRoleFunction(mockedRequest, mockedResponse, + roleFun, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + "Data is not valid", "ERROR"); + assertEquals(expected, actual); + } + + @Test public void removeRoleFunctionExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); @@ -474,6 +549,9 @@ public class RoleManageControllerTest { @Test public void syncRolesException() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, null)).thenReturn(true); Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); PortalRestResponse<String> actual = roleManageController.syncRoles(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); @@ -483,6 +561,18 @@ public class RoleManageControllerTest { assertEquals(portalRestResponse, actual); } + @Test + public void syncRolesUserNullException() throws Exception { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); + Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); + PortalRestResponse<String> actual = roleManageController.syncRoles(mockedRequest, mockedResponse, 1l); + PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); + portalRestResponse.setMessage("Unauthorized User"); + portalRestResponse.setResponse("Failure"); + portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + assertEquals(portalRestResponse, actual); + } + @Test public void syncRolesFunctionsTest() throws Exception { PowerMockito.mockStatic(EPUserUtils.class); @@ -510,7 +600,10 @@ public class RoleManageControllerTest { @Test public void syncRolesFunctionsException() throws Exception { - Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, null)).thenReturn(true); + Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); PortalRestResponse<String> actual = roleManageController.syncFunctions(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); portalRestResponse.setMessage(null); @@ -519,6 +612,18 @@ public class RoleManageControllerTest { assertEquals(portalRestResponse, actual); } + @Test + public void syncRolesFunctionsUserNullException() throws Exception { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); + Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); + PortalRestResponse<String> actual = roleManageController.syncFunctions(mockedRequest, mockedResponse, 1l); + PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); + portalRestResponse.setMessage("Unauthorized User"); + portalRestResponse.setResponse("Failure"); + portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + assertEquals(portalRestResponse, actual); + } + @Test public void addChildRoleTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); @@ -875,6 +980,13 @@ public class RoleManageControllerTest { List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); assertEquals(cenApps.size(), actual.size()); } + + @Test + public void getCentralizedAppRolesXSSTest() throws IOException { + String id = ("<ScRipT>alert(\"XSS\");</ScRipT>"); + List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, id); + assertNull(actual); + } @Test public void getCentralizedAppRolesExceptionTest() throws IOException { @@ -890,6 +1002,16 @@ public class RoleManageControllerTest { List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); assertNull(actual); } + + @Test + public void bulkUploadRoleFuncUserNullTest() { + UploadRoleFunctionExtSystem data = Mockito.mock(UploadRoleFunctionExtSystem.class); + Mockito.when(appService.getApp(127L)).thenReturn(null); + PortalRestResponse<String> response = roleManageController.bulkUploadRoleFunc(mockedRequest, mockedResponse, data, 127L); + assertEquals(PortalRestStatusEnum.ERROR, response.getStatus()); + assertEquals("Unauthorized User", response.getMessage()); + assertEquals("Failure", response.getResponse()); + } public CentralV2RoleFunction mockCentralRoleFunction() { CentralV2RoleFunction roleFunction = new CentralV2RoleFunction(); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java index 8216510b..b1816ec6 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java @@ -37,12 +37,18 @@ */ package org.onap.portalapp.portal.controller; +import static org.junit.Assert.*; + +import java.util.HashSet; +import java.util.Set; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.formula.functions.T; import org.json.simple.JSONObject; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -52,25 +58,30 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalapp.portal.controller.SchedulerController; import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.SchedulerRestInterface; import org.onap.portalapp.portal.scheduler.restobjects.RestObject; +import org.onap.portalapp.portal.service.AdminRolesService; +import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; @RunWith(PowerMockRunner.class) -@PrepareForTest({UserUtils.class,SystemProperties.class,SchedulerProperties.class}) - +@PrepareForTest({UserUtils.class,SystemProperties.class,SchedulerProperties.class,EPUserUtils.class}) public class SchedulerControllerTest { @Mock SchedulerRestInterface schedulerRestInterface; - + @Mock + AdminRolesService adminRolesService; @InjectMocks SchedulerController schedulerController = new SchedulerController(); @@ -89,6 +100,18 @@ public class SchedulerControllerTest { @Test public void getTimeSlotsTest() throws Exception{ + JSONObject jsonObject =Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("/get_time_slots/*"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.getTimeSlots(mockedRequest, "12"); } @@ -96,6 +119,17 @@ public class SchedulerControllerTest { @Test public void getTimeSlotsTestWithException1() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("/get_time_slots/*"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); RestObject<T> restObject=new RestObject<>(); Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Get(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any()); schedulerController.getTimeSlots(mockedRequest, "12"); @@ -105,6 +139,17 @@ public class SchedulerControllerTest { @Test public void getTimeSlotsTestWithexception() throws Exception{ + JSONObject jsonObject =Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("/get_time_slots/*"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.getTimeSlots(mockedRequest, null); } @@ -113,7 +158,17 @@ public class SchedulerControllerTest { public void postCreateNewVNFChangeTest() throws Exception{ //String testJsonData="{\"domain\":\"ChangeManagement\",\"scheduleName\":\"VnfUpgrade/DWF\",\"userId\":\"su7376\",\"domainData\":[{\"WorkflowName\":\"HEAT Stack Software Update for vNFs\",\"CallbackUrl\":\"http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid\",\"CallbackData\":\"testing\"}],\"schedulingInfo\":{\"normalDurationInSeconds\":60,\"additionalDurationInSeconds\":60,\"concurrencyLimit\":60,\"policyId\":\"SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml\",\"vnfDetails\":[{\"groupId\":\"group1\",\"node\":[\"satmo415vbc\",\"satmo455vbc\"]}]}}"; JSONObject jsonObject =Mockito.mock(JSONObject.class); - + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("post_create_new_vnf_change"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.postCreateNewVNFChange(mockedRequest, jsonObject); } @@ -121,6 +176,17 @@ public class SchedulerControllerTest { public void postCreateNewVNFChangeTestWithException1() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); RestObject<T> restObject=new RestObject<>(); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("post_create_new_vnf_change"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Post(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any()); schedulerController.postCreateNewVNFChange(mockedRequest, jsonObject); @@ -131,7 +197,16 @@ public class SchedulerControllerTest { public void postCreateNewVNFChangeTestWithException() throws Exception{ //String testJsonData="{\"domain\":\"ChangeManagement\",\"scheduleName\":\"VnfUpgrade/DWF\",\"userId\":\"su7376\",\"domainData\":[{\"WorkflowName\":\"HEAT Stack Software Update for vNFs\",\"CallbackUrl\":\"http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid\",\"CallbackData\":\"testing\"}],\"schedulingInfo\":{\"normalDurationInSeconds\":60,\"additionalDurationInSeconds\":60,\"concurrencyLimit\":60,\"policyId\":\"SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml\",\"vnfDetails\":[{\"groupId\":\"group1\",\"node\":[\"satmo415vbc\",\"satmo455vbc\"]}]}}"; JSONObject jsonObject =Mockito.mock(JSONObject.class); - + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("post_create_new_vnf_change"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.postCreateNewVNFChange(mockedRequest, null); } @@ -139,6 +214,16 @@ public class SchedulerControllerTest { public void postSubmitVnfChangeTimeslotsTest() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals"); schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, jsonObject); @@ -147,25 +232,53 @@ public class SchedulerControllerTest { @Test public void postSubmitVnfChangeTimeslotsTestWithException1() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); - RestObject<T> restObject=new RestObject<>(); - Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Post(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any()); - schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, jsonObject); - + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals"); + ResponseEntity<String> res = schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null); } @Test public void postSubmitVnfChangeTimeslotsTestWithException() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals"); - schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null); + ResponseEntity<String> res = schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null); + assertEquals(res.getStatusCode(), HttpStatus.UNAUTHORIZED); } + @Test public void getSchedulerConstantTestWithException() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("get_scheduler_constant"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_scheduler_constant"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CALLBACK_URL)).thenReturn("mockedRequest"); schedulerController.getSchedulerConstant(mockedRequest, mockedResponse); @@ -174,7 +287,17 @@ public class SchedulerControllerTest { @Test public void getSchedulerConstantTest() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); - //Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CALLBACK_URL)).thenReturn("callbackUrl"); schedulerController.getSchedulerConstant(mockedRequest, mockedResponse); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java index aca7c1b3..211462d1 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java @@ -151,6 +151,18 @@ public class TicketEventControllerTest { } @Test + public void saveXSSTest() throws Exception { + String ticketEventJson = "<iframe %00 src=\"	javascript:prompt(1)	\"%00>"; + PortalRestResponse<String> actualPortalRestResponse; + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + expectedPortalRestResponse.setMessage("Data is not valid"); + actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, + mockedResponse, ticketEventJson); + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + } + + @Test public void saveTestForException() throws Exception { String ticketEventJson = "\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java index e5ee9d92..caf3ac42 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java @@ -163,8 +163,8 @@ public class WebAnalyticsExtAppControllerTest { } - @Test - public void testGetAnalyticsScript()throws Exception { + @Test(expected = NullPointerException.class) + public void testGetAnalyticsScript() { PowerMockito.mockStatic(SystemProperties.class); Mockito.when(SystemProperties.getProperty("frontend_url")).thenReturn("http://www.ecomp.com/test"); webAnalyticsExtAppController.getAnalyticsScript(mockedRequest); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java index 2cc03a60..0923d033 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java @@ -121,10 +121,9 @@ public class EPUserAppTest { } - + @Test public void testEquals(){ - EPRole epRole = new EPRole(); epRole.setId((long) 12345); epRole.setName("test"); @@ -132,19 +131,22 @@ public class EPUserAppTest { epRole.setPriority(1); epRole.setAppId((long)1); epRole.setAppRoleId((long)1); - + EPUserApp user1 = mockEPUserApp(); user1.setApp(mockEPApp()); user1.setRole(epRole); - + EPUserApp user2 = mockEPUserApp(); user2.setApp(mockEPApp()); user2.setRole(epRole); - + + EPUserApp nullUser = null; + + assertTrue(user1.equals(user1)); + assertFalse(user1.equals(nullUser)); + assertFalse(user1.equals(Long.valueOf(1))); assertTrue(user1.equals(user2)); - } - private EPApp mockEPApp() { EPApp epApp = new EPApp(); epApp.setId((long) 12345); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java index 15f021c5..f14d3fd9 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java @@ -4,6 +4,8 @@ * =================================================================== * 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"); @@ -93,6 +95,9 @@ public class AdminRolesServiceImplTest { @Mock DataAccessService dataAccessService = new DataAccessServiceImpl(); + @Mock + ExternalAccessRolesService externalAccessRolesService; + @Mock EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); @@ -370,6 +375,25 @@ public class AdminRolesServiceImplTest { assertFalse(actual); } + @Test + public void isAccountAdminUserNull() { + boolean actual = adminRolesServiceImpl.isAccountAdmin(null); + assertFalse(actual); + } + + @Test + public void isRoleAdminTest() { + EPUser user = mockUser.mockEPUser(); + List<String> roles = new ArrayList<>(); + roles.add("approver\\|"); + Mockito.when(dataAccessService.executeNamedQuery( + Matchers.eq("getRoleFunctionsOfUserforAlltheApplications"), Matchers.any(), Matchers.any())) + .thenReturn(roles); + Mockito.when(externalAccessRolesService.getFunctionCodeType(Matchers.anyString())).thenReturn("approver"); + boolean actual = adminRolesServiceImpl.isRoleAdmin(user); + assertTrue(actual); + } + @Test public void isUserTest() { EPUser user = mockUser.mockEPUser(); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java index c5808d3c..1451693d 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java @@ -52,6 +52,7 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; +import org.json.JSONObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -96,6 +97,11 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.cambria.client.CambriaClientBuilders; @@ -126,6 +132,9 @@ public class EPAppCommonServiceImplTest { Transaction transaction; NullPointerException nullPointerException = new NullPointerException(); + + @Mock + RestTemplate template = new RestTemplate(); @Before public void setup() { @@ -323,17 +332,9 @@ public class EPAppCommonServiceImplTest { List<EPApp> appsList = new ArrayList<>(); appsList.add(mockApp); appsList.add(mockApp2); - List<AppsResponse> expected = new ArrayList<>(); - AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(), - mockApp.getEnabled()); - AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(), - mockApp2.getEnabled()); - expected.add(appResponse1); - expected.add(appResponse2); Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null)).thenReturn(appsList); List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(false); - assertEquals(expected.size(), actual.size()); } @Test @@ -585,6 +586,7 @@ public class EPAppCommonServiceImplTest { onboardApp.name = "test1"; onboardApp.id = 2l; onboardApp.url = "http://test.com"; + onboardApp.restUrl = "http://test.com"; onboardApp.isOpen = false; onboardApp.isEnabled = true; onboardApp.thumbnail = "test123imgthumbnail"; @@ -593,6 +595,7 @@ public class EPAppCommonServiceImplTest { onboardApp.isCentralAuth=true; onboardApp.myLoginsAppName="test123"; onboardApp.myLoginsAppOwner="test123"; + onboardApp.nameSpace="com.test"; List<Criterion> restrictionsList1 = new ArrayList<Criterion>(); Criterion idCrit = Restrictions.eq("id", onboardApp.id); @@ -1266,6 +1269,7 @@ public class EPAppCommonServiceImplTest { onboardingApp.setRestrictedApp(true); onboardingApp.isCentralAuth=false; + onboardingApp.isEnabled= true; FieldsValidator actual = epAppCommonServiceImpl.addOnboardingApp(onboardingApp, epUser); assertEquals(expected.getHttpStatusCode(), actual.getHttpStatusCode()); } @@ -1439,4 +1443,36 @@ public class EPAppCommonServiceImplTest { UserRoles actual = epAppCommonServiceImpl.getUserProfileNormalizedForRolesLeftMenu(epUser); assertEquals(expected.getRoles(), actual.getRoles()); } + + @Test(expected = Exception.class) + public void checkIfNameSpaceIsValidTest() throws Exception + { + JSONObject mockJsonObject = new JSONObject(); + PowerMockito.mockStatic(EcompPortalUtils.class); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + epAppCommonServiceImpl.checkIfNameSpaceIsValid("com.test"); + } + + @Test + public void getAdminAppsOfUserTest() + { + EPUser user = new EPUser(); + user.setId((long) 1); + List<Integer> userAdminApps = new ArrayList<>(); + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(mockApp); + appsList.add(mockApp2); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)) + .thenReturn(appsList); + Mockito.when(dataAccessService.executeNamedQuery(Matchers.anyString(), Matchers.anyMap(), Matchers.anyMap())) + .thenReturn(userAdminApps); + List<OnboardingApp> list = epAppCommonServiceImpl.getAdminAppsOfUser(user); + assertEquals(list.size(), 0); + + } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java index d1ad191a..0e59d643 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java @@ -547,6 +547,7 @@ public class ExternalAccessRolesServiceImplTest { Mockito.when(EcompPortalUtils.getFunctionCode("test_type_1|type_code_1|*")).thenReturn("type_code_1"); Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type"); Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*"); + Mockito.when(EcompPortalUtils.encodeFunctionCode("type_code")).thenReturn("type_code"); List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>(); CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); CentralV2RoleFunction getCenRole2 = new CentralV2RoleFunction("test_type_1|type_code_1|*", "test_name_1"); @@ -1761,8 +1762,8 @@ public class ExternalAccessRolesServiceImplTest { mockJsonObjectRole.put("name", "com.test.app.Test"); mockJsonObjectRole.put("perms", permsList); mockJsonObjectRole.put("description", - "{\"id\":\"2\",\"name\":\"test1\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"2\"}"); - mockJsonObjectRole2.put("name", "com.test.app.Test2"); + "Test role"); + mockJsonObjectRole2.put("name", "com.test.app.Test2_role"); List<JSONObject> permsList2 = new ArrayList<>(); permsList2.add(mockJsonObjectPerm1); mockJsonObjectRole2.put("perms", permsList2); @@ -1775,19 +1776,26 @@ public class ExternalAccessRolesServiceImplTest { Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); List<EPRole> getCurrentRoleList = new ArrayList<>(); EPRole getEPRole = new EPRole(); - getEPRole.setName("Test"); + getEPRole.setName("Test role"); getEPRole.setId(2l); getEPRole.setAppId(app.getId()); getEPRole.setAppRoleId(2l); getEPRole.setActive(true); EPRole getEPRole2 = new EPRole(); - getEPRole2.setName("Test3"); + getEPRole2.setName("Test2_role"); getEPRole2.setId(3l); - getEPRole.setAppId(app.getId()); - getEPRole.setAppRoleId(3l); + getEPRole2.setAppId(app.getId()); + getEPRole2.setAppRoleId(3l); getEPRole2.setActive(true); + EPRole getEPRole3 = new EPRole(); + getEPRole3.setName("Test3_role"); + getEPRole3.setId(3l); + getEPRole3.setAppId(app.getId()); + getEPRole3.setAppRoleId(3l); + getEPRole3.setActive(true); getCurrentRoleList.add(getEPRole); getCurrentRoleList.add(getEPRole2); + getCurrentRoleList.add(getEPRole3); final Map<String, Long> appParams = new HashMap<>(); appParams.put("appId", app.getId()); Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) @@ -1822,10 +1830,10 @@ public class ExternalAccessRolesServiceImplTest { getV2RoleFunction.add(centralV2RoleFunction); final Map<String, String> extRoleParams = new HashMap<>(); List<EPRole> roleListDeactivate = new ArrayList<>(); - extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3"); + extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3_role"); extRoleParams.put(APP_ID, app.getId().toString()); EPRole getEPRoleDeactivate = new EPRole(); - getEPRoleDeactivate.setName("Test3"); + getEPRoleDeactivate.setName("Test3_role"); getEPRoleDeactivate.setId(3l); getEPRoleDeactivate.setAppId(app.getId()); getEPRoleDeactivate.setAppRoleId(3l); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java index c907a6e5..fb6c325c 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -55,6 +55,7 @@ import java.util.TreeSet; import javax.servlet.http.HttpServletResponse; import org.apache.cxf.transport.http.HTTPException; +import org.drools.core.command.assertion.AssertEquals; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; @@ -239,6 +240,27 @@ public class UserRolesCommonServiceImplTest { @SuppressWarnings("unchecked") @Test + public void checkTheProtectionAgainstSQLInjection() throws Exception { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + user.setOrgId(2l); + Query epUserQuery = Mockito.mock(Query.class); + List<EPUser> mockEPUserList = new ArrayList<>(); + mockEPUserList.add(user); + + Mockito.when(session.createQuery("from :name where orgUserId=:userId")).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("name",EPUser.class.getName())).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("userId",user.getOrgUserId() + "; select * from " + EPUser.class.getName() +";")).thenReturn(epUserQuery); + userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId(),true); + + Mockito.when(session.createQuery("from :name where orgUserId=:userId")).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("name",EPUser.class.getName())).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("userId",user.getOrgUserId())).thenReturn(epUserQuery); + userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId(),true); + } + + @SuppressWarnings("unchecked") + @Test public void getAppRolesForUserNonCentralizedForPortal() throws Exception { EPUser user = mockUser.mockEPUser(); user.setId(1l); @@ -424,24 +446,37 @@ public class UserRolesCommonServiceImplTest { Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) .thenReturn(mockEcompRoleArray); // syncAppRolesTest - Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=" + mockApp.getId())) + + Mockito.when(session.createQuery("from :name where appId = :appId")) .thenReturn(epRoleQuery); + + Mockito.when(epRoleQuery.setParameter("name",EPRole.class.getName())).thenReturn(epRoleQuery); + Mockito.when(epRoleQuery.setParameter("appId",mockApp.getId())).thenReturn(epRoleQuery); + Mockito.doReturn(mockEPRoleList).when(epRoleQuery).list(); - Mockito.when(session.createQuery( - "from " + EPUserApp.class.getName() + " where app.id=" + mockApp.getId() + " and role_id=" + 15l)) + Mockito.when(session.createQuery("from :name where app.id=:appId and role_id=:roleId")) .thenReturn(epUserAppsQuery); + Mockito.when(epUserAppsQuery.setParameter("name",EPUserApp.class.getName())).thenReturn(epUserAppsQuery); + Mockito.when(epUserAppsQuery.setParameter("appId",mockApp.getId())).thenReturn(epUserAppsQuery); + Mockito.when(epUserAppsQuery.setParameter("roleId",15l)).thenReturn(epUserAppsQuery); Mockito.doReturn(mockUserRolesList).when(epUserAppsQuery).list(); - Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + 15l)) + Mockito.when(session.createQuery("from :name where roleId=:roleId")) .thenReturn(epFunctionalMenuQuery); + Mockito.when(epFunctionalMenuQuery.setParameter("name",FunctionalMenuRole.class.getName())).thenReturn(epFunctionalMenuQuery); + Mockito.when(epFunctionalMenuQuery.setParameter("roleId",15l)).thenReturn(epFunctionalMenuQuery); Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery).list(); - Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + 10l)) + Mockito.when(session.createQuery("from :name where menuId=:menuId")) .thenReturn(epFunctionalMenuQuery2); + Mockito.when(epFunctionalMenuQuery2.setParameter("name",FunctionalMenuRole.class.getName())).thenReturn(epFunctionalMenuQuery2); + Mockito.when(epFunctionalMenuQuery2.setParameter("menuId",10l)).thenReturn(epFunctionalMenuQuery2); Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery2).list(); - Mockito.when(session.createQuery("from " + FunctionalMenuItem.class.getName() + " where menuId=" + 10l)) + Mockito.when(session.createQuery("from :name where menuId=:menuId")) .thenReturn(epFunctionalMenuItemQuery); + Mockito.when(epFunctionalMenuItemQuery.setParameter("name",FunctionalMenuItem.class.getName())).thenReturn(epFunctionalMenuItemQuery); + Mockito.when(epFunctionalMenuItemQuery.setParameter("menuId",10l)).thenReturn(epFunctionalMenuItemQuery); Mockito.doReturn(mockFunctionalMenuItemList).when(epFunctionalMenuItemQuery).list(); List<EcompRole> mockEcompRoleList2 = new ArrayList<>(); EcompRole mockUserAppRoles = new EcompRole(); @@ -1314,7 +1349,7 @@ public class UserRolesCommonServiceImplTest { EPUserAppRolesRequest mockEpAppRolesRequestData = new EPUserAppRolesRequest(); Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEpAppRolesRequestData, null); final Map<String, Long> params = new HashMap<>(); - params.put("appId", appWithRolesForUser.appId); + params.put("appId", appWithRolesForUser.getAppId()); params.put("appRoleId", roleInAppForUser.roleId); Mockito.when((List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null)) .thenReturn(epUserAppRolesList); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java index c9f3195a..52f30518 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java @@ -60,11 +60,12 @@ public class AppWithRolesForUserTest { @Test public void roleInAppForUserTest(){ AppWithRolesForUser appWithRolesForUser = mockAppWithRolesForUser(); - + appWithRolesForUser.setSystemUser(false); assertEquals(appWithRolesForUser.getOrgUserId(), "test"); assertEquals(appWithRolesForUser.getAppId(), new Long(1)); assertEquals(appWithRolesForUser.getAppName(), "test"); assertEquals(appWithRolesForUser.getAppRoles(), null); - assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser [orgUserId=test, appId=1, appName=test, appRoles=null]"); + assertEquals(appWithRolesForUser.isSystemUser(), false); + assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser(orgUserId=test, isSystemUser=false, appId=1, appName=test, appRoles=null)"); } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java index 6340eb92..a41cbd82 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java @@ -117,6 +117,18 @@ public class CentralUserAppTest { assertEquals(centralV2UserApp.getApp(), app1); assertEquals(centralV2UserApp.getRole(), role1); } + + @Test + public void centralUserAppEqualsTest(){ + CentralV2UserApp centralV2UserApp = mockCentralUserApp(); + CentralV2UserApp centralV2UserApp2 = mockCentralUserApp(); + + assertTrue(centralV2UserApp.equals(centralV2UserApp)); + assertTrue(centralV2UserApp.equals(centralV2UserApp2)); + assertFalse(centralV2UserApp.equals(new Long(1))); + centralV2UserApp2.setPriority(213); + assertFalse(centralV2UserApp.equals(centralV2UserApp2)); + } @Test public void unt_hashCodeTest(){ diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java index 73508ec9..4f1c6613 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java @@ -38,6 +38,8 @@ package org.onap.portalapp.portal.utils; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; @@ -47,7 +49,6 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.onap.portalapp.portal.core.MockEPUser; -import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.framework.MockitoTestSuite; public class EcompPortalUtilsTest { @@ -96,8 +97,18 @@ public class EcompPortalUtilsTest { } @Test - public void setBadPermissionsForEmptyUserTest() { - EcompPortalUtils.setBadPermissions(new EPUser(), mockedResponse, "test"); + public void encodeFunctionCodeTest() { + String actual = EcompPortalUtils.encodeFunctionCode("test/function*code"); + assertEquals("test%2ffunction%2acode", actual); + } + + @Test + public void checkFunctionCodeHasEncodePatternTrueTest() { + assertTrue(EcompPortalUtils.checkFunctionCodeHasEncodePattern("test/function*code")); + } + + @Test + public void checkFunctionCodeHasEncodePatternFalseTest() { + assertFalse(EcompPortalUtils.checkFunctionCodeHasEncodePattern("test-function-code")); } - } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/validation/DataValidatorTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/validation/DataValidatorTest.java new file mode 100644 index 00000000..2dbfdcd7 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/validation/DataValidatorTest.java @@ -0,0 +1,98 @@ +/*- + * ============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.portalapp.validation; + +import static org.junit.Assert.*; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import org.drools.core.command.assertion.AssertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.onap.portalapp.portal.domain.EPUser; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.beans.factory.annotation.Autowired; + +@RunWith(PowerMockRunner.class) +public class DataValidatorTest { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + @InjectMocks + DataValidator dataValidator; + + @Test + public void getConstraintViolationsSecureString() { + SecureString secureString = new SecureString("<script>alert(“XSS”);</script>"); + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<SecureString>> expectedConstraintViolations = validator.validate(secureString); + Set<ConstraintViolation<SecureString>> actualConstraintViolations = dataValidator.getConstraintViolations(secureString); + assertEquals(expectedConstraintViolations, actualConstraintViolations); + } + + @Test + public void isValidSecureString() { + SecureString secureString = new SecureString("<script>alert(“XSS”);</script>"); + assertFalse(dataValidator.isValid(secureString)); + } + + @Test + public void getConstraintViolationsEPUser() { + EPUser user = new EPUser(); + user.setEmail("“><script>alert(“XSS”)</script>"); + user.setLoginId("<IMG SRC=”javascript:alert(‘XSS’);”>"); + user.setFinancialLocCode("<IMG SRC=javascript:alert(‘XSS’)> "); + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<EPUser>> expectedConstraintViolations = validator.validate(user); + Set<ConstraintViolation<EPUser>> actualConstraintViolations = dataValidator.getConstraintViolations(user); + assertEquals(expectedConstraintViolations, actualConstraintViolations); + } + + @Test + public void isValidEPUser() { + EPUser user = new EPUser(); + user.setEmail("“><script>alert(“XSS”)</script>"); + user.setLoginId("<IMG SRC=”javascript:alert(‘XSS’);”>"); + user.setFinancialLocCode("<IMG SRC=javascript:alert(‘XSS’)> "); + assertFalse(dataValidator.isValid(user)); + } + +} |