From: Dominik Mizyn Date: Mon, 18 Nov 2019 12:08:23 +0000 (+0100) Subject: UserRolesController methods up X-Git-Tag: 3.2.0~66 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=portal.git;a=commitdiff_plain;h=refs%2Fchanges%2F01%2F98501%2F2 UserRolesController methods up putAppWithUserRoleStateForUser() up Issue-ID: PORTAL-710 Change-Id: Ie0d03fc28d684bb0362901b0ec108941e70f6b9c Signed-off-by: Dominik Mizyn --- diff --git a/portal-BE/pom.xml b/portal-BE/pom.xml index 13477b68..a882f751 100644 --- a/portal-BE/pom.xml +++ b/portal-BE/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.2.0.M4 + 2.2.1.RELEASE org.onap @@ -188,7 +188,7 @@ org.apache.cxf cxf-rt-rs-client - 3.3.2 + 3.3.4 compile diff --git a/portal-BE/src/main/java/org/onap/portal/controller/LanguageController.java b/portal-BE/src/main/java/org/onap/portal/controller/LanguageController.java index c545d7f1..c470aead 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/LanguageController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/LanguageController.java @@ -101,7 +101,7 @@ public class LanguageController { @SuppressWarnings("OptionalGetWithoutIsPresent") FnUser user = fnUserService.getUser(userId).get(); user.setLanguageId(fnLanguage); - fnUserService.saveFnUser(principal, user); + fnUserService.saveFnUser(user); //response.setResponse(fnUserMapper.fnUserToFnUserDto(user).toString()); response.setMessage("SUCCESS"); response.setStatus(PortalRestStatusEnum.OK); diff --git a/portal-BE/src/main/java/org/onap/portal/controller/UserController.java b/portal-BE/src/main/java/org/onap/portal/controller/UserController.java index c2dcccd6..8057a9a6 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/UserController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/UserController.java @@ -113,7 +113,7 @@ public class UserController { user.setLoginPwd(CipherUtil .encryptPKC(profileDetail.getLoginPassword(), "AGLDdG4D04BKm2IxIWEr8o==!")); } - userService.saveFnUser(principal, user); + userService.saveFnUser(user); // Update user info in the session portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null); } diff --git a/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java index ce7cf1f9..da3026e1 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java @@ -51,17 +51,30 @@ import org.apache.cxf.transport.http.HTTPException; import org.onap.portal.domain.db.fn.FnRole; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles; +import org.onap.portal.domain.dto.ecomp.EcompAuditLog; import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess; +import org.onap.portal.domain.dto.ecomp.PortalRestResponse; +import org.onap.portal.domain.dto.ecomp.PortalRestStatusEnum; import org.onap.portal.domain.dto.transport.AppWithRolesForUser; +import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator; import org.onap.portal.domain.dto.transport.FieldsValidator; +import org.onap.portal.domain.dto.transport.RoleInAppForUser; import org.onap.portal.domain.dto.transport.UserApplicationRoles; +import org.onap.portal.logging.aop.EPEELFLoggerAdvice; +import org.onap.portal.logging.logic.EPLogUtil; import org.onap.portal.service.AdminRolesService; import org.onap.portal.service.ApplicationsRestClientService; import org.onap.portal.service.fn.FnUserRoleService; import org.onap.portal.service.fn.FnUserService; +import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portal.utils.PortalConstants; +import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.service.AuditServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.PathVariable; @@ -81,6 +94,7 @@ public class UserRolesController { private final FnUserRoleService fnUserRoleService; private final AdminRolesService adminRolesService; private final ApplicationsRestClientService applicationsRestClientService; + private final AuditServiceImpl auditService = new AuditServiceImpl(); /* private final UserRolesService userRolesService; @@ -316,112 +330,112 @@ public class UserRolesController { } return result; } + */ - @RequestMapping(value = {"/portalApi/userAppRoles"}, method = { - RequestMethod.PUT}, produces = "application/json") - public PortalRestResponse putAppWithUserRoleStateForUser(Principal principal, - @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { - // FieldsValidator fieldsValidator = new FieldsValidator(); - PortalRestResponse portalResponse = new PortalRestResponse<>(); - StringBuilder sbUserApps = new StringBuilder(); - if (newAppRolesForUser != null) { - sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId()); - if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) { - sbUserApps.append("' has roles = { "); - for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) { - if (appRole.isApplied) { - sbUserApps.append(appRole.roleName + " ,"); - } + @RequestMapping(value = {"/portalApi/userAppRoles"}, method = { + RequestMethod.PUT}, produces = "application/json") + public PortalRestResponse putAppWithUserRoleStateForUser(Principal principal, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { + // FieldsValidator fieldsValidator = new FieldsValidator(); + PortalRestResponse portalResponse = new PortalRestResponse<>(); + StringBuilder sbUserApps = new StringBuilder(); + if (newAppRolesForUser != null) { + sbUserApps.append("User '").append(newAppRolesForUser.getOrgUserId()); + if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) { + sbUserApps.append("' has roles = { "); + for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) { + if (appRole.getIsApplied()) { + sbUserApps.append(appRole.getRoleName()).append(" ,"); } - sbUserApps.deleteCharAt(sbUserApps.length() - 1); - sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId()); - } else { - sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId()); } - } - logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", - sbUserApps.toString()); - - FnUser user = fnUserService.loadUserByUsername(principal.getName()); - // boolean changesApplied = false; - ExternalRequestFieldsValidator changesApplied = null; - - if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) { - EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser"); - } else if (newAppRolesForUser == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "putAppWithUserRoleStateForUser: newAppRolesForUser is null"); + sbUserApps.deleteCharAt(sbUserApps.length() - 1); + sbUserApps.append("} assigned for the app ").append(newAppRolesForUser.getAppId()); } else { - changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser); - try { - if (changesApplied.isResult()) { - logger.info(EELFLoggerDelegate.applicationLogger, - "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.getOrgUserId()); - auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), - PortalConstants.AUDIT_LOG_COMMENT_SIZE)); - auditService.logActivity(auditLog, null); - - 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( - "UserRolesController.putAppWithUserRoleStateForUser", - EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), - newAppRolesForUser.getOrgUserId(), sbUserApps.toString())); - MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); - MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); - MDC.remove(SystemProperties.MDC_TIMER); - portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null); - - } - if (!changesApplied.isResult()) { - throw new Exception(changesApplied.getDetailMessage()); - } - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "putAppWithUserRoleStateForUser: failed for app {}, user {}", - newAppRolesForUser.getAppId(), - newAppRolesForUser.getOrgUserId(), e); - portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null); - } + sbUserApps.append("' has no roles assigned for app ").append(newAppRolesForUser.getAppId()); } - - EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied); - return portalResponse; } + logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", + sbUserApps.toString()); - @RequestMapping(value = {"/portalApi/updateRemoteUserProfile"}, method = { - RequestMethod.GET}, produces = "application/json") - public PortalRestResponse updateRemoteUserProfile(HttpServletRequest request) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + // boolean changesApplied = false; + ExternalRequestFieldsValidator changesApplied = null; - String updateRemoteUserFlag = FAILURE; + if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser"); + } else if (newAppRolesForUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: newAppRolesForUser is null"); + } else { + changesApplied = adminRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser); try { - // saveNewUser = userService.saveNewUser(newUser); - String orgUserId = request.getParameter("loginId"); - Long appId = Long.parseLong(request.getParameter("appId")); - userRolesService.updateRemoteUserProfile(orgUserId, appId); + if (changesApplied.isResult()) { + logger.info(EELFLoggerDelegate.applicationLogger, + "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.getOrgUserId()); + auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + + 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( + "UserRolesController.putAppWithUserRoleStateForUser", + EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), + newAppRolesForUser.getOrgUserId(), sbUserApps.toString())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null); + + } + if (!changesApplied.isResult()) { + throw new Exception(changesApplied.getDetailMessage()); + } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e); - return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: failed for app {}, user {}", + newAppRolesForUser.getAppId(), + newAppRolesForUser.getOrgUserId(), e); + portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null); } - return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, ""); + } + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied); + return portalResponse; + } + @RequestMapping(value = {"/portalApi/updateRemoteUserProfile"}, method = { + RequestMethod.GET}, produces = "application/json") + public PortalRestResponse updateRemoteUserProfile(HttpServletRequest request) { + + String updateRemoteUserFlag = FAILURE; + try { + // saveNewUser = userService.saveNewUser(newUser); + String orgUserId = request.getParameter("loginId"); + long appId = Long.parseLong(request.getParameter("appId")); + fnUserRoleService.updateRemoteUserProfile(orgUserId, appId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage()); } - */ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, ""); + + } + @RequestMapping(value = {"/portalApi/app/{appId}/users"}, method = { RequestMethod.GET}, produces = "application/json") public List getUsersFromAppEndpoint(@PathVariable("appId") Long appId) { @@ -488,9 +502,8 @@ public class UserRolesController { public FieldsValidator putAppWithUserRoleRequest(Principal principal, @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { FieldsValidator fieldsValidator = null; + FnUser user = fnUserService.loadUserByUsername(principal.getName()); try { - - FnUser user = fnUserService.loadUserByUsername(principal.getName()); fieldsValidator = fnUserRoleService.putUserAppRolesRequest(newAppRolesForUser, user); response.setStatus(0); @@ -505,6 +518,7 @@ public class UserRolesController { } + @SuppressWarnings("ConstantConditions") @RequestMapping(value = {"/portalApi/appCatalogRoles"}, method = { RequestMethod.GET}, produces = "application/json") public List getUserAppCatalogRoles(Principal principal, diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java index 849b2620..603e45d2 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java @@ -57,8 +57,8 @@ import org.onap.portal.domain.dto.transport.Analytics; import org.onap.portal.logging.aop.EPAuditLog; import org.onap.portal.logging.aop.EPEELFLoggerAdvice; import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.AppsCacheService; import org.onap.portal.service.WidgetMService; -import org.onap.portal.service.fn.old.AppsCacheService; import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portal.utils.EcompPortalUtils; import org.onap.portal.utils.PortalConstants; diff --git a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpAppFunctionDao.java b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpAppFunctionDao.java new file mode 100644 index 00000000..935e5646 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpAppFunctionDao.java @@ -0,0 +1,59 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.dao.ep; + +import java.util.List; +import org.onap.portal.domain.db.ep.EpAppFunction; +import org.onap.portal.domain.db.ep.EpAppFunction.EpAppFunctionId; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional +public interface EpAppFunctionDao extends JpaRepository { + + @Query + List getAppRoleFunctionList(final @Param("roleId") Long roleId, final @Param("appId") Long appId); + +} diff --git a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDao.java b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDao.java index b4987e9c..7924d431 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDao.java @@ -40,13 +40,17 @@ package org.onap.portal.dao.ep; +import java.util.List; import org.onap.portal.domain.db.ep.EpUserRolesRequest; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository @Transactional public interface EpUserRolesRequestDao extends JpaRepository { - + @Query + List userAppRolesRequestList(final @Param("userId") Long userId, final @Param("appId") Long appId); } diff --git a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDetDao.java b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDetDao.java index 35893193..cfc97baa 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDetDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpUserRolesRequestDetDao.java @@ -40,8 +40,11 @@ package org.onap.portal.dao.ep; +import java.util.List; import org.onap.portal.domain.db.ep.EpUserRolesRequestDet; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -49,4 +52,7 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public interface EpUserRolesRequestDetDao extends JpaRepository { + @Query + List appRolesRequestDetailList(final @Param("reqId") Long reqId); + } diff --git a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java index 01bcdfe5..a87f31cc 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java @@ -52,9 +52,22 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public interface FnRoleDao extends JpaRepository { - @Query - List retrieveAppRoleByAppRoleIdAndByAppId(final @Param("appId") Long appId, - final @Param("appRoleId") Long appRoleId); + @Query + List retrieveAppRoleByAppRoleIdAndByAppId(final @Param("appId") Long appId, + final @Param("appRoleId") Long appRoleId); - List getUserRoleOnUserIdAndAppId(final @Param("userId") Long userId, final @Param("appId") Long appId); + @Query + List getUserRoleOnUserIdAndAppId(final @Param("userId") Long userId, final @Param("appId") Long appId); + + @Query + List retrieveAppRoleByRoleIdWhereAppIdIsNull(final @Param("roleId") Long roleId); + + @Query + List retrieveAppRolesWhereAppIdIsNull(); + + @Query + List retrieveAppRolesByAppId(final @Param("appId") Long id); + + @Query + List retrieveAppRolesByRoleNameAndByAppId(final @Param("roleName") String roleName, final @Param("appId") Long appId); } diff --git a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java index 9c0a6fef..efb56b29 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java @@ -62,4 +62,7 @@ public interface FnUserRoleDao extends JpaRepository { @Query List getUserRolesForRoleIdAndAppId(final @Param("roleId") Long roleId, final @Param("appId") Long appId); + + @Query + List retrieveByAppIdAndUserId(final @Param("appId") Long appId, final @Param("userId") String userId); } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpAppFunction.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpAppFunction.java index d37c71ec..533309df 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpAppFunction.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpAppFunction.java @@ -51,6 +51,8 @@ import javax.persistence.IdClass; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.Valid; @@ -64,6 +66,7 @@ import lombok.Setter; import org.hibernate.validator.constraints.SafeHtml; import org.onap.portal.domain.db.ep.EpAppFunction.EpAppFunctionId; import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.dto.DomainVo; /* CREATE TABLE `ep_app_function` ( @@ -76,6 +79,20 @@ CREATE TABLE `ep_app_function` ( ) */ +@NamedQueries({ + @NamedQuery( + name = "EpAppFunction.getAppRoleFunctionList", + query = "from\n" + + " EpAppRoleFunction rf,\n" + + " EpAppFunction f\n" + + " where\n" + + " rf.fnRole.roleId = :roleId\n" + + " and rf.appId.appId = :appId\n" + + " and rf.appId.appId = f.appId.appId\n" + + " and rf.epAppFunction.functionCd = f.functionCd" + ) +}) + @Table(name = "ep_app_function", indexes = {@Index(name = "fk_ep_app_function_app_id", columnList = "app_id")}) @Getter @@ -84,7 +101,7 @@ CREATE TABLE `ep_app_function` ( @IdClass(EpAppFunctionId.class) @NoArgsConstructor @AllArgsConstructor -public class EpAppFunction implements Serializable{ +public class EpAppFunction extends DomainVo implements Serializable{ @Id @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "app_id") @@ -101,6 +118,14 @@ public class EpAppFunction implements Serializable{ @NotNull @SafeHtml private String functionName; + + private Long roleId; + private String type; + @SafeHtml + private String action; + @SafeHtml + private String editUrl; + @OneToMany( targetEntity = EpAppRoleFunction.class, mappedBy = "epAppFunction", @@ -109,6 +134,17 @@ public class EpAppFunction implements Serializable{ ) private Set epAppRoleFunctions; + public EpAppFunction(Long id, String code, String name, FnApp appId, String type, String action,String editUrl) { + super(); + this.id = id; + this.functionCd = code; + this.functionName = name; + this.appId = appId; + this.type = type; + this.action = action; + this.editUrl = editUrl; + } + @Getter @Setter @EqualsAndHashCode diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequest.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequest.java index 387f038d..752e47aa 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequest.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequest.java @@ -52,6 +52,8 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.Valid; @@ -84,6 +86,13 @@ CREATE TABLE `ep_user_roles_request` ( ) */ +@NamedQueries({ + @NamedQuery( + name = "EpUserRolesRequest.userAppRolesRequestList", + query = "FROM EpUserRolesRequest where userId.userId =:userId and appId.appId =:appId and requestStatus = 'P'" + ) +}) + @Table(name = "ep_user_roles_request") @NoArgsConstructor @AllArgsConstructor diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequestDet.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequestDet.java index 76044530..5338754b 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequestDet.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequestDet.java @@ -51,6 +51,8 @@ import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.Valid; @@ -78,6 +80,13 @@ CREATE TABLE `ep_user_roles_request_det` ( ) */ +@NamedQueries({ + @NamedQuery( + name = "EpUserRolesRequestDet.appRolesRequestDetailList", + query = "FROM EpUserRolesRequestDet where reqId.reqId = :reqId" + ) +}) + @Table(name = "ep_user_roles_request_det", indexes = { @Index(name = "fk_user_roles_req_fn_req_id", columnList = "req_id"), @Index(name = "fk_user_roles_req_fn_role_id", columnList = "requested_role_id") diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java index 275ce1e3..80617ba9 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java @@ -44,11 +44,13 @@ import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.IdClass; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -85,46 +87,44 @@ CREATE TABLE `fn_role` ( */ @NamedQueries({ - @NamedQuery( - name = "FnRole.retrieveAppRolesByRoleNameAndByAppId", - query = "FROM FnRole where role_name =:roleName and app_id =:appId"), - @NamedQuery( - name = "FnRole.retrieveAppRolesByAppId", - query = "FROM FnRole where app_id =:appId"), - @NamedQuery( - name = "FnRole.retrieveAppRolesWhereAppIdIsNull", - query = "FROM FnRole where app_id is null"), - @NamedQuery( - name = "FnRole.retrieveAppRoleByRoleIdWhereAppIdIsNull", - query = "FROM FnRole where role_id =:roleId and app_id is null"), - @NamedQuery( - name = "FnRole.retrieveAppRoleByAppRoleIdAndByAppId", - query = "FROM FnRole where appRoleId =:appRoleId and appId =:appId"), - @NamedQuery( - name = "FnRole.retrieveAppRoleByRoleIdAndAppId", - query = "FROM FnRole where role_id =:roleId and app_id =:appId"), - @NamedQuery( - name = "FnRole.retrieveAppRolesByRoleNameAndWhereAppIdIsNull", - query = "FROM FnRole where role_name =:roleName and app_id is null"), - @NamedQuery( - name = "FnRole.retrieveActiveRolesOfApplication", - query = "from FnRole where active_yn = 'Y' and app_id=:appId"), - @NamedQuery(name = "FnRole.retrieveRoleToUpdateInExternalAuthSystem", - query = "FROM FnRole where role_name =:roleName and app_id =:appId"), - @NamedQuery( - name = "FnRole.getUserRoleOnUserIdAndAppId", - query = " FROM" - + " FnRole fr,\n" - + " FnUserRole fur\n" - + " WHERE\n" - + " fr.roleId = fur.roleId\n" - + " AND fur.userId = :userId" - + " AND fur.appId = :appId\n" - + " AND fr.activeYn = 'y'") - }) + @NamedQuery( + name = "FnRole.retrieveAppRolesByRoleNameAndByAppId", + query = "FROM FnRole where roleName =:roleName and appId =:appId"), + @NamedQuery( + name = "FnRole.retrieveAppRolesByAppId", + query = "FROM FnRole where appId =:appId"), + @NamedQuery( + name = "FnRole.retrieveAppRolesWhereAppIdIsNull", + query = "FROM FnRole where appId is null"), + @NamedQuery( + name = "FnRole.retrieveAppRoleByRoleIdWhereAppIdIsNull", + query = "FROM FnRole where roleId =:roleId and appId is null"), + @NamedQuery( + name = "FnRole.retrieveAppRoleByAppRoleIdAndByAppId", + query = "FROM FnRole where appRoleId =:appRoleId and appId =:appId"), + @NamedQuery( + name = "FnRole.retrieveAppRoleByRoleIdAndAppId", + query = "FROM FnRole where roleId =:roleId and appId =:appId"), + @NamedQuery( + name = "FnRole.retrieveAppRolesByRoleNameAndWhereAppIdIsNull", + query = "FROM FnRole where roleName =:roleName and appId is null"), + @NamedQuery( + name = "FnRole.retrieveActiveRolesOfApplication", + query = "from FnRole where active_yn = 'Y' and appId=:appId"), + @NamedQuery( + name = "FnRole.getUserRoleOnUserIdAndAppId", + query = " FROM" + + " FnRole fr,\n" + + " FnUserRole fur\n" + + " WHERE\n" + + " fr.roleId = fur.roleId\n" + + " AND fur.userId = :userId" + + " AND fur.appId = :appId\n" + + " AND fr.activeYn = 'y'") +}) @Table(name = "fn_role", indexes = { - @Index(name = "fn_role_name_app_id_idx", columnList = "role_name, app_id", unique = true) + @Index(name = "fn_role_name_app_id_idx", columnList = "role_name, app_id", unique = true) }) @NoArgsConstructor @AllArgsConstructor @@ -133,98 +133,114 @@ CREATE TABLE `fn_role` ( @Entity public class FnRole extends DomainVo implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "role_id", length = 11, nullable = false) - @Digits(integer = 11, fraction = 0) - private Long roleId; - @Column(name = "role_name", length = 300, nullable = false) - @Size(max = 300) - @NotNull - @SafeHtml - private String roleName; - @Column(name = "active_yn", length = 1, columnDefinition = "character varying(1) default 'y'", nullable = false) - @NotNull - private Boolean activeYn; - @Column(name = "priority", length = 4, columnDefinition = "decimal(4,0) DEFAULT NULL") - @Digits(integer = 4, fraction = 0) - private Long priority; - @Column(name = "app_Id", length = 11, columnDefinition = "int(11) default null") - @Digits(integer = 11, fraction = 0) - private Long appId; - @Column(name = "app_role_id", length = 11, columnDefinition = "int(11) default null") - @Digits(integer = 11, fraction = 0) - private Long appRoleId; - @OneToMany( - targetEntity = FnRoleFunction.class, - mappedBy = "roleId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnRoleFunctions; - @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinTable( - name = "fn_user_pseudo_role", - joinColumns = {@JoinColumn(name = "pseudo_role_Id", referencedColumnName = "role_id")}, - inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")}, - indexes = { - @Index(name = "fk_pseudo_role_user_id", columnList = "user_id") - } - ) - private Set fnUsers; - @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinTable( - name = "fn_role_composite", - joinColumns = {@JoinColumn(name = "parent_role_id", referencedColumnName = "role_id")}, - inverseJoinColumns = {@JoinColumn(name = "child_role_id", referencedColumnName = "role_id")}, - indexes = { - @Index(name = "fk_fn_role_composite_child", columnList = "child_role_id") - } - ) - private Set fnRoles; - @ManyToMany(cascade = CascadeType.ALL, - fetch = FetchType.LAZY) - private Set fnRoleList; - @OneToMany( - targetEntity = EpRoleNotification.class, - mappedBy = "notificationID", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epRoleNotifications; - @OneToMany( - targetEntity = FnMenuFunctionalRoles.class, - mappedBy = "roleId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnMenuFunctionalRoles; - @OneToMany( - targetEntity = EpWidgetCatalogRole.class, - mappedBy = "roleId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epWidgetCatalogRoles; - @OneToMany( - targetEntity = EpAppRoleFunction.class, - mappedBy = "fnRole", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epAppRoleFunctions; - @OneToMany( - targetEntity = EpUserRolesRequestDet.class, - mappedBy = "requestedRoleId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epUserRolesRequestDets; - @OneToMany( - targetEntity = FnUserRole.class, - mappedBy = "roleId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnUserRoles; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "role_id", length = 11, nullable = false) + @Digits(integer = 11, fraction = 0) + private Long roleId; + @Column(name = "role_name", length = 300, nullable = false) + @Size(max = 300) + @NotNull + @SafeHtml + private String roleName; + @Column(name = "active_yn", length = 1, columnDefinition = "character varying(1) default 'y'", nullable = false) + @NotNull + private Boolean activeYn; + @Column(name = "priority", length = 4, columnDefinition = "decimal(4,0) DEFAULT NULL") + @Digits(integer = 4, fraction = 0) + private Integer priority; + @Column(name = "app_Id", length = 11, columnDefinition = "int(11) default null") + @Digits(integer = 11, fraction = 0) + private Long appId; + @Column(name = "app_role_id", length = 11, columnDefinition = "int(11) default null") + @Digits(integer = 11, fraction = 0) + private Long appRoleId; + @OneToMany( + targetEntity = FnRoleFunction.class, + mappedBy = "roleId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnRoleFunctions; + @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinTable( + name = "fn_user_pseudo_role", + joinColumns = {@JoinColumn(name = "pseudo_role_Id", referencedColumnName = "role_id")}, + inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")}, + indexes = { + @Index(name = "fk_pseudo_role_user_id", columnList = "user_id") + } + ) + private Set fnUsers; + @OneToMany( + targetEntity = FnRoleComposite.class, + mappedBy = "childRoles", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set childRoles; + @OneToMany( + targetEntity = FnRoleComposite.class, + mappedBy = "parentRoles", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set parentRoles; + @ManyToMany(cascade = CascadeType.ALL, + fetch = FetchType.LAZY) + private Set roleFunctions; + @OneToMany( + targetEntity = EpRoleNotification.class, + mappedBy = "notificationID", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epRoleNotifications; + @OneToMany( + targetEntity = FnMenuFunctionalRoles.class, + mappedBy = "roleId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnMenuFunctionalRoles; + @OneToMany( + targetEntity = EpWidgetCatalogRole.class, + mappedBy = "roleId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epWidgetCatalogRoles; + @OneToMany( + targetEntity = EpAppRoleFunction.class, + mappedBy = "fnRole", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epAppRoleFunctions; + @OneToMany( + targetEntity = EpUserRolesRequestDet.class, + mappedBy = "requestedRoleId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epUserRolesRequestDets; + @OneToMany( + targetEntity = FnUserRole.class, + mappedBy = "roleId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnUserRoles; + + public FnRole(Long roleId, String roleName, Boolean activeYn, Integer priority, + Set fnRoleFunctions, Set childRoles, + Set parentRoles) { + this.roleId = roleId; + this.roleName = roleName; + this.activeYn = activeYn; + this.priority = priority; + this.fnRoleFunctions = fnRoleFunctions; + this.childRoles = childRoles; + this.parentRoles = parentRoles; + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRoleComposite.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRoleComposite.java new file mode 100644 index 00000000..42a24b22 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRoleComposite.java @@ -0,0 +1,95 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.domain.db.fn; + +import java.io.Serializable; +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.Index; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.validation.Valid; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.onap.portal.domain.db.fn.FnRoleComposite.FnRoleCompositeId; + +@Table(name = "fn_role_composite", indexes = { + @Index(name = "fk_fn_role_composite_child", columnList = "child_role_id") +}) +@Getter +@Setter +@Entity +@NoArgsConstructor +@AllArgsConstructor +@IdClass(FnRoleCompositeId.class) +public class FnRoleComposite implements Serializable{ + + @Id + @Valid + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "parent_role_id") + private FnRole parentRoles; + @Id + @Valid + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "child_role_id") + private FnRole childRoles; + + @Getter + @Setter + @NoArgsConstructor + @EqualsAndHashCode + @AllArgsConstructor + public class FnRoleCompositeId implements Serializable { + + @Valid + private FnRole parentRoles; + @Valid + private FnRole childRoles; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java index 315f911a..dc01f388 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java @@ -63,7 +63,6 @@ import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; @@ -85,6 +84,9 @@ import org.onap.portal.domain.db.ep.EpUserNotification; import org.onap.portal.domain.db.ep.EpUserRolesRequest; import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter; import org.onap.portal.domain.dto.DomainVo; +import org.onap.portalsdk.core.domain.App; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.domain.UserApp; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; @@ -155,31 +157,31 @@ CREATE TABLE `fn_user` ( */ @NamedQueries({ - @NamedQuery( - name = "FnUser.getUserWithOrgUserId", - query = "FROM FnUser WHERE orgUserId = :orgId"), - @NamedQuery( - name = "FnUser.getActiveUsers", - query = "FROM FnUser WHERE activeYn = 'Y'"), - @NamedQuery( - name = "FnUser.getUsersByOrgIds", - query = "FROM FnUser WHERE orgUserId IN :orgIds" - ) + @NamedQuery( + name = "FnUser.getUserWithOrgUserId", + query = "FROM FnUser WHERE orgUserId = :orgId"), + @NamedQuery( + name = "FnUser.getActiveUsers", + query = "FROM FnUser WHERE activeYn = 'Y'"), + @NamedQuery( + name = "FnUser.getUsersByOrgIds", + query = "FROM FnUser WHERE orgUserId IN :orgIds" + ) }) @Table(name = "fn_user", indexes = { - @Index(name = "fn_user_address_id", columnList = "address_id"), - @Index(name = "fn_user_alert_method_cd", columnList = "alert_method_cd"), - @Index(name = "fn_user_org_id", columnList = "org_id"), - @Index(name = "fk_fn_user_ref_197_fn_user", columnList = "manager_id"), - @Index(name = "fk_fn_user_ref_198_fn_user", columnList = "created_id"), - @Index(name = "fk_fn_user_ref_199_fn_user", columnList = "modified_id"), - @Index(name = "fk_timezone", columnList = "timezone") + @Index(name = "fn_user_address_id", columnList = "address_id"), + @Index(name = "fn_user_alert_method_cd", columnList = "alert_method_cd"), + @Index(name = "fn_user_org_id", columnList = "org_id"), + @Index(name = "fk_fn_user_ref_197_fn_user", columnList = "manager_id"), + @Index(name = "fk_fn_user_ref_198_fn_user", columnList = "created_id"), + @Index(name = "fk_fn_user_ref_199_fn_user", columnList = "modified_id"), + @Index(name = "fk_timezone", columnList = "timezone") }, - uniqueConstraints = { - @UniqueConstraint(name = "fn_user_hrid", columnNames = "hrid"), - @UniqueConstraint(name = "fn_user_login_id", columnNames = "login_id") + uniqueConstraints = { + @UniqueConstraint(name = "fn_user_hrid", columnNames = "hrid"), + @UniqueConstraint(name = "fn_user_login_id", columnNames = "login_id") - }) + }) @Getter @Setter @@ -190,334 +192,361 @@ CREATE TABLE `fn_user` ( @DynamicUpdate public class FnUser extends DomainVo implements UserDetails, Serializable { - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUser.class); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUser.class); + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id", nullable = false) + private Long userId; + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "org_id") + private FnOrg orgId; + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "manager_id") + private FnUser managerId; + @Column(name = "first_name", length = 50) + @Size(max = 50) + @SafeHtml + private String firstName; + @Column(name = "middle_name", length = 50) + @Size(max = 50) + @SafeHtml + private String middleName; + @Column(name = "last_name", length = 50) + @Size(max = 50) + @SafeHtml + private String lastName; + @Column(name = "phone", length = 25) + @Size(max = 25) + @SafeHtml + private String phone; + @Column(name = "fax", length = 25) + @Size(max = 25) + @SafeHtml + private String fax; + @Column(name = "cellular", length = 25) + @Size(max = 25) + @SafeHtml + private String cellular; + @Column(name = "email", length = 50) + @Size(max = 50) + @Email + @SafeHtml + private String email; + @Column(name = "address_id") + @Digits(integer = 11, fraction = 0) + private Long addressId; + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "alert_method_cd") + private FnLuAlertMethod alertMethodCd; + @Column(name = "hrid", length = 20) + @Size(max = 20) + @SafeHtml + private String hrid; + @Column(name = "org_user_id", length = 20) + @Size(max = 20) + @SafeHtml + private String orgUserId; + @Column(name = "org_code", length = 30) + @Size(max = 30) + @SafeHtml + private String org_code; + @Column(name = "login_id", length = 25) + @Size(max = 25) + @SafeHtml + private String loginId; + @Column(name = "login_pwd", length = 100) + @Size(max = 100) + @SafeHtml + private String loginPwd; + @Column(name = "last_login_date", nullable = false, columnDefinition = "datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()") + @PastOrPresent + protected LocalDateTime lastLoginDate; + @Column(name = "active_yn", nullable = false) + private Boolean activeYn; + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "created_id") + private FnUser createdId; + @Column(name = "created_date", columnDefinition = "datetime DEFAULT current_timestamp()", nullable = false) + @PastOrPresent + protected LocalDateTime createdDate; + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "modified_id") + private FnUser modifiedId; + @Column(name = "modified_date", nullable = false, columnDefinition = "datetime default now()") + @PastOrPresent + protected LocalDateTime modifiedDate; + @Column(name = "is_internal_yn", nullable = false, columnDefinition = "bit DEFAULT 0") + private Boolean isInternalYn; + @Column(name = "is_system_user", nullable = false, columnDefinition = "bit DEFAULT 0") + private Boolean isSystemUser; + @Column(name = "address_line_1", length = 100) + @Size(max = 100) + @SafeHtml + private String addressLine1; + @Column(name = "address_line_2", length = 100) + @Size(max = 100) + @SafeHtml + private String addressLine2; + @Column(name = "city", length = 50) + @Size(max = 50) + @SafeHtml + private String city; + @Column(name = "state_cd", length = 3) + @Size(max = 3) + @SafeHtml + private String stateCd; + @Column(name = "zip_code", length = 11) + @Size(max = 11) + @SafeHtml + private String zipCode; + @Column(name = "country_cd", length = 3) + @Size(max = 3) + @SafeHtml + private String countryCd; + @Column(name = "location_clli", length = 8) + @Size(max = 8) + @SafeHtml + private String locationClli; + @Column(name = "org_manager_userid", length = 20) + @Size(max = 20) + @SafeHtml + private String orgManagerUserId; + @Column(name = "company", length = 100) + @Size(max = 100) + @SafeHtml + private String company; + @Column(name = "department_name", length = 200) + @Size(max = 200) + @SafeHtml + private String departmentName; + @Column(name = "job_title", length = 100) + @Size(max = 100) + @SafeHtml + private String jobTitle; + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "timezone") + private FnLuTimezone timezone; + @Column(name = "department", length = 25) + @Size(max = 25) + @SafeHtml + private String department; + @Column(name = "business_unit", length = 25) + @Size(max = 25) + @SafeHtml + private String businessUnit; + @Column(name = "business_unit_name", length = 100) + @Size(max = 100) + @SafeHtml + private String businessUnitName; + @Column(name = "cost_center", length = 25) + @Size(max = 25) + @SafeHtml + private String cost_center; + @Column(name = "fin_loc_code", length = 10) + @Size(max = 10) + @SafeHtml + private String finLocCode; + @Column(name = "silo_status", length = 10) + @Size(max = 10) + @SafeHtml + private String siloStatus; + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "language_id", nullable = false, columnDefinition = "bigint DEFAULT 1") + @NotNull(message = "languageId must not be null") + private FnLanguage languageId; + @Column(name = "is_guest", nullable = false, columnDefinition = "bit DEFAULT 0") + @NotNull(message = "guest must not be null") + private Boolean guest; + @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fnUserList") + private Set crReportFileHistorie; + @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + private Set fnRoles; + @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set fnRoleList; + @OneToMany( + targetEntity = FnAuditLog.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnAuditLogs; + @OneToMany( + targetEntity = FnUser.class, + mappedBy = "createdId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnUsersCreatedId; + @OneToMany( + targetEntity = FnUser.class, + mappedBy = "managerId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnUsersManagerId; + @OneToMany( + targetEntity = FnUser.class, + mappedBy = "modifiedId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set fnUsersModifiedId; + @OneToMany( + targetEntity = EpUserRolesRequest.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epUserRolesRequests; + @OneToMany( + targetEntity = FnPersUserAppSel.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set persUserAppSels; + @OneToMany( + targetEntity = EpWidgetCatalogParameter.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epWidgetCatalogParameters; + @OneToMany( + targetEntity = EpPersUserWidgetPlacement.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epPersUserWidgetPlacements; + @OneToMany( + targetEntity = EpPersUserWidgetSel.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epPersUserWidgetSels; + @OneToMany( + targetEntity = FnUserRole.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set userApps; + @OneToMany( + targetEntity = EpUserNotification.class, + mappedBy = "userId", + cascade = CascadeType.ALL, + fetch = FetchType.LAZY + ) + private Set epUserNotifications; + + @Override + public Collection getAuthorities() { + return fnRoles + .stream() + .map(fnRole -> new SimpleGrantedAuthority("ROLE_" + fnRole.getRoleName())) + .collect(Collectors.toList()); + } + + @Override + public String getPassword() { + return this.getLoginPwd(); + } + + @Override + public String getUsername() { + return this.getLoginId(); + } - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "user_id", nullable = false) - private Long userId; - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinColumn(name = "org_id") - private FnOrg orgId; - @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinColumn(name = "manager_id") - private FnUser managerId; - @Column(name = "first_name", length = 50) - @Size(max = 50) - @SafeHtml - private String firstName; - @Column(name = "middle_name", length = 50) - @Size(max = 50) - @SafeHtml - private String middleName; - @Column(name = "last_name", length = 50) - @Size(max = 50) - @SafeHtml - private String lastName; - @Column(name = "phone", length = 25) - @Size(max = 25) - @SafeHtml - private String phone; - @Column(name = "fax", length = 25) - @Size(max = 25) - @SafeHtml - private String fax; - @Column(name = "cellular", length = 25) - @Size(max = 25) - @SafeHtml - private String cellular; - @Column(name = "email", length = 50) - @Size(max = 50) - @Email - @SafeHtml - private String email; - @Column(name = "address_id") - @Digits(integer = 11, fraction = 0) - private Long addressId; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "alert_method_cd") - private FnLuAlertMethod alertMethodCd; - @Column(name = "hrid", length = 20) - @Size(max = 20) - @SafeHtml - private String hrid; - @Column(name = "org_user_id", length = 20) - @Size(max = 20) - @SafeHtml - private String orgUserId; - @Column(name = "org_code", length = 30) - @Size(max = 30) - @SafeHtml - private String org_code; - @Column(name = "login_id", length = 25) - @Size(max = 25) - @SafeHtml - private String loginId; - @Column(name = "login_pwd", length = 100) - @Size(max = 100) - @SafeHtml - private String loginPwd; - @Column(name = "last_login_date", nullable = false, columnDefinition = "datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()") - @PastOrPresent - protected LocalDateTime lastLoginDate; - @Column(name = "active_yn", nullable = false) - private Boolean activeYn; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "created_id") - private FnUser createdId; - @Column(name = "created_date", columnDefinition = "datetime DEFAULT current_timestamp()", nullable = false) - @PastOrPresent - protected LocalDateTime createdDate; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "modified_id") - private FnUser modifiedId; - @Column(name = "modified_date", nullable = false, columnDefinition = "datetime default now()") - @PastOrPresent - protected LocalDateTime modifiedDate; - @Column(name = "is_internal_yn", nullable = false, columnDefinition = "bit DEFAULT 0") - private Boolean isInternalYn; - @Column(name = "address_line_1", length = 100) - @Size(max = 100) - @SafeHtml - private String addressLine1; - @Column(name = "address_line_2", length = 100) - @Size(max = 100) - @SafeHtml - private String addressLine2; - @Column(name = "city", length = 50) - @Size(max = 50) - @SafeHtml - private String city; - @Column(name = "state_cd", length = 3) - @Size(max = 3) - @SafeHtml - private String stateCd; - @Column(name = "zip_code", length = 11) - @Size(max = 11) - @SafeHtml - private String zipCode; - @Column(name = "country_cd", length = 3) - @Size(max = 3) - @SafeHtml - private String countryCd; - @Column(name = "location_clli", length = 8) - @Size(max = 8) - @SafeHtml - private String locationClli; - @Column(name = "org_manager_userid", length = 20) - @Size(max = 20) - @SafeHtml - private String orgManagerUserId; - @Column(name = "company", length = 100) - @Size(max = 100) - @SafeHtml - private String company; - @Column(name = "department_name", length = 200) - @Size(max = 200) - @SafeHtml - private String departmentName; - @Column(name = "job_title", length = 100) - @Size(max = 100) - @SafeHtml - private String jobTitle; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "timezone") - private FnLuTimezone timezone; - @Column(name = "department", length = 25) - @Size(max = 25) - @SafeHtml - private String department; - @Column(name = "business_unit", length = 25) - @Size(max = 25) - @SafeHtml - private String businessUnit; - @Column(name = "business_unit_name", length = 100) - @Size(max = 100) - @SafeHtml - private String businessUnitName; - @Column(name = "cost_center", length = 25) - @Size(max = 25) - @SafeHtml - private String cost_center; - @Column(name = "fin_loc_code", length = 10) - @Size(max = 10) - @SafeHtml - private String finLocCode; - @Column(name = "silo_status", length = 10) - @Size(max = 10) - @SafeHtml - private String siloStatus; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "language_id", nullable = false, columnDefinition = "bigint DEFAULT 1") - @NotNull(message = "languageId must not be null") - private FnLanguage languageId; - @Column(name = "is_guest", nullable = false, columnDefinition = "bit DEFAULT 0") - @NotNull(message = "guest must not be null") - private Boolean guest; - @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fnUserList") - private Set crReportFileHistorie; - @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set fnRoles; - @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - private Set fnRoleList; - @OneToMany( - targetEntity = FnAuditLog.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnAuditLogs; - @OneToMany( - targetEntity = FnUser.class, - mappedBy = "createdId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnUsersCreatedId; - @OneToMany( - targetEntity = FnUser.class, - mappedBy = "managerId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnUsersManagerId; - @OneToMany( - targetEntity = FnUser.class, - mappedBy = "modifiedId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnUsersModifiedId; - @OneToMany( - targetEntity = EpUserRolesRequest.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epUserRolesRequests; - @OneToMany( - targetEntity = FnPersUserAppSel.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set persUserAppSels; - @OneToMany( - targetEntity = EpWidgetCatalogParameter.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epWidgetCatalogParameters; - @OneToMany( - targetEntity = EpPersUserWidgetPlacement.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epPersUserWidgetPlacements; - @OneToMany( - targetEntity = EpPersUserWidgetSel.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epPersUserWidgetSels; - @OneToMany( - targetEntity = FnUserRole.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set fnUserRoles; - @OneToMany( - targetEntity = EpUserNotification.class, - mappedBy = "userId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY - ) - private Set epUserNotifications; + @Override + public boolean isAccountNonExpired() { + return true; + } - @Override - public Collection getAuthorities() { - return fnRoles - .stream() - .map(fnRole -> new SimpleGrantedAuthority("ROLE_" + fnRole.getRoleName())) - .collect(Collectors.toList()); - } + @Override + public boolean isAccountNonLocked() { + return true; + } - @Override - public String getPassword() { - return this.getLoginPwd(); - } + @Override + public boolean isCredentialsNonExpired() { + return true; + } - @Override - public String getUsername() { - return this.getLoginId(); - } + @Override + public boolean isEnabled() { + return true; + } - @Override - public boolean isAccountNonExpired() { - return true; - } + public String getFullName() { + return this.firstName + " " + this.lastName; + } - @Override - public boolean isAccountNonLocked() { - return true; - } + public SortedSet getAppEPRoles(FnApp app) { - @Override - public boolean isCredentialsNonExpired() { - return true; - } + logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - app = {}", app.getAppName()); - @Override - public boolean isEnabled() { - return true; - } + SortedSet roles = new TreeSet<>(); + Set userAppRoles = getUserApps(); - public String getFullName() { - return this.firstName + " " + this.lastName; - } + logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - userApps = {} ", userAppRoles.size()); - public SortedSet getAppEPRoles(FnApp app) { + Iterator userAppRolesIterator = userAppRoles.iterator(); - logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - app = {}", app.getAppName()); + FnUserRole userAppRole; + // getting default app + while (userAppRolesIterator.hasNext()) { + FnUserRole tempUserApp = userAppRolesIterator.next(); + if (tempUserApp.getAppId().getId().equals(app.getId())) { - SortedSet roles = new TreeSet<>(); - Set userAppRoles = getFnUserRoles(); + logger.debug(EELFLoggerDelegate.debugLogger, + "In EPUser.getAppEPRoles() - for user {}, found application {}", this.getFullName(), + app.getAppName()); - logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - userApps = {} ", userAppRoles.size()); + userAppRole = tempUserApp; - Iterator userAppRolesIterator = userAppRoles.iterator(); + FnRole role = userAppRole.getRoleId(); + if (role.getActiveYn()) { + logger.debug(EELFLoggerDelegate.debugLogger, + "In EPUser.getAppEPRoles() - Role {} is active - adding for user {} and app {}", + role.getRoleName(), this.getFullName(), app.getAppName()); + roles.add(role); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, + "In EPUser.getAppEPRoles() - Role {} is NOT active - NOT adding for user {} and app {}", + role.getRoleName(), this.getFullName(), app.getAppName()); + } + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - roles = {}", roles.size()); - FnUserRole userAppRole; - // getting default app - while (userAppRolesIterator.hasNext()) { - FnUserRole tempUserApp = userAppRolesIterator.next(); - if (tempUserApp.getAppId().getId().equals(app.getId())) { + return roles; + } - logger.debug(EELFLoggerDelegate.debugLogger, - "In EPUser.getAppEPRoles() - for user {}, found application {}", this.getFullName(), - app.getAppName()); + public void setRoles(Set roles) { + FnApp app = new FnApp(); + app.setId(1L); + app.setAppName("Default"); + this.addAppRoles(app, roles); + } - userAppRole = tempUserApp; + private void addAppRoles(FnApp app, Set roles) { + if (roles != null) { + Set newUserApps = new HashSet<>(); + for (FnRole role : roles) { + FnUserRole userApp = new FnUserRole(); + userApp.setUserId(this); + userApp.setAppId(app); + userApp.setRoleId(role); + newUserApps.add(userApp); + } - FnRole role = userAppRole.getRoleId(); - if (role.getActiveYn()) { - logger.debug(EELFLoggerDelegate.debugLogger, - "In EPUser.getAppEPRoles() - Role {} is active - adding for user {} and app {}", - role.getRoleName(), this.getFullName(), app.getAppName()); - roles.add(role); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, - "In EPUser.getAppEPRoles() - Role {} is NOT active - NOT adding for user {} and app {}", - role.getRoleName(), this.getFullName(), app.getAppName()); - } - } - } - logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - roles = {}", roles.size()); + this.setUserApps(newUserApps); + } else { + this.userApps.clear(); + } - return roles; - } + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java index 06320c4c..f3fdec1e 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java @@ -144,7 +144,10 @@ CREATE TABLE `fn_user_role` ( + " FnUserRole userrole\n" + "WHERE\n" + " userrole.roleId.roleId = :roleId\n" - + " AND userrole.appId.appId = :appId" + + " AND userrole.appId.appId = :appId"), + @NamedQuery( + name = "FnUserRole.retrieveByAppIdAndUserId", + query = "from FnUserRole where appId.appId =:appId and userId.userId =:userId" ) }) diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java index 230da910..91ea87f2 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java @@ -65,6 +65,7 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DomainVo.class); private static final long serialVersionUID = 1L; protected Long id; @@ -75,7 +76,6 @@ public class DomainVo extends FusionVo implements Serializable, Cloneable, Compa protected Long rowNum; protected Serializable auditUserId; protected Set auditTrail = null; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DomainVo.class); public DomainVo(Long id) { this.id = id; diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java index 25cc66fa..84fa0fbd 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java @@ -41,62 +41,65 @@ package org.onap.portal.domain.dto.transport; import java.io.Serializable; -import java.util.Date; +import java.time.LocalDateTime; import java.util.SortedSet; import java.util.TreeSet; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.onap.portal.domain.db.ep.EpAppFunction; @Getter @Setter +@Builder @EqualsAndHashCode @NoArgsConstructor @AllArgsConstructor public class CentralV2Role implements Serializable, Comparable { - private static final long serialVersionUID = -4332644961113063714L; + private static final long serialVersionUID = -4332644961113063714L; - private Long id; - private Date created; - private Date modified; - private Long createdId; - private Long modifiedId; - private Long rowNum; - private String name; - private boolean active; - private Integer priority; - private SortedSet roleFunctions = new TreeSet<>(); - private SortedSet childRoles = new TreeSet<>(); - private SortedSet parentRoles = new TreeSet<>(); + private Long id; + private LocalDateTime created; + private LocalDateTime modified; + private Long createdId; + private Long modifiedId; + private Long rowNum; + private String name; + private boolean active; + private Integer priority; + private SortedSet roleFunctions = new TreeSet<>(); + private SortedSet childRoles = new TreeSet<>(); + private SortedSet parentRoles = new TreeSet<>(); - public CentralV2Role(Long id, String name) { - this.id = id; - this.name = name; - } + public CentralV2Role(Long id, String name) { + this.id = id; + this.name = name; + } - public void addRoleFunction(CentralV2RoleFunction roleFunction) { - this.roleFunctions.add(roleFunction); - } + public void addRoleFunction(EpAppFunction roleFunction) { + this.roleFunctions.add(roleFunction); + } - public void addChildRole(CentralV2Role role) { - this.childRoles.add(role); - } + public void addChildRole(CentralV2Role role) { + this.childRoles.add(role); + } - public void addParentRole(CentralV2Role role) { - this.parentRoles.add(role); - } + public void addParentRole(CentralV2Role role) { + this.parentRoles.add(role); + } - @Override - public int compareTo(Object obj) { - CentralV2Role other = (CentralV2Role) obj; + @Override + public int compareTo(Object obj) { + CentralV2Role other = (CentralV2Role) obj; - String c1 = getName(); - String c2 = other.getName(); + String c1 = getName(); + String c2 = other.getName(); - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EcompUserAppRoles.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EcompUserAppRoles.java index ebf8fe88..bb110ece 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EcompUserAppRoles.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EcompUserAppRoles.java @@ -61,5 +61,4 @@ public class EcompUserAppRoles implements Serializable { private Integer priority; private Long roleId; private String roleName; - } diff --git a/portal-BE/src/main/java/org/onap/portal/exception/SyncUserRolesException.java b/portal-BE/src/main/java/org/onap/portal/exception/SyncUserRolesException.java new file mode 100644 index 00000000..604689ae --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/exception/SyncUserRolesException.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.exception; + +public class SyncUserRolesException extends Exception{ + + public SyncUserRolesException(String msg) { + super(msg); + } + +} + diff --git a/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java index fa8ab5d5..b555e6ae 100644 --- a/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java +++ b/portal-BE/src/main/java/org/onap/portal/logging/aop/EPEELFLoggerAdvice.java @@ -49,8 +49,8 @@ import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.onap.portal.domain.db.fn.FnApp; import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.service.AppsCacheService; import org.onap.portal.service.fn.FnUserService; -import org.onap.portal.service.fn.old.AppsCacheService; import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portal.utils.EcompPortalUtils; import org.onap.portalsdk.core.exception.SessionExpiredException; diff --git a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java index c2d88bc1..74b3548a 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java @@ -40,112 +40,1169 @@ package org.onap.portal.service; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.stream.Collectors; import javax.persistence.EntityManager; +import javax.persistence.Query; +import org.apache.commons.lang.StringUtils; +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.portal.domain.db.ep.EpUserRolesRequest; +import org.onap.portal.domain.db.ep.EpUserRolesRequestDet; +import org.onap.portal.domain.db.fn.FnApp; import org.onap.portal.domain.db.fn.FnRole; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.db.fn.FnUserRole; +import org.onap.portal.domain.dto.transport.AppWithRolesForUser; +import org.onap.portal.domain.dto.transport.CentralV2Role; +import org.onap.portal.domain.dto.transport.EcompUserAppRoles; +import org.onap.portal.domain.dto.transport.ExternalAccessUser; +import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail; +import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator; +import org.onap.portal.domain.dto.transport.ExternalRoleDescription; +import org.onap.portal.domain.dto.transport.RemoteRoleV1; +import org.onap.portal.domain.dto.transport.RoleInAppForUser; +import org.onap.portal.domain.dto.transport.RolesInAppForUser; +import org.onap.portal.exception.SyncUserRolesException; import org.onap.portal.logging.format.EPAppMessagesEnum; import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.ep.EpUserRolesRequestDetService; +import org.onap.portal.service.ep.EpUserRolesRequestService; +import org.onap.portal.service.fn.FnAppService; +import org.onap.portal.service.fn.FnRoleService; import org.onap.portal.service.fn.FnUserRoleService; import org.onap.portal.service.fn.FnUserService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portal.utils.PortalConstants; +import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.restful.domain.EcompRole; +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.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; @Service @Transactional public class AdminRolesService { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); - - private final Long SYS_ADMIN_ROLE_ID = 1L; - private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; - private final Long ECOMP_APP_ID = 1L; - private final String ADMIN_ACCOUNT = "Is account admin for user {}"; - - private final EntityManager entityManager; - private final FnUserService fnUserService; - private final FnUserRoleService fnUserRoleService; - - @Autowired - public AdminRolesService(final EntityManager entityManager, - final FnUserService fnUserService, final FnUserRoleService fnUserRoleService) { - this.entityManager = entityManager; - this.fnUserService = fnUserService; - this.fnUserRoleService = fnUserRoleService; - } - - public boolean isSuperAdmin(final String orgUserId) { - boolean isSuperAdmin; - try { - isSuperAdmin = fnUserRoleService - .isSuperAdmin(orgUserId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID); - } catch (Exception e) { - logger.error("isSuperAdmin exception: " + e.toString()); - throw e; + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); + private static final Object syncRests = new Object(); + private RestTemplate template = new RestTemplate(); + + private final Long SYS_ADMIN_ROLE_ID = 1L; + private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private final Long ECOMP_APP_ID = 1L; + private final String ADMIN_ACCOUNT = "Is account admin for user {}"; + + private final AppsCacheService appsCacheService; + private final EntityManager entityManager; + private final FnUserService fnUserService; + private final FnRoleService fnRoleService; + private final FnAppService fnAppService; + private final FnUserRoleService fnUserRoleService; + private final EcompUserAppRolesService ecompUserAppRolesService; + private final ApplicationsRestClientService applicationsRestClientService; + private final EpUserRolesRequestDetService epUserRolesRequestDetService; + private final ExternalAccessRolesService externalAccessRolesService; + private final EpUserRolesRequestService epUserRolesRequestService; + + @Autowired + public AdminRolesService(AppsCacheService appsCacheService, + final EntityManager entityManager, + final FnUserService fnUserService, FnRoleService fnRoleService, + FnAppService fnAppService, + final FnUserRoleService fnUserRoleService, + EcompUserAppRolesService ecompUserAppRolesService, + ApplicationsRestClientService applicationsRestClientService, + EpUserRolesRequestDetService epUserRolesRequestDetService, + ExternalAccessRolesService externalAccessRolesService, + EpUserRolesRequestService epUserRolesRequestService) { + this.appsCacheService = appsCacheService; + this.entityManager = entityManager; + this.fnUserService = fnUserService; + this.fnRoleService = fnRoleService; + this.fnAppService = fnAppService; + this.fnUserRoleService = fnUserRoleService; + this.ecompUserAppRolesService = ecompUserAppRolesService; + this.applicationsRestClientService = applicationsRestClientService; + this.epUserRolesRequestDetService = epUserRolesRequestDetService; + this.externalAccessRolesService = externalAccessRolesService; + this.epUserRolesRequestService = epUserRolesRequestService; + } + + public boolean isSuperAdmin(final String orgUserId) { + boolean isSuperAdmin; + try { + isSuperAdmin = fnUserRoleService + .isSuperAdmin(orgUserId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID); + } catch (Exception e) { + logger.error("isSuperAdmin exception: " + e.toString()); + throw e; + } + logger.info("isSuperAdmin " + isSuperAdmin); + return isSuperAdmin; + } + + public boolean isAccountAdmin(FnUser user) { + try { + final Map userParams = new HashMap<>(); + userParams.put("userId", user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); + List userAdminApps = getAdminAppsForTheUser(user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, + "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", + user.getOrgUserId(), userAdminApps.size()); + + if (user.getId() != null) { + for (FnUserRole userApp : user.getUserApps()) { + if (userApp.getRoleId().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.getRoleId().getId()); + return true; + } + } + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isAccountAdmin operation", + e); + } + return false; + } + + public boolean isUser(FnUser user) { + try { + FnUser currentUser = fnUserService.getUser(user.getId()).orElseThrow(Exception::new); + if (currentUser != null && currentUser.getId() != null) { + for (FnUserRole userApp : currentUser.getUserApps()) { + if (!userApp.getAppId().getId().equals(ECOMP_APP_ID)) { + FnRole role = userApp.getRoleId(); + if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId() + .equals(ACCOUNT_ADMIN_ROLE_ID)) { + if (role.getActiveYn()) { + return true; + } + } + } + } + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", + e); + } + return false; + } + + public boolean isRoleAdmin(FnUser user) { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access"); + List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, + "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser); + Set getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser); + Set getRoleFuncListOfPortalSet1 = new HashSet<>(); + Set roleFunSet; + roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")) + .collect(Collectors.toSet()); + if (!roleFunSet.isEmpty()) { + for (String roleFunction : roleFunSet) { + String type = externalAccessRolesService.getFunctionCodeType(roleFunction); + getRoleFuncListOfPortalSet1.add(type); + } + } + + 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); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isRoleAdmin operation", + e); + } + return false; + } + + public boolean isAccountAdminOfApplication(FnUser user, FnApp app) { + boolean isApplicationAccountAdmin = false; + try { + logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); + List userAdminApps = getAdminAppsForTheUser(user.getId()); + if (!userAdminApps.isEmpty()) { + isApplicationAccountAdmin = userAdminApps.contains(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; + + } + + private List getAdminAppsForTheUser(final Long userId) { + String query = "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 and (fa.enabled = 'Y' || fa.app_id=1)"; + return entityManager.createQuery(query, Integer.class) + .setParameter("userId", userId).getResultList(); + } + + public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user, + AppWithRolesForUser newAppRolesForUser) { + boolean result = false; + boolean epRequestValue = false; + String userId = ""; + String reqMessage = ""; + if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) { + userId = newAppRolesForUser.getOrgUserId().trim(); + } + Long appId = newAppRolesForUser.getAppId(); + List roleInAppForUserList = newAppRolesForUser.getAppRoles(); + + if (userId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + try { + FnApp app = fnAppService.getById(appId); + + boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user, + app); + Set rolesGotDeletedFromApprover = new TreeSet<>(); + + boolean checkIfUserIsOnlyRoleAdmin = + isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin; + if (checkIfUserIsOnlyRoleAdmin) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (!roleInAppForUser.getIsApplied()) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.getRoleId()); + ecompRole.setName(roleInAppForUser.getRoleName()); + rolesGotDeletedFromApprover.add(ecompRole); + } + } + } + + applyChangesToUserAppRolesForMyLoginsRequest(user, appId); + + boolean systemUser = newAppRolesForUser.isSystemUser(); + + if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) + && systemUser) { + + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + List roleAppUserList = rolesInAppForUser.getRoles(); + Set rolesGotDeletedByApprover = new TreeSet<>(); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + // Apply changes in external Access system + + updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), + roleAppUserList, + epRequestValue, systemUser, rolesGotDeletedByApprover, false); + } + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, + "Portal", + systemUser, rolesGotDeletedByApprover, false); + + } else if (!app.getAuthCentral() && systemUser) { + throw new Exception("For non-centralized application we cannot add systemUser"); + } else { // if centralized app + if (app.getAuthCentral()) { + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + pushRemoteUser(roleInAppForUserList, userId, app, mapper, + applicationsRestClientService, false); + } + + Set userRolesInLocalApp = postUsersRolesToLocalApp( + roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, + appId, + userRolesInLocalApp); + List roleAppUserList = rolesInAppForUser.getRoles(); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), + roleAppUserList, + epRequestValue, false, rolesGotDeletedFromApprover, + checkIfUserIsOnlyRoleAdmin); + } + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, + epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover, + checkIfUserIsOnlyRoleAdmin); + } + // In case if portal is not centralized then follow existing approach + else if (!app.getAuthCentral() && app.getId() + .equals(PortalConstants.PORTAL_APP_ID)) { + Set userRolesInLocalApp = postUsersRolesToLocalApp( + roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, + appId, + userRolesInLocalApp); + Set rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, + epRequestValue, "Portal", false, rolesGotDeletedByApprover, false); + } else {// remote app + FnUser remoteAppUser; + if (!app.getAuthCentral() && !app.getId() + .equals(PortalConstants.PORTAL_APP_ID)) { + + remoteAppUser = checkIfRemoteUserExits(userId, app, + applicationsRestClientService); + + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId, app, + mapper, applicationsRestClientService); + } + Set userRolesInRemoteApp = postUsersRolesToRemoteApp( + roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate( + userId, appId, + userRolesInRemoteApp); + Set rolesGotDeletedByApprover = new TreeSet<>(); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, + epRequestValue, null, false, rolesGotDeletedByApprover, false); + + // If no roles remain, request app to set user inactive. + if (userRolesInRemoteApp.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", + app, + userId); + postUserToRemoteApp(userId, app, + applicationsRestClientService); + } + } + } + } + } catch (Exception e) { + String message = String.format( + "Failed to create user or update user roles for User %s, AppId %s", + userId, Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + result = false; + reqMessage = e.getMessage(); + } + } + //return result; + return new ExternalRequestFieldsValidator(result, reqMessage); + + } + + private void pushRemoteUser(List roleInAppForUserList, String userId, FnApp app, + ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed) + throws Exception { + pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper, + roleInAppForUserList, appRoleIdUsed); + } + + + private void postUserToRemoteApp(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + + getUser(userId, app, applicationsRestClientService); + + } + + private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService) + throws HTTPException { + return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true); + + } + + private void pushUserOnRemoteApp(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService, + ObjectMapper mapper, List roleInAppForUserList, boolean appRoleIdUsed) + throws Exception { + + FnUser client; + client = fnUserService.loadUserByUsername(userId); + + 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); + List userList = fnUserService.getUserWithOrgUserId(userId); + if (!userList.isEmpty()) { + logger.debug(EELFLoggerDelegate.debugLogger, + userList.get(0).getOrgUserId() + " User was found in Portal"); + client = userList.get(0); + client.setUserApps(Collections.EMPTY_SET); + client.setIsSystemUser(false); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal"); + throw new Exception(msg); + } + + } + + client.setLoginId(userId); + client.setActiveYn(true); + client.setOrgUserId(userId); + + roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false)); + SortedSet roles = new TreeSet<>(); + + List getAppRoles = externalAccessRolesService.getAppRoles(app.getId()); + List appList = new ArrayList<>(); + appList.add(app); + List roleList = new ArrayList<>(); + Map params = new HashMap<>(); + + List userRoles = new ArrayList<>(); + + for (RoleInAppForUser roleInappForUser : roleInAppForUserList) { + FnRole role = new FnRole(); + role.setId(roleInappForUser.getRoleId()); + role.setRoleName(roleInappForUser.getRoleName()); + userRoles.add(role); + } + + if (appRoleIdUsed) { + List userAppRoles = new ArrayList<>(); + for (FnRole role : userRoles) { + FnRole appRole = getAppRoles.stream() + .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny() + .orElse(null); + FnRole epRole = new FnRole(); + if (appRole != null) { + epRole.setId(appRole.getId()); + epRole.setRoleName(appRole.getRoleName()); + } + userAppRoles.add(epRole); + } + userRoles = new ArrayList<>(userAppRoles); + } + roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList); + + for (CentralV2Role epRole : roleList) { + Role role = new Role(); + FnRole appRole = getAppRoles.stream() + .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null); + if (appRole != null) { + role.setId(appRole.getAppRoleId()); + role.setName(epRole.getName()); + role.setRoleFunctions(epRole.getRoleFunctions()); + } + roles.add(role); + } + client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet())); + String userInString; + userInString = mapper.writerFor(FnUser.class).writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post a client to remote application, users json = " + userInString); + applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId)); + } + + private FnRole roleToFnRole(Role role) { + return new FnRole(role.getId(), role.getName(), role.getActive(), role.getPriority(), role.getRoleFunctions(), + role.getChildRoles(), role.getParentRoles()); + } + + private Set postUsersRolesToRemoteApp(List roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + throws JsonProcessingException, HTTPException { + Set updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); + Set updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); + String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote); + FnApp externalApp; + externalApp = appsCacheService.getApp(appId); + String appBaseUri = null; + Set updatedUserRolesinRemoteV1 = new TreeSet<>(); + if (externalApp != null) { + appBaseUri = externalApp.getAppRestEndpoint(); + } + if (appBaseUri != null && appBaseUri.endsWith("/api")) { + for (EcompRole eprole : updatedUserRolesinRemote) { + RemoteRoleV1 role = new RemoteRoleV1(); + role.setId(eprole.getId()); + role.setName(eprole.getName()); + updatedUserRolesinRemoteV1.add(role); + } + userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1); + } + applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, + String.format("/user/%s/roles", userId)); + return updateUserRolesInEcomp; + } + + private void addRemoteUser(List roleInAppForUserList, String userId, FnApp app, + ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception { + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper); + } + } + + private void createNewUserOnRemoteApp(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper) + throws Exception { + + FnUser client = fnUserService.loadUserByUsername(userId); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + 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); + } + + client.setLoginId(userId); + client.setActiveYn(true); + + String userInString; + userInString = mapper.writerFor(FnUser.class).writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post new client to remote application, users json = " + userInString); + applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId)); + + } + + private boolean remoteUserShouldBeCreated(List roleInAppForUserList) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.getIsApplied()) { + return true; + } + } + return false; + } + + private Set constructUsersRemoteAppRoles(List roleInAppForUserList) { + Set existingUserRoles = new TreeSet<>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId() + .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.getRoleId()); + ecompRole.setName(roleInAppForUser.getRoleName()); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) { + List epRequestIdVal; + try { + epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId); + if (epRequestIdVal.size() > 0) { + EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0); + epAppRolesRequestData.setUpdatedDate(LocalDateTime.now()); + epAppRolesRequestData.setRequestStatus("O"); + epAppRolesRequestData.setUserId(user); + epUserRolesRequestService.saveOne(epAppRolesRequestData); + List epUserAppRolesDetailList = epUserRolesRequestDetService + .appRolesRequestDetailList(epAppRolesRequestData.getReqId()); + if (epUserAppRolesDetailList.size() > 0) { + for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) { + epRequestUpdateList.setRequestType("O"); + epRequestUpdateList.setReqId(epAppRolesRequestData); + epRequestUpdateList.setReqId(epAppRolesRequestData); + epUserRolesRequestDetService.saveOne(epRequestUpdateList); + } + logger.debug(EELFLoggerDelegate.debugLogger, + "User App roles request from User Page is overridden"); + } + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e); + } + } + + private Set postUsersRolesToLocalApp(List roleInAppForUserList) { + return constructUsersEcompRoles(roleInAppForUserList); + } + + private Set constructUsersEcompRoles(List roleInAppForUserList) { + Set existingUserRoles = new TreeSet<>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.getIsApplied()) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.getRoleId()); + ecompRole.setName(roleInAppForUser.getRoleName()); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId, + Set userRolesInRemoteApp) { + RolesInAppForUser result; + result = new RolesInAppForUser(); + result.setAppId(appId); + result.setOrgUserId(userId); + + for (EcompRole role : userRolesInRemoteApp) { + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.setRoleId(role.getId()); + roleInAppForUser.setRoleName(role.getName()); + roleInAppForUser.setIsApplied(true); + result.getRoles().add(roleInAppForUser); + } + return result; + } + + private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List roleInAppUser, + boolean isPortalRequest, boolean isSystemUser, Set deletedRolesByApprover, + boolean isLoggedInUserRoleAdminofApp) throws Exception { + try { + List userInfo = checkIfUserExists(orgUserId); + if (userInfo.isEmpty()) { + createLocalUserIfNecessary(orgUserId, isSystemUser); + } + String name; + if (EPCommonSystemProperties + .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(); + HttpEntity getUserRolesEntity = new HttpEntity<>(headers); + ResponseEntity getResponse = externalAccessRolesService + .getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + + List userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + ExternalAccessUserRoleDetail userRoleDetail; + if (extRoles != null) { + for (int i = 0; i < extRoles.length(); i++) { + if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".") + && !extRoles.getJSONObject(i).getString("name") + .equals(app.getAuthNamespace() + ".admin") + && !extRoles.getJSONObject(i).getString("name") + .equals(app.getAuthNamespace() + ".owner")) { + if (extRoles.getJSONObject(i).has("description")) { + ExternalRoleDescription desc = new ExternalRoleDescription( + extRoles.getJSONObject(i).getString("description")); + userRoleDetail = new ExternalAccessUserRoleDetail( + extRoles.getJSONObject(i).getString("name"), desc); + userRoleDetailList.add(userRoleDetail); + } else { + userRoleDetail = new ExternalAccessUserRoleDetail( + extRoles.getJSONObject(i).getString("name"), null); + userRoleDetailList.add(userRoleDetail); + } + + } + } + } + + List userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList( + userRoleDetailList, app); + + List userAppList; + // If request coming from portal not from external role approval system then we have to check if user already + // have account admin or system admin as GUI will not send these roles + if (!isPortalRequest) { + FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0); + userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getAppId(), user.getUserId()); + if (!roleInAppUser.isEmpty()) { + for (EcompUserAppRoles userApp : userAppList) { + if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID) + || userApp.getRoleId() + .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { + RoleInAppForUser addSpecialRole = new RoleInAppForUser(); + addSpecialRole.setIsApplied(true); + addSpecialRole.setRoleId(userApp.getRoleId()); + addSpecialRole.setRoleName(userApp.getRoleName()); + roleInAppUser.add(addSpecialRole); + } + } + } + } + List roleInAppUserNonDupls = roleInAppUser.stream().distinct() + .collect(Collectors.toList()); + Map currentUserRolesToUpdate = new HashMap<>(); + for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) { + currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_"), roleInAppUserNew); + } + final Map currentUserRolesInExternalSystem = new HashMap<>(); + for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) { + currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole); + } + + if (isLoggedInUserRoleAdminofApp) { + if (deletedRolesByApprover.size() > 0) { + List newUpdatedRoles = new ArrayList<>(); + for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { + for (EcompRole role : deletedRolesByApprover) { + if ((userRole.getName().substring(app.getAuthNamespace().length() + 1)) + .equals(role.getName())) { + newUpdatedRoles.add(userRole); } - logger.info("isSuperAdmin " + isSuperAdmin); - return isSuperAdmin; - } - - public boolean isAccountAdmin(FnUser user) { - try { - final Map userParams = new HashMap<>(); - userParams.put("userId", user.getId()); - logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); - List userAdminApps; - String query = "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 and (fa.enabled = 'Y' || fa.app_id=1)"; - userAdminApps = entityManager.createQuery(query, Integer.class) - .setParameter("userId", user.getId()).getResultList(); - logger.debug(EELFLoggerDelegate.debugLogger, - "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", - user.getOrgUserId(), userAdminApps.size()); - - if (user.getId() != null) { - for (FnUserRole userApp : user.getFnUserRoles()) { - if (userApp.getRoleId().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.getRoleId().getId()); - return true; - } - } - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while executing isAccountAdmin operation", - e); + } + } + if (newUpdatedRoles.size() > 0) { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles); + } else { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + currentUserRolesToUpdate = new HashMap<>(); + + } + + } else { + userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(); + currentUserRolesToUpdate = new HashMap<>(); + + } + } + + // Check if user roles does not exists in local but still there in External Central Auth System delete them all + for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) { + if (!(currentUserRolesToUpdate + .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) { + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}", + userRole.getName()); + ResponseEntity deleteResponse = template.exchange( + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + userRole.getName(), + HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}", + userRole.getName(), deleteResponse.getBody()); + } + } + // Check if user roles does not exists in External Central Auth System add them all + for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) { + if (!(currentUserRolesInExternalSystem + .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_")))) { + ExternalAccessUser extUser = new ExternalAccessUser(name, + app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_")); + String formattedUserRole = mapper.writeValueAsString(extUser); + HttpEntity entity = new HttpEntity<>(formattedUserRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}", + name, addUserRole.getRoleName()); + ResponseEntity addResponse = template + .exchange(SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}", + addResponse.getBody(), addUserRole.getRoleName()); + if (addResponse.getStatusCode().value() != 201 + && addResponse.getStatusCode().value() != 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Finished POST operation in external system but unable to save user role", + addResponse.getBody(), + addUserRole.getRoleName()); + throw new Exception(addResponse.getBody()); + } + } + } + } 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; + } + } + + private List checkIfRoleAreMatchingInUserRoleDetailList( + List userRoleDetailList, FnApp app) { + Map epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app); + //Add Account Admin role for partner app to prevent conflict + if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) { + FnRole role = new FnRole(); + role.setRoleName(PortalConstants.ADMIN_ROLE + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + epRoleList.put(role.getRoleName(), role); + } + userRoleDetailList.removeIf( + userRoleDetail -> !epRoleList + .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1))); + return userRoleDetailList; + } + + private List checkIfUserExists(String userParams) { + return fnUserService.getUserWithOrgUserId(userParams); + } + + @Transactional + private void createLocalUserIfNecessary(String userId, boolean isSystemUser) { + if (StringUtils.isEmpty(userId)) { + logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); + return; + } + try { + List userList = fnUserService.getUserWithOrgUserId(userId); + if (userList.size() == 0) { + FnUser client; + if (!isSystemUser) { + client = fnUserService.loadUserByUsername(userId); + } else { + client = new FnUser(); + client.setOrgUserId(userId); + client.setIsSystemUser(true); + client.setFirstName(userId.substring(0, userId.indexOf("@"))); + } + if (client == null) { + String msg = "createLocalUserIfNecessary: cannot create user " + userId + + ", because not found in phonebook"; + logger.error(EELFLoggerDelegate.errorLogger, msg); + } else { + client.setLoginId(userId); + client.setActiveYn(true); + } + fnUserService.saveFnUser(client); + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + } + + } + + private FnUser checkIfRemoteUserExits(String userId, FnApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + FnUser checkRemoteUser = null; + try { + checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", + e); + } else if (e.getResponseCode() == 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing", + e); + } else { + // Other response code, let it come thru. + throw e; + } + } + return checkRemoteUser; + } + + private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService) + throws HTTPException { + if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) { + List userList = fnUserService.getUserWithOrgUserId(userId); + if (userList != null && !userList.isEmpty()) { + return userList.get(0); + } else { + return null; + } + } + return getUser(userId, app, applicationsRestClientService); + } + + private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, + boolean externalSystemRequest, String reqType, boolean isSystemUser, + Set rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception { + boolean result = false; + String userId = rolesInAppForUser.getOrgUserId(); + Long appId = rolesInAppForUser.getAppId(); + synchronized (syncRests) { + createLocalUserIfNecessary(userId, isSystemUser); + + EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()]; + for (int i = 0; + i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) { + RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i); + EcompRole role = new EcompRole(); + role.setId(roleInAppForUser.getRoleId()); + role.setName(roleInAppForUser.getRoleName()); + userAppRoles[i] = role; + } + try { + EcompRole[] applicationRoles = null; + + if (isLoggedInUserRoleAdminOfApp) { + List roles = Arrays.stream(userAppRoles) + .collect(Collectors.toList()); + List roles1 = new ArrayList<>(rolesDeletedByApprover); + roles.addAll(roles1); + applicationRoles = roles.toArray(new EcompRole[0]); + } + + syncUserRoles(userId, appId, userAppRoles, externalSystemRequest, + reqType, isLoggedInUserRoleAdminOfApp, applicationRoles); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + + userId, e); + if ("DELETE".equals(reqType)) { + throw new Exception(e.getMessage()); + } + } + } + return result; + } + + private void syncUserRoles(String userId, Long appId, + EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin, + EcompRole[] appRoles) throws Exception { + + Transaction transaction = null; + String roleActive; + HashMap newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); + List roleInfo = externalAccessRolesService + .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + FnRole adminRole = new FnRole(); + if (roleInfo.size() > 0) { + adminRole = roleInfo.get(0); + logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName()); + } + try { + List userList = fnUserService.getUserWithOrgUserId(userId); + if (userList.size() > 0) { + FnUser client = userList.get(0); + roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; + List userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId); + entityManager + .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive) + .setParameter("appId", appId) + .setParameter("userId", client.getId()) + .getResultList(); + + if ("DELETE".equals(reqType)) { + for (FnUserRole userAppRoleList : userRoles) { + List rolesList = + (!userAppRoleList.getRoleId().getRoleName() + .equals(adminRole.getRoleName())) + ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId + (userAppRoleList.getRoleId().getRoleName(), appId) + : fnRoleService.retrieveAppRolesWhereAppIdIsNull(); + if (!rolesList.isEmpty()) { + checkIfRoleInactive(rolesList.get(0)); + } + } + } + + if (appRoles != null) { + List appRolesList = Arrays.stream(appRoles).collect(Collectors.toList()); + List finalUserRolesList = new ArrayList<>(); + if (checkIfUserisRoleAdmin) { + for (EcompRole role : appRolesList) { + for (FnUserRole userAppRoleList : userRoles) { + if (userAppRoleList.getRoleId().getRoleName() + .equals(role.getName())) { + finalUserRolesList.add(userAppRoleList); + } + } - return false; - } - - public boolean isUser(FnUser user) { - try { - FnUser currentUser = fnUserService.getUser(user.getId()).orElseThrow(Exception::new); - if (currentUser != null && currentUser.getId() != null) { - for (FnUserRole userApp : currentUser.getFnUserRoles()) { - if (!userApp.getAppId().getId().equals(ECOMP_APP_ID)) { - FnRole role = userApp.getRoleId(); - if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId() - .equals(ACCOUNT_ADMIN_ROLE_ID)) { - if (role.getActiveYn()) { - return true; - } - } - } - } - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", - e); + } + userRoles = new ArrayList<>(finalUserRolesList); + } + } + + for (FnUserRole userRole : userRoles) { + if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getRoleId()) + && !PortalConstants.SYS_ADMIN_ROLE_ID + .equals(userRole.getRoleId().getRoleId()) + && !extRequestValue) { + syncUserRolesExtension(userRole, appId, + newUserAppRolesMap); + } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) + || "DELETE".equals(reqType))) { + syncUserRolesExtension(userRole, appId, + newUserAppRolesMap); + } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID + .equals(userRole.getRoleId().getRoleId())) { + syncUserRolesExtension(userRole, appId, + newUserAppRolesMap); + } + } + + Collection newRolesToAdd = newUserAppRolesMap.values(); + if (newRolesToAdd.size() > 0) { + FnApp app = fnAppService.getById(appId); + + HashMap rolesMap = new HashMap<>(); + if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app + String appIdValue = ""; + if (!extRequestValue) { + appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID; + } + @SuppressWarnings("unchecked") + List roles = entityManager + .createQuery( + "from " + FnRole.class.getName() + " where appId is null " + + appIdValue).getResultList(); + for (FnRole role : roles) { + role.setAppId(1L); + rolesMap.put(role.getId(), role); + } + } else { // remote app + @SuppressWarnings("unchecked") + List roles = entityManager + .createQuery("from EPRole where appId=:appId") + .setParameter("appId", appId) + .getResultList(); + for (FnRole role : roles) { + if (!extRequestValue && app.getAuthCentral()) { + rolesMap.put(role.getId(), role); + } else { + rolesMap.put(role.getAppRoleId(), role); } - return false; - } + } + } + + FnRole role; + for (EcompRole userRole : newRolesToAdd) { + FnUserRole userApp = new FnUserRole(); + if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName() + .equals(adminRole.getRoleName())) { + role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + userApp.setRoleId(role); + } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) + && !extRequestValue) { + continue; + } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app + .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) { + continue; + } else { + userApp.setRoleId(rolesMap.get(userRole.getId())); + } + + userApp.setUserId(client); + userApp.setAppId(app); + fnUserRoleService.saveOne(userApp); + } + + if (PortalConstants.PORTAL_APP_ID.equals(appId)) { + /* + * for local app -- hack - always make sure fn_role + * table's app_id is null and not 1 for primary app in + * this case being onap portal app; reason: hibernate + * is rightly setting this to 1 while persisting to + * fn_role as per the mapping but SDK role management + * code expects the app_id to be null as there is no + * concept of App_id in SDK + */ + Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 "); + query.executeUpdate(); + } + } + } + transaction.commit(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncUserRoles, Details: " + e.toString()); + if ("DELETE".equals(reqType)) { + throw new SyncUserRolesException(e.getMessage()); + } + } + } + + private static HashMap hashMapFromEcompRoles(EcompRole[] ecompRoles) { + HashMap result = new HashMap<>(); + if (ecompRoles != null) { + for (EcompRole ecompRole : ecompRoles) { + if (ecompRole.getId() != null) { + result.put(ecompRole.getId(), ecompRole); + } + } + } + return result; + } + + private void syncUserRolesExtension(FnUserRole userRole, Long appId, + HashMap newUserAppRolesMap) { + + Long userAppRoleId; + if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app + userAppRoleId = userRole.getRoleId().getRoleId(); + } else { // remote app + userAppRoleId = userRole.getId(); + } + + if (!newUserAppRolesMap.containsKey(userAppRoleId)) { + fnUserRoleService.deleteById(userRole.getId()); + } else { + newUserAppRolesMap.remove(userAppRoleId); + } + } + + private void checkIfRoleInactive(FnRole epRole) throws Exception { + if (!epRole.getActiveYn()) { + throw new Exception(epRole.getRoleName() + " role is unavailable"); + } + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/ApplicationsRestClientService.java b/portal-BE/src/main/java/org/onap/portal/service/ApplicationsRestClientService.java index e606cb0b..78434cc8 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/ApplicationsRestClientService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/ApplicationsRestClientService.java @@ -42,6 +42,7 @@ package org.onap.portal.service; import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import java.net.MalformedURLException; import java.net.URL; @@ -51,13 +52,11 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.apache.cxf.jaxrs.client.WebClient; -import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.apache.cxf.transport.http.HTTPException; import org.onap.portal.domain.db.fn.FnApp; import org.onap.portal.logging.aop.EPMetricsLog; import org.onap.portal.logging.format.EPAppMessagesEnum; import org.onap.portal.logging.logic.EPLogUtil; -import org.onap.portal.service.fn.old.AppsCacheService; import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portal.utils.EcompPortalUtils; import org.onap.portal.utils.SystemType; @@ -72,321 +71,340 @@ import org.springframework.stereotype.Service; @Service public class ApplicationsRestClientService { - private static final String PASSWORD_HEADER = "password"; - private static final String APP_USERNAME_HEADER = "username"; - private static final String BASIC_AUTHENTICATION_HEADER = "Authorization"; - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientService.class); - - Gson gson = null; - - private final AppsCacheService appsCacheService; - - @Autowired - public ApplicationsRestClientService(AppsCacheService appsCacheService) { - this.appsCacheService = appsCacheService; - } - - private static boolean isHttpSuccess(int status) { - return status / 100 == 2; - } - - @EPMetricsLog - private void verifyResponse(Response response, String restPath) throws HTTPException { - int status = response.getStatus(); - logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status); - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status)); - if (!isHttpSuccess(status)) { - String errMsg = - "Failed. Status=" + status + restPath + "; [" + ((ResponseImpl) response).getStatusInfo() - .getReasonPhrase().toString() - + "]"; - URL url = null; - try { - // must not be null to avoid NPE in HTTPException constructor - url = new URL("http://null"); - if (((ResponseImpl) response).getLocation() != null) { - url = ((ResponseImpl) response).getLocation().toURL(); - } - } catch (MalformedURLException e) { - // never mind. it is only for the debug message. - logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e); - } - logger.error(EELFLoggerDelegate.errorLogger, - "http response failed. " + restPath + errMsg + "; url=" + url); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeIncorrectHttpStatusError); - throw new HTTPException(status, errMsg, url); - } - } - - private WebClient createClientForApp(long appId, String restPath) { - return createClientFor(appId, restPath, SystemType.APPLICATION); - } - - private static WebClient createClientForPath(String baseUri, String path) { - logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path); - WebClient client = WebClient.create(baseUri); - client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); - client.path(path); - return client; - } - - //TODO Need to implement the mylogins once the endpoint is confirmed - @EPMetricsLog - private WebClient createClientFor(long appSystemId, String restPath, SystemType type) { - logger.debug(EELFLoggerDelegate.debugLogger, - "creating client for appId=" + appSystemId + "; restPath=" + restPath); - FnApp externalApp = null; - - if (type == SystemType.APPLICATION) { - externalApp = appsCacheService.getApp(appSystemId); - } else { - // TO DO - } - - if (externalApp != null) { - String appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : ""; - String username = (type == SystemType.APPLICATION) ? externalApp.getAppUsername() : ""; - String encriptedPwd = (type == SystemType.APPLICATION) ? externalApp.getAppPassword() : ""; - - String appName = (type == SystemType.APPLICATION) ? externalApp.getAppName() : ""; - String decreptedAppPwd = StringUtils.EMPTY; - - // Set local context - MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP); - if (appBaseUri != null && appBaseUri.contains("https")) { - MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS); - } - MDC.put(EPCommonSystemProperties.FULL_URL, appBaseUri + restPath); - MDC.put(EPCommonSystemProperties.TARGET_ENTITY, appName); - MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath); - - if (!encriptedPwd.isEmpty() || encriptedPwd != null || StringUtils.isEmpty(encriptedPwd)) { - try { - decreptedAppPwd = CipherUtil.decryptPKC(encriptedPwd, - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "createClientFor failed to decrypt", e); - } - } - WebClient client = createClientForPath(appBaseUri, restPath); - - if (externalApp.getAppPassword().isEmpty() || externalApp.getAppPassword() == null) { - logger.debug(EELFLoggerDelegate.debugLogger, - "Entering in the externalApp get app password contains null : {}"); - - externalApp = appsCacheService.getApp(1L); - logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}", externalApp); - - String mechidUsername = externalApp.getAppUsername(); - logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}", - mechidUsername); - - String password = externalApp.getAppPassword(); - String decreptedexternalAppPwd = StringUtils.EMPTY; - try { - decreptedexternalAppPwd = CipherUtil.decryptPKC(password, - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } catch (CipherUtilException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "failed to decreptedexternalAppPwd when external app pwd is null", e); - } - - username = mechidUsername; - decreptedAppPwd = decreptedexternalAppPwd; - - } else { - logger.debug(EELFLoggerDelegate.debugLogger, - "Entering in the externalApp get app password is not null : {}"); - - // support basic authentication for some partners - String encoding = Base64.getEncoder() - .encodeToString((username + ":" + decreptedAppPwd).getBytes()); - String encodingStr = "Basic " + encoding; - client.header(BASIC_AUTHENTICATION_HEADER, encodingStr); - } - - // But still keep code downward compatible for non compliant apps - client.header(APP_USERNAME_HEADER, username); - client.header(PASSWORD_HEADER, decreptedAppPwd); - - String encoding = Base64.getEncoder() - .encodeToString((username + ":" + decreptedAppPwd).getBytes()); - String encodingStr = "Basic " + encoding; - client.header(BASIC_AUTHENTICATION_HEADER, encodingStr); - client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); - client.header(SystemProperties.USERAGENT_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE); - logger.debug(EELFLoggerDelegate.debugLogger, - String.format( - "check the partner application URL App %d found, baseUri=[%s], Headers: [%s=%s]", - appSystemId, appBaseUri, - APP_USERNAME_HEADER, username)); - return client; - } - return null; - } - - public T post(Class clazz, long appId, Object payload, String restPath, SystemType type) - throws HTTPException { - WebClient client = null; - Response response = null; - T t = null; - - client = createClientFor(appId, restPath, type); - EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload); - - try { - if (client != null) { - response = client.post(payload); - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "Unable to create the Webclient to make the '" + restPath + "' API call."); - } - } catch (Exception e) { - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, - Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while making the POST REST API call", e); - } - - if (response != null) { - //verifyResponse(response); - verifyResponse(response, restPath); - // String contentType = response.getHeaderString("Content-Type"); - if (clazz != null) { - String str = ((ResponseImpl) response).readEntity(String.class); - EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str); - try { - t = (T) gson.fromJson(str, clazz); - - //t = gson.fromJson(str, clazz); - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); - } - } - } - return t; - } - - public T post(Class clazz, long appId, Object payload, String restPath) throws HTTPException { - return post(clazz, appId, payload, restPath, SystemType.APPLICATION); - } - - public T put(Class clazz, long appId, Object payload, String restPath) throws HTTPException { - WebClient client = null; - Response response = null; - T t = null; - - logger.debug(EELFLoggerDelegate.debugLogger, - "Entering to createClientForApp method for payload: {} and restPath: {} and appId: {}", - payload.toString(), restPath, appId); - - client = createClientForApp(appId, restPath); - EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT request =", payload); - - logger.debug(EELFLoggerDelegate.debugLogger, - "Finished createClientForApp method for payload: {} and restPath: {} and appId: {}", - payload.toString(), restPath, appId); - - try { - if (client != null) { - logger.debug(EELFLoggerDelegate.debugLogger, - "Entering to PUT for payload: {} and restPath: {} and appId: {}", - payload.toString(), restPath, appId); - - response = client.put(payload); - - logger.debug(EELFLoggerDelegate.debugLogger, - "Finished to PUT for payload: {} and restPath: {} and appId: {}", - payload.toString(), restPath, appId); - - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "Unable to create the Webclient to make the '" + restPath + "' API call."); - } - } catch (Exception e) { - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, - Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while making the PUT REST API call", e); - } - - if (response != null) { - //verifyResponse(response); - verifyResponse(response, restPath); - String str = ((ResponseImpl) response).readEntity(String.class); - EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT result =", str); - try { - t = gson.fromJson(str, clazz); - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); - } - } - return t; - } - - protected Response getResponse(long appId, String restPath) { - WebClient webClient = null; - Response response = null; - - webClient = createClientForApp(appId, restPath); - EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET request =", "no-payload"); - - try { - if (webClient != null) { - response = webClient.get(); - } else { - logger.error(EELFLoggerDelegate.errorLogger, - "Unable to create the Webclient to make the '" + restPath + "' API call."); - } - } catch (Exception e) { - MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, - Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while making the GET REST API call", e); - } - return response; - } - - public T get(Class clazz, long appId, String restPath) throws HTTPException { - T t = null; - Response response = getResponse(appId, restPath); - - if (response != null) { - //verifyResponse(response); - verifyResponse(response, restPath); + private static final String PASSWORD_HEADER = "password"; + private static final String APP_USERNAME_HEADER = "username"; + private static final String BASIC_AUTHENTICATION_HEADER = "Authorization"; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientService.class); + + private Gson gson = null; + + private final ObjectMapper mapper = new ObjectMapper(); + + private final AppsCacheService appsCacheService; + + @Autowired + public ApplicationsRestClientService(AppsCacheService appsCacheService) { + this.appsCacheService = appsCacheService; + } + + private static boolean isHttpSuccess(int status) { + return status / 100 == 2; + } + + @EPMetricsLog + private void verifyResponse(Response response, String restPath) throws HTTPException { + int status = response.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status); + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status)); + if (!isHttpSuccess(status)) { + String errMsg = + "Failed. Status=" + status + restPath + "; [" + response.getStatusInfo() + .getReasonPhrase() + + "]"; + URL url = null; + try { + // must not be null to avoid NPE in HTTPException constructor + url = new URL("http://null"); + if (response.getLocation() != null) { + url = response.getLocation().toURL(); + } + } catch (MalformedURLException e) { + // never mind. it is only for the debug message. + logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e); + } + logger.error(EELFLoggerDelegate.errorLogger, + "http response failed. " + restPath + errMsg + "; url=" + url); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeIncorrectHttpStatusError); + throw new HTTPException(status, errMsg, url); + } + } + + private WebClient createClientForApp(long appId, String restPath) { + return createClientFor(appId, restPath, SystemType.APPLICATION); + } + + private static WebClient createClientForPath(String baseUri, String path) { + logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path); + WebClient client = WebClient.create(baseUri); + client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); + client.path(path); + return client; + } + + //TODO Need to implement the mylogins once the endpoint is confirmed + @EPMetricsLog + private WebClient createClientFor(long appSystemId, String restPath, SystemType type) { + logger.debug(EELFLoggerDelegate.debugLogger, + "creating client for appId=" + appSystemId + "; restPath=" + restPath); + FnApp externalApp = null; + + if (type == SystemType.APPLICATION) { + externalApp = appsCacheService.getApp(appSystemId); + } + + if (externalApp != null) { + String appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : ""; + String username = (type == SystemType.APPLICATION) ? externalApp.getAppUsername() : ""; + String encriptedPwd = (type == SystemType.APPLICATION) ? externalApp.getAppPassword() : ""; + + String appName = (type == SystemType.APPLICATION) ? externalApp.getAppName() : ""; + String decreptedAppPwd = StringUtils.EMPTY; + + // Set local context + MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP); + if (appBaseUri != null && appBaseUri.contains("https")) { + MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS); + } + MDC.put(EPCommonSystemProperties.FULL_URL, appBaseUri + restPath); + MDC.put(EPCommonSystemProperties.TARGET_ENTITY, appName); + MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath); + + try { + decreptedAppPwd = CipherUtil.decryptPKC(encriptedPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createClientFor failed to decrypt", e); + } + WebClient client = createClientForPath(appBaseUri, restPath); + + if (externalApp.getAppPassword().isEmpty() || externalApp.getAppPassword() == null) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Entering in the externalApp get app password contains null : {}"); + + externalApp = appsCacheService.getApp(1L); + logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}", externalApp); + + String mechidUsername = externalApp.getAppUsername(); + logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}", + mechidUsername); + + String password = externalApp.getAppPassword(); + String decreptedexternalAppPwd = StringUtils.EMPTY; + try { + decreptedexternalAppPwd = CipherUtil.decryptPKC(password, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (CipherUtilException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "failed to decreptedexternalAppPwd when external app pwd is null", e); + } + + username = mechidUsername; + decreptedAppPwd = decreptedexternalAppPwd; + + } else { + logger.debug(EELFLoggerDelegate.debugLogger, + "Entering in the externalApp get app password is not null : {}"); + + // support basic authentication for some partners + String encoding = Base64.getEncoder() + .encodeToString((username + ":" + decreptedAppPwd).getBytes()); + String encodingStr = "Basic " + encoding; + client.header(BASIC_AUTHENTICATION_HEADER, encodingStr); + } + + // But still keep code downward compatible for non compliant apps + client.header(APP_USERNAME_HEADER, username); + client.header(PASSWORD_HEADER, decreptedAppPwd); + + String encoding = Base64.getEncoder() + .encodeToString((username + ":" + decreptedAppPwd).getBytes()); + String encodingStr = "Basic " + encoding; + client.header(BASIC_AUTHENTICATION_HEADER, encodingStr); + client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); + client.header(SystemProperties.USERAGENT_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE); + logger.debug(EELFLoggerDelegate.debugLogger, + String.format( + "check the partner application URL App %d found, baseUri=[%s], Headers: [%s=%s]", + appSystemId, appBaseUri, + APP_USERNAME_HEADER, username)); + return client; + } + return null; + } + + public T post(Class clazz, long appId, Object payload, String restPath, SystemType type) + throws HTTPException { + WebClient client; + Response response = null; + T t = null; + + client = createClientFor(appId, restPath, type); + EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload); + + try { + if (client != null) { + response = client.post(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while making the POST REST API call", e); + } + + if (response != null) { + verifyResponse(response, restPath); + if (clazz != null) { + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str); + try { + t = gson.fromJson(str, clazz); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } + } + return t; + } + + public T post(Class clazz, long appId, Object payload, String restPath) throws HTTPException { + return post(clazz, appId, payload, restPath, SystemType.APPLICATION); + } + + public T put(Class clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client; + Response response = null; + T t = null; + + logger.debug(EELFLoggerDelegate.debugLogger, + "Entering to createClientForApp method for payload: {} and restPath: {} and appId: {}", + payload.toString(), restPath, appId); + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT request =", payload); + + logger.debug(EELFLoggerDelegate.debugLogger, + "Finished createClientForApp method for payload: {} and restPath: {} and appId: {}", + payload.toString(), restPath, appId); + + try { + if (client != null) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Entering to PUT for payload: {} and restPath: {} and appId: {}", + payload.toString(), restPath, appId); + + response = client.put(payload); + + logger.debug(EELFLoggerDelegate.debugLogger, + "Finished to PUT for payload: {} and restPath: {} and appId: {}", + payload.toString(), restPath, appId); + + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while making the PUT REST API call", e); + } + + if (response != null) { + verifyResponse(response, restPath); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT result =", str); + try { + t = gson.fromJson(str, clazz); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } + return t; + } + + private Response getResponse(long appId, String restPath) { + WebClient webClient; + Response response = null; + + webClient = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET request =", "no-payload"); + + try { + if (webClient != null) { + response = webClient.get(); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while making the GET REST API call", e); + } + return response; + } + + public T get(Class clazz, long appId, String restPath) throws HTTPException { + T t = null; + Response response = getResponse(appId, restPath); + + if (response != null) { + //verifyResponse(response); + verifyResponse(response, restPath); /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which doesn't work as expected. Created Portal-253 for tracking */ - String str = ((ResponseImpl) response).readEntity(String.class); + String str = response.readEntity(String.class); - EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str); - try { - t = gson.fromJson(str, clazz); - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); - } - } + EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str); + try { + t = gson.fromJson(str, clazz); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } - return t; - } + return t; + } - public String getIncomingJsonString(final Long appId, final String restPath) throws HTTPException { - Response response = getResponse(appId, restPath); + public String getIncomingJsonString(final Long appId, final String restPath) throws HTTPException { + Response response = getResponse(appId, restPath); - if (response != null) { - //verifyResponse(response); - verifyResponse(response,restPath); + if (response != null) { + //verifyResponse(response); + verifyResponse(response, restPath); /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which doesn't work as expected. Created Portal-253 for tracking */ - String incomingJson = ((ResponseImpl)response).readEntity(String.class); - return incomingJson; - } + return (response).readEntity(String.class); + } + + return ""; + } + + public T get(Class clazz, Long appId, String restPath, boolean useJacksonMapper) throws HTTPException { + + if (!useJacksonMapper) { + return get(clazz, appId, restPath); + } + + T t = null; + Response response = getResponse(appId, restPath); + + if (response != null) { + //verifyResponse(response); + verifyResponse(response, restPath); + String str = (response).readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str); + + try { + t = mapper.readValue(str, clazz); + } catch (Exception e) { + e.printStackTrace(); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } + + return t; + } - return ""; - } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/AppsCacheService.java b/portal-BE/src/main/java/org/onap/portal/service/AppsCacheService.java new file mode 100644 index 00000000..6274f9a6 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/AppsCacheService.java @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.dto.transport.OnboardingApp; +import org.onap.portal.service.fn.FnAppService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class AppsCacheService { + + + private final FnAppService appsService; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheService.class); + + @Autowired + public AppsCacheService(FnAppService appsService) { + this.appsService = appsService; + } + + final class CacheConfiguration { + + private long updateTime; + private final int updateInterval; + + CacheConfiguration(long updateTime, int updateInterval) { + this.updateTime = updateTime; + this.updateInterval = updateInterval; + } + } + + private CacheConfiguration quickRefreshCacheConf = null; + private CacheConfiguration slowRefreshCacheConf = null; + + + private static volatile Map appsMap; + private static volatile Map uebAppsMap; + + @PostConstruct + public void init() { + quickRefreshCacheConf = new CacheConfiguration(0, 120); + slowRefreshCacheConf = new CacheConfiguration(0, 3600); + + this.refreshAppsMap(quickRefreshCacheConf); + } + + private void refreshAppsMap(CacheConfiguration conf) { + long now = System.currentTimeMillis(); + + if (noNeedToUpdate(now, conf)) { + return; + } + + synchronized (this) { + if (noNeedToUpdate(now, conf)) { + return; + } + List allApps = appsService.getAppsFullList(); + Map newAppsMap = new HashMap<>(); + for (FnApp app : allApps) { + newAppsMap.put(app.getId(), app); + } + + Map newUebAppsMap = new HashMap<>(); + for (FnApp app : allApps) { + newUebAppsMap.put(app.getUebKey(), app); + } + // Switch cache with the new one. + appsMap = newAppsMap; + uebAppsMap = newUebAppsMap; + conf.updateTime = now; + } + + } + + private boolean noNeedToUpdate(long now, CacheConfiguration conf) { + long secondsPassed = (now - conf.updateTime) / 1000; + if (secondsPassed < conf.updateInterval) { + logger.debug(EELFLoggerDelegate.debugLogger, + "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + + conf.updateInterval); + return true; // no need to update cache + } + return false; // its time to update + } + + public String getAppEndpoint(Long appId) { + refreshAppsMap(quickRefreshCacheConf); + FnApp app = appsMap.get(appId); + if (app != null) { + return app.getAppRestEndpoint(); + } + return null; + } + + public List getAppsFullList() { + refreshAppsMap(quickRefreshCacheConf); + List appList = new ArrayList<>(appsMap.values()); + appList.removeIf(app -> app.getId() == 1); + List appsFinalList = appList.stream() + .filter(app -> app.getEnabled() && !app.getOpen()).collect(Collectors.toList()); + + List onboardingAppsList = new ArrayList(); + for (FnApp app : appsFinalList) { + OnboardingApp onboardingApp = new OnboardingApp(); + appsService.createOnboardingFromApp(app, onboardingApp); + onboardingAppsList.add(onboardingApp); + } + return onboardingAppsList; + } + + public FnApp getApp(Long appId) { + refreshAppsMap(quickRefreshCacheConf); + return appsMap.get(appId); + } + + public FnApp getAppFromUeb(String appKey) { + return getAppFromUeb(appKey, 0); + } + + public FnApp getAppFromUeb(String appKey, Integer quickCacheRefresh) { + refreshAppsMap(quickCacheRefresh == 1 ? quickRefreshCacheConf : slowRefreshCacheConf); + return uebAppsMap.get(appKey); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/EcompUserAppRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/EcompUserAppRolesService.java new file mode 100644 index 00000000..2a8415c3 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/EcompUserAppRolesService.java @@ -0,0 +1,86 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.List; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.persistence.Tuple; +import org.onap.portal.domain.dto.transport.EcompUserAppRoles; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class EcompUserAppRolesService { + + private final static String QUERY = "select\n" + + " fr.role_name as roleName,\n" + + " fu.app_id as appId,\n" + + " fu.user_id as userId,\n" + + " fu.priority as priority,\n" + + " fu.role_id as roleId\n" + + " from\n" + + " fn_user_role fu\n" + + " left outer join fn_role fr on fu.role_id = fr.role_id\n" + + " where\n" + + " fu.user_id = :userId\n" + + " and fu.app_id = :appId"; + + private final EntityManager entityManager; + + @Autowired + public EcompUserAppRolesService(EntityManager entityManager) { + this.entityManager = entityManager; + } + + + public List getUserAppExistingRoles(final Long appId, final Long userId){ + List tuples = entityManager.createQuery(QUERY, Tuple.class) + .setParameter("appId", appId) + .setParameter("userId", userId) + .getResultList(); + return tuples.stream().map(this::tupleToEcompUserAppRoles).collect(Collectors.toList()); + } + + private EcompUserAppRoles tupleToEcompUserAppRoles(Tuple tuple){ + return new EcompUserAppRoles((String)tuple.get("appId"), (Long) tuple.get("userId"), (Integer) tuple.get("priority"), (Long) tuple.get("roleId"), (String) tuple.get("roleName")); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java new file mode 100644 index 00000000..e1ad4305 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java @@ -0,0 +1,223 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedSet; +import java.util.TreeSet; +import org.onap.portal.domain.db.ep.EpAppFunction; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.db.fn.FnRole; +import org.onap.portal.domain.dto.transport.CentralV2Role; +import org.onap.portal.exception.RoleFunctionException; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.ep.EpAppFunctionService; +import org.onap.portal.service.fn.FnRoleService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EPUserUtils; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portal.utils.PortalConstants; +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.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class 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(ExternalAccessRolesService.class); + private RestTemplate template = new RestTemplate(); + + private final FnRoleService fnRoleService; + private final EpAppFunctionService epAppFunctionService; + + @Autowired + public ExternalAccessRolesService(FnRoleService fnRoleService, + EpAppFunctionService epAppFunctionService) { + this.fnRoleService = fnRoleService; + this.epAppFunctionService = epAppFunctionService; + } + + 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; + } + + private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) { + return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url"); + } + + private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) { + return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url"); + } + + private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) { + return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url"); + } + + public List getPortalAppRoleInfo(Long roleId) { + return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId); + } + + public ResponseEntity getUserRolesFromExtAuthSystem(String name, HttpEntity getUserRolesEntity) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if (getResponse.getStatusCode().value() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, + "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}", + getResponse.getBody()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}", + getResponse.getBody()); + EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode()); + } + return getResponse; + } + + public Map getAppRoleNamesWithUnderscoreMap(FnApp app) { + final Map currentRolesInDB = new HashMap<>(); + List getCurrentRoleList = null; + final Map appParams = new HashMap<>(); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull(); + } else { + appParams.put("appId", app.getId()); + getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId()); + } + for (FnRole role : getCurrentRoleList) { + currentRolesInDB.put(role.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role); + } + return currentRolesInDB; + } + + public List createCentralRoleObject(List app, List roleInfo, + List roleList) throws RoleFunctionException { + for (FnRole role : roleInfo) { + List cenRoleFuncList = epAppFunctionService + .getAppRoleFunctionList(role.getId(), app.get(0).getId()); + SortedSet roleFunctionSet = new TreeSet<>(); + for (EpAppFunction roleFunc : cenRoleFuncList) { + String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd()); + functionCode = EPUserUtils.decodeFunctionCode(functionCode); + String type = getFunctionCodeType(roleFunc.getFunctionCd()); + String action = getFunctionCodeAction(roleFunc.getFunctionCd()); + EpAppFunction cenRoleFunc = new EpAppFunction(role.getId(), functionCode, + roleFunc.getFunctionName(), null, type, action, null); + roleFunctionSet.add(cenRoleFunc); + } + SortedSet childRoles = new TreeSet<>(); + SortedSet parentRoles = new TreeSet<>(); + CentralV2Role cenRole; + if (role.getAppRoleId() == null) { + cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated()) + .modified(role.getModified()).createdId(role.getCreatedId().getUserId()) + .modifiedId(role.getModifiedId().getUserId()).rowNum(role.getRowNum()).name(role.getRoleName()) + .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet) + .childRoles(childRoles).parentRoles(parentRoles).build(); + } else { + cenRole = CentralV2Role.builder().id(role.getAppRoleId()) + .created(role.getCreated()).modified(role.getModified()).createdId(role.getCreatedId().getUserId()) + .modifiedId(role.getModifiedId().getUserId()).rowNum(role.getRowNum()).name(role.getRoleName()) + .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet) + .childRoles(childRoles).parentRoles(parentRoles).build(); + } + roleList.add(cenRole); + } + return roleList; + } + + private String getFunctionCodeAction(String roleFuncItem) { + return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem); + } + + public List getAppRoles(Long appId) { + List applicationRoles; + try { + if (appId == 1) { + applicationRoles = fnRoleService.retrieveAppRolesWhereAppIdIsNull(); + } else { + applicationRoles = fnRoleService.retrieveAppRolesByAppId(appId); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e); + throw e; + } + return applicationRoles; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/ep/EpAppFunctionService.java b/portal-BE/src/main/java/org/onap/portal/service/ep/EpAppFunctionService.java new file mode 100644 index 00000000..b3691fce --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/ep/EpAppFunctionService.java @@ -0,0 +1,62 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service.ep; + +import java.util.List; +import org.onap.portal.dao.ep.EpAppFunctionDao; +import org.onap.portal.domain.db.ep.EpAppFunction; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class EpAppFunctionService { + + private final EpAppFunctionDao epAppFunctionDao; + + @Autowired + public EpAppFunctionService(EpAppFunctionDao epAppFunctionDao) { + this.epAppFunctionDao = epAppFunctionDao; + } + + public List getAppRoleFunctionList(final Long roleId, final Long appId) { + return epAppFunctionDao.getAppRoleFunctionList(roleId, appId); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestDetService.java b/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestDetService.java index 52e4527f..11c78b46 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestDetService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestDetService.java @@ -40,6 +40,9 @@ package org.onap.portal.service.ep; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.onap.portal.dao.ep.EpUserRolesRequestDetDao; import org.onap.portal.domain.db.ep.EpUserRolesRequestDet; import org.springframework.beans.factory.annotation.Autowired; @@ -59,4 +62,8 @@ public class EpUserRolesRequestDetService { public EpUserRolesRequestDet saveOne(EpUserRolesRequestDet epUserRolesRequestDet){ return epUserRolesRequestDetDao.save(epUserRolesRequestDet); } + + public List appRolesRequestDetailList(final Long reqId){ + return Optional.of(epUserRolesRequestDetDao.appRolesRequestDetailList(reqId)).orElse(new ArrayList<>()); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestService.java b/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestService.java index 3acd40e9..4f5326d7 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/ep/EpUserRolesRequestService.java @@ -40,6 +40,9 @@ package org.onap.portal.service.ep; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.onap.portal.dao.ep.EpUserRolesRequestDao; import org.onap.portal.domain.db.ep.EpUserRolesRequest; import org.springframework.beans.factory.annotation.Autowired; @@ -59,4 +62,8 @@ public class EpUserRolesRequestService { public EpUserRolesRequest saveOne(EpUserRolesRequest epUserRolesRequest){ return epUserRolesRequestDao.save(epUserRolesRequest); } + + public List userAppRolesRequestList(final Long userId, final Long appId){ + return Optional.of(epUserRolesRequestDao.userAppRolesRequestList(userId, appId)).orElse(new ArrayList<>()); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java index d8d88c97..a3920e31 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java @@ -40,9 +40,13 @@ package org.onap.portal.service.fn; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.TreeSet; import javax.persistence.EntityExistsException; +import javax.persistence.EntityManager; +import javax.persistence.Query; import org.onap.portal.dao.fn.FnAppDao; import org.onap.portal.domain.db.fn.FnApp; import org.onap.portal.domain.dto.transport.OnboardingApp; @@ -56,56 +60,72 @@ import org.springframework.stereotype.Service; @Service public class FnAppService { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppService.class); + private static final String SUPER_ADMIN_ROLE_ID = "1"; - private final FnAppDao fnAppDao; + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppService.class); - @Autowired - public FnAppService(final FnAppDao fnAppDao) { - this.fnAppDao = fnAppDao; - } + private final FnAppDao fnAppDao; + private final EntityManager entityManager; - public List getAppsFullList() { - return fnAppDao.findAll(); - } + @Autowired + public FnAppService(final FnAppDao fnAppDao, EntityManager entityManager) { + this.fnAppDao = fnAppDao; + this.entityManager = entityManager; + } - public FnApp getById(final Long id){ - return Optional.of(fnAppDao.getOne(id)).orElseThrow(EntityExistsException::new); - } + public List getAppsFullList() { + return fnAppDao.findAll(); + } - public void createOnboardingFromApp(FnApp app, OnboardingApp onboardingApp) { - onboardingApp.setId(app.getId()); - onboardingApp.setName(app.getAppName()); - onboardingApp.setImageUrl(app.getAppImageUrl()); - onboardingApp.setDescription(app.getAppDescription()); - onboardingApp.setNotes(app.getAppNotes()); - onboardingApp.setUrl(app.getAppUrl()); - onboardingApp.setAlternateUrl(app.getAppAlternateUrl()); - onboardingApp.setRestUrl(app.getAppRestEndpoint()); - onboardingApp.setIsOpen(app.getOpen()); - onboardingApp.setIsEnabled(app.getEnabled()); - onboardingApp.setUsername(app.getAppUsername()); - onboardingApp.setAppPassword((app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) - ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD : decryptedPassword(app.getAppPassword(), app)); - onboardingApp.setUebTopicName(app.getUebTopicName()); - onboardingApp.setUebKey(app.getUebKey()); - onboardingApp.setUebSecret(app.getUebSecret()); - onboardingApp.setIsCentralAuth(app.getAuthCentral()); - onboardingApp.setNameSpace(app.getAuthNamespace()); - onboardingApp.setRestrictedApp(app.isRestrictedApp()); - } + public FnApp getById(final Long id) { + return Optional.of(fnAppDao.getOne(id)).orElseThrow(EntityExistsException::new); + } - private String decryptedPassword(String encryptedAppPwd, FnApp app) { - String result = ""; - if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) { - try { - result = CipherUtil.decryptPKC(encryptedAppPwd, - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "decryptedPassword failed for app " + app.getAppName(), e); - } - } - return result; - } + public void createOnboardingFromApp(FnApp app, OnboardingApp onboardingApp) { + onboardingApp.setId(app.getId()); + onboardingApp.setName(app.getAppName()); + onboardingApp.setImageUrl(app.getAppImageUrl()); + onboardingApp.setDescription(app.getAppDescription()); + onboardingApp.setNotes(app.getAppNotes()); + onboardingApp.setUrl(app.getAppUrl()); + onboardingApp.setAlternateUrl(app.getAppAlternateUrl()); + onboardingApp.setRestUrl(app.getAppRestEndpoint()); + onboardingApp.setIsOpen(app.getOpen()); + onboardingApp.setIsEnabled(app.getEnabled()); + onboardingApp.setUsername(app.getAppUsername()); + onboardingApp.setAppPassword((app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) + ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD : decryptedPassword(app.getAppPassword(), app)); + onboardingApp.setUebTopicName(app.getUebTopicName()); + onboardingApp.setUebKey(app.getUebKey()); + onboardingApp.setUebSecret(app.getUebSecret()); + onboardingApp.setIsCentralAuth(app.getAuthCentral()); + onboardingApp.setNameSpace(app.getAuthNamespace()); + onboardingApp.setRestrictedApp(app.isRestrictedApp()); + } + + private String decryptedPassword(String encryptedAppPwd, FnApp app) { + String result = ""; + if (encryptedAppPwd != null && !encryptedAppPwd.isEmpty()) { + try { + result = CipherUtil.decryptPKC(encryptedAppPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "decryptedPassword failed for app " + app.getAppName(), e); + } + } + return result; + } + + List getUserRemoteApps(String id) { +/* StringBuilder sb = new StringBuilder(); + sb.append("SELECT * FROM FnApp join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where "); + sb.append("FN_USER_ROLE.USER_ID = ").append(id).append(" AND FN_USER_ROLE.ROLE_ID != ") + .append(SUPER_ADMIN_ROLE_ID); + sb.append(" AND FN_APP.ENABLED = 'Y'"); + + Query query = entityManager.createQuery(sb.toString()); + List adminApps = query.getResultList();*/ + return new ArrayList<>(); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java index cabefcc3..aa859dbd 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java @@ -54,42 +54,60 @@ import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class FnRoleService { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnRoleService.class); + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnRoleService.class); - private final FnRoleDao fnRoleDao; - @Autowired - public FnRoleService(FnRoleDao fnRoleDao) { - this.fnRoleDao = fnRoleDao; - } + private final FnRoleDao fnRoleDao; - public FnRole getById(final Long id) { - return fnRoleDao.findById(id).orElseThrow(EntityExistsException::new); - } + @Autowired + public FnRoleService(FnRoleDao fnRoleDao) { + this.fnRoleDao = fnRoleDao; + } - public FnRole getRole(final Long appId, final Long appRoleId) { + public FnRole getById(final Long id) { + return fnRoleDao.findById(id).orElseThrow(EntityExistsException::new); + } - String sql = "SELECT * FROM fn_role where APP_ID = :appId AND APP_ROLE_ID = :appRoleId"; + public FnRole getRole(final Long appId, final Long appRoleId) { - List roles = Optional.of(fnRoleDao.retrieveAppRoleByAppRoleIdAndByAppId(appId, appRoleId)).orElse(new ArrayList<>()); - if (!roles.isEmpty()) { - logger.error(EELFLoggerDelegate.errorLogger, - String.format( - "search by appId=%s, appRoleid=%s should have returned 0 or 1 results. Got %d. This is an internal server error.", - appId, appRoleId, roles.size())); - logger.error(EELFLoggerDelegate.errorLogger, - "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar."); - return roles.get(0); - } - return null; - } + String sql = "SELECT * FROM fn_role where APP_ID = :appId AND APP_ROLE_ID = :appRoleId"; - public List retrieveAppRoleByAppRoleIdAndByAppId(Long appId, Long appRoleId){ - return Optional.of(fnRoleDao.retrieveAppRoleByAppRoleIdAndByAppId(appId, appRoleId)).orElse(new ArrayList<>()); - } + List roles = Optional.of(fnRoleDao.retrieveAppRoleByAppRoleIdAndByAppId(appId, appRoleId)) + .orElse(new ArrayList<>()); + if (!roles.isEmpty()) { + logger.error(EELFLoggerDelegate.errorLogger, + String.format( + "search by appId=%s, appRoleid=%s should have returned 0 or 1 results. Got %d. This is an internal server error.", + appId, appRoleId, roles.size())); + logger.error(EELFLoggerDelegate.errorLogger, + "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar."); + return roles.get(0); + } + return null; + } - public List getUserRoleOnUserIdAndAppId(final Long userId, final Long appId) { - return Optional.of(fnRoleDao.getUserRoleOnUserIdAndAppId(userId, appId)).orElse(new ArrayList<>()); - } + public List retrieveAppRoleByAppRoleIdAndByAppId(final Long appId, final Long appRoleId) { + return Optional.of(fnRoleDao.retrieveAppRoleByAppRoleIdAndByAppId(appId, appRoleId)).orElse(new ArrayList<>()); + } + + public List getUserRoleOnUserIdAndAppId(final Long userId, final Long appId) { + return Optional.of(fnRoleDao.getUserRoleOnUserIdAndAppId(userId, appId)).orElse(new ArrayList<>()); + } + + public List retrieveAppRoleByRoleIdWhereAppIdIsNull(final Long roleId) { + return Optional.of(fnRoleDao.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId)).orElse(new ArrayList<>()); + } + + public List retrieveAppRolesWhereAppIdIsNull() { + return Optional.of(fnRoleDao.retrieveAppRolesWhereAppIdIsNull()).orElse(new ArrayList<>()); + } + + public List retrieveAppRolesByAppId(final Long id) { + return Optional.of(fnRoleDao.retrieveAppRolesByAppId(id)).orElse(new ArrayList<>()); + } + + public List retrieveAppRolesByRoleNameAndByAppId(final String roleName, final Long appId) { + return Optional.of(fnRoleDao.retrieveAppRolesByRoleNameAndByAppId(roleName, appId)).orElse(new ArrayList<>()); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java index 6c1b9fa0..7772c8f0 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java @@ -47,6 +47,7 @@ import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; @@ -56,9 +57,14 @@ import java.util.Set; import java.util.SortedSet; import java.util.stream.Collectors; import javax.persistence.EntityManager; +import javax.persistence.Query; import javax.persistence.Tuple; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang.StringUtils; import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; import org.onap.portal.dao.fn.FnUserRoleDao; import org.onap.portal.domain.db.ep.EpUserRolesRequest; import org.onap.portal.domain.db.ep.EpUserRolesRequestDet; @@ -69,325 +75,409 @@ import org.onap.portal.domain.db.fn.FnUserRole; import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles; import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess; import org.onap.portal.domain.dto.transport.AppWithRolesForUser; +import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail; import org.onap.portal.domain.dto.transport.FieldsValidator; import org.onap.portal.domain.dto.transport.RemoteRole; import org.onap.portal.domain.dto.transport.RemoteUserWithRoles; import org.onap.portal.domain.dto.transport.RoleInAppForUser; import org.onap.portal.domain.dto.transport.UserApplicationRoles; +import org.onap.portal.exception.SyncUserRolesException; +import org.onap.portal.logging.format.EPAppMessagesEnum; +import org.onap.portal.logging.logic.EPLogUtil; import org.onap.portal.service.ApplicationsRestClientService; +import org.onap.portal.service.ExternalAccessRolesService; import org.onap.portal.service.ep.EpUserRolesRequestDetService; import org.onap.portal.service.ep.EpUserRolesRequestService; import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EcompPortalUtils; import org.onap.portal.utils.PortalConstants; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.restful.domain.EcompRole; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; @Service @Transactional public class FnUserRoleService { - private static final String USER_APP_CATALOG_ROLES = - "select\n" - + " A.reqId as reqId,\n" - + " B.requestedRoleId.roleId as requestedRoleId,\n" - + " A.requestStatus as requestStatus,\n" - + " A.appId.appId as appId,\n" - + " (\n" - + " select\n" - + " roleName\n" - + " from\n" - + " FnRole\n" - + " where\n" - + " roleId = B.requestedRoleId.roleId\n" - + " ) as roleName\n" - + "from\n" - + " EpUserRolesRequest A\n" - + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n" - + "where\n" - + " A.userId.userId = :userid\n" - + " and A.appId IN (\n" - + " select\n" - + " appId\n" - + " from\n" - + " FnApp\n" - + " where\n" - + " appName = :appName\n" - + " )\n" - + " and A.requestStatus = 'P'\n"; - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class); - private final FnUserRoleDao fnUserRoleDao; - private final FnAppService fnAppService; - private final FnRoleService fnRoleService; - private final FnUserService fnUserService; - private final EpUserRolesRequestService epUserRolesRequestService; - private final EpUserRolesRequestDetService epUserRolesRequestDetService; - private final EntityManager entityManager; - private final ApplicationsRestClientService applicationsRestClientService; - - @Autowired - public FnUserRoleService(FnUserRoleDao fnUserRoleDao, FnAppService fnAppService, - FnRoleService fnRoleService, - FnUserService fnUserService, - EpUserRolesRequestService epUserRolesRequestService, - EpUserRolesRequestDetService epUserRolesRequestDetService, - EntityManager entityManager, - ApplicationsRestClientService applicationsRestClientService) { - this.fnUserRoleDao = fnUserRoleDao; - this.fnAppService = fnAppService; - this.fnRoleService = fnRoleService; - this.fnUserService = fnUserService; - this.epUserRolesRequestService = epUserRolesRequestService; - this.epUserRolesRequestDetService = epUserRolesRequestDetService; - this.entityManager = entityManager; - this.applicationsRestClientService = applicationsRestClientService; - } - - public List getAdminUserRoles(final Long userId, final Long roleId, final Long appId) { - return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>()); - } - - public boolean isSuperAdmin(final String orgUserId, final Long roleId, final Long appId) { - List roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream() - .filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList()); - return !roles.isEmpty(); - } - - private List getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) { - return Optional.of(fnUserRoleDao.getUserRolesForRoleIdAndAppId(roleId, appId)).orElse(new ArrayList<>()); - } - - public FnUserRole saveOne(final FnUserRole fnUserRole) { - return fnUserRoleDao.save(fnUserRole); - } - - public ExternalSystemAccess getExternalRequestAccess() { - ExternalSystemAccess res = null; - try { - res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE, - Boolean.parseBoolean( - SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE))); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage()); - } - return res; - } - - public List getUserAppCatalogRoles(FnUser userid, String appName) { - List tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class) - .setParameter("userid", userid.getUserId()) - .setParameter("appName", appName) - .getResultList(); - return tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList()); - } - - private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) { - return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"), - (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId")); - } - - private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData, - ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId) - throws JsonProcessingException, HTTPException { - boolean result = false; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - String userRolesAsString = mapper.writeValueAsString(userAppRolesData); - logger.error(EELFLoggerDelegate.errorLogger, - "Should not be reached here, as the endpoint is not defined yet from the Mylogins"); - applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, - String.format("/user/%s/myLoginroles", userId)); - return result; - } - - public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) { - FieldsValidator fieldsValidator = new FieldsValidator(); - List appRole; - try { - logger.error(EELFLoggerDelegate.errorLogger, - "Should not be reached here, still the endpoint is yet to be defined"); - boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService, - newAppRolesForUser.getAppId(), user.getId()); - logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result); - FnApp app = fnAppService.getById(newAppRolesForUser.getAppId()); - EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest(); - epUserRolesRequest.setCreatedDate(LocalDateTime.now()); - epUserRolesRequest.setUpdatedDate(LocalDateTime.now()); - epUserRolesRequest.setUserId(user); - epUserRolesRequest.setAppId(app); - epUserRolesRequest.setRequestStatus("P"); - List appRoleIdList = newAppRolesForUser.getAppRoles(); - Set appRoleDetails = new LinkedHashSet<>(); - epUserRolesRequestService.saveOne(epUserRolesRequest); - for (RoleInAppForUser userAppRoles : appRoleIdList) { - Boolean isAppliedVal = userAppRoles.getIsApplied(); - if (isAppliedVal) { - appRole = fnRoleService - .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(), - userAppRoles.getRoleId()); - if (!appRole.isEmpty()) { - EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet(); - epAppRoleDetail.setRequestedRoleId(appRole.get(0)); - epAppRoleDetail.setRequestType("P"); - epAppRoleDetail.setReqId(epUserRolesRequest); - epUserRolesRequestDetService.saveOne(epAppRoleDetail); - } - } - } - epUserRolesRequest.setEpRequestIdDetail(appRoleDetails); - fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK); - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e); - fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - return fieldsValidator; - } - - public List importRolesFromRemoteApplication(Long appId) throws HTTPException { - FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull"); - List rolesList = Arrays.asList(appRolesFull); - for (FnRole externalAppRole : rolesList) { - - // Try to find an existing extern role for the app in the local - // onap DB. If so, then use its id to update the existing external - // application role record. - Long externAppId = externalAppRole.getId(); - FnRole existingAppRole = fnRoleService.getRole(appId, externAppId); - if (existingAppRole != null) { - logger.debug(EELFLoggerDelegate.debugLogger, - String.format( - "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", - appId, externAppId)); - continue; - } - // persistExternalRoleInEcompDb(externalAppRole, appId, - // roleService); - } - - return rolesList; - } - - public List getUsersFromAppEndpoint(Long appId) throws HTTPException { - ArrayList userApplicationRoles = new ArrayList<>(); - - FnApp app = fnAppService.getById(appId); - //If local or centralized application - if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) { - List userList = fnUserService.getActiveUsers(); - for (FnUser user : userList) { - UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app); - if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) { - userApplicationRoles.add(userWithAppRoles); - } - } - - } - // remote app - else { - RemoteUserWithRoles[] remoteUsers = null; - String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users"); - - remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString); - - userApplicationRoles = new ArrayList<>(); - for (RemoteUserWithRoles remoteUser : remoteUsers) { - UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, - remoteUser); - if (userWithRemoteAppRoles.getRoles() != null - && userWithRemoteAppRoles.getRoles().size() > 0) { - userApplicationRoles.add(userWithRemoteAppRoles); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, - "User " + userWithRemoteAppRoles.getOrgUserId() - + " doesn't have any roles assigned to any app."); - } - } - } - - return userApplicationRoles; - } - - private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) { - UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); - userWithRemoteAppRoles.setAppId(appId); - userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId()); - userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName()); - userWithRemoteAppRoles.setLastName(remoteUser.getLastName()); - userWithRemoteAppRoles.setRoles(remoteUser.getRoles()); - return userWithRemoteAppRoles; - } - - private boolean isAppUpgradeVersion(FnApp app) { - return true; - } - - private RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) { - - ObjectMapper mapper = new ObjectMapper(); - try { - return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, - "doGetUsers : Failed : Unexpected property in incoming JSON", - e); - logger.error(EELFLoggerDelegate.errorLogger, - "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString); - } - - return new RemoteUserWithRoles[0]; - } - - private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) { - UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); - userWithRemoteAppRoles.setAppId(appId); - userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId()); - userWithRemoteAppRoles.setFirstName(user.getFirstName()); - userWithRemoteAppRoles.setLastName(user.getLastName()); - userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app)); - return userWithRemoteAppRoles; - } - - private List convertToRemoteRoleList(FnUser user, FnApp app) { - List roleList = new ArrayList<>(); - SortedSet roleSet = user.getAppEPRoles(app); - for (FnRole role : roleSet) { - logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getRoleName()); - RemoteRole rRole = new RemoteRole(); - rRole.setId(role.getId()); - rRole.setName(role.getRoleName()); - roleList.add(rRole); - } - - //Get the active roles of user for that application using query - List userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId()); - - for (FnRole remoteUserRoleList : userEpRoleList) { - - RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId())) - .findAny().orElse(null); - if (remoteRoleListId == null) { - logger.debug(EELFLoggerDelegate.debugLogger, - "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(), - - remoteUserRoleList.getRoleName()); - RemoteRole role = new RemoteRole(); - role.setId(remoteUserRoleList.getId()); - role.setName(remoteUserRoleList.getRoleName()); - - roleList.add(role); - } - - } - - logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size()); - - return roleList; - - - - } + private static final String GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS = + "select\n" + + " distinct ep.function_cd functionCd\n" + + "from\n" + + " fn_user_role fu,\n" + + " ep_app_role_function ep,\n" + + " ep_app_function ea\n" + + "where\n" + + " fu.role_id = ep.role_id\n" + + " and fu.app_id = ep.app_id\n" + + " and fu.user_id = 'userId'\n" + + " and ea.function_cd = ep.function_cd\n" + + " and exists (\n" + + " select\n" + + " fa.app_id\n" + + " from\n" + + " fn_user fu,\n" + + " fn_user_role ur,\n" + + " fn_app fa\n" + + " where\n" + + " fu.user_id = 'userId'\n" + + " and fu.user_id = ur.user_id\n" + + " and ur.app_id = fa.app_id\n" + + " and fa.enabled = 'Y'\n" + + " )"; + + private static final String USER_APP_CATALOG_ROLES = + "select\n" + + " A.reqId as reqId,\n" + + " B.requestedRoleId.roleId as requestedRoleId,\n" + + " A.requestStatus as requestStatus,\n" + + " A.appId.appId as appId,\n" + + " (\n" + + " select\n" + + " roleName\n" + + " from\n" + + " FnRole\n" + + " where\n" + + " roleId = B.requestedRoleId.roleId\n" + + " ) as roleName\n" + + "from\n" + + " EpUserRolesRequest A\n" + + " left join EpUserRolesRequestDet B on A.reqId = B.reqId.reqId\n" + + "where\n" + + " A.userId.userId = :userid\n" + + " and A.appId IN (\n" + + " select\n" + + " appId\n" + + " from\n" + + " FnApp\n" + + " where\n" + + " appName = :appName\n" + + " )\n" + + " and A.requestStatus = 'P'\n"; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class); + + private final FnUserRoleDao fnUserRoleDao; + private final FnAppService fnAppService; + private final FnRoleService fnRoleService; + private final FnUserService fnUserService; + private final EpUserRolesRequestService epUserRolesRequestService; + private final EpUserRolesRequestDetService epUserRolesRequestDetService; + private final EntityManager entityManager; + private final ApplicationsRestClientService applicationsRestClientService; + + @Autowired + public FnUserRoleService(FnUserRoleDao + fnUserRoleDao, + FnAppService fnAppService, + FnRoleService fnRoleService, + FnUserService fnUserService, + EpUserRolesRequestService epUserRolesRequestService, + EpUserRolesRequestDetService epUserRolesRequestDetService, + EntityManager entityManager, + ApplicationsRestClientService applicationsRestClientService) { + this.fnUserRoleDao = fnUserRoleDao; + this.fnAppService = fnAppService; + this.fnRoleService = fnRoleService; + this.fnUserService = fnUserService; + this.epUserRolesRequestService = epUserRolesRequestService; + this.epUserRolesRequestDetService = epUserRolesRequestDetService; + this.entityManager = entityManager; + this.applicationsRestClientService = applicationsRestClientService; + } + + public List getAdminUserRoles(final Long userId, final Long roleId, final Long appId) { + return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>()); + } + + public boolean isSuperAdmin(final String orgUserId, final Long roleId, final Long appId) { + List roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream() + .filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList()); + return !roles.isEmpty(); + } + + private List getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId) { + return Optional.of(fnUserRoleDao.getUserRolesForRoleIdAndAppId(roleId, appId)).orElse(new ArrayList<>()); + } + + public FnUserRole saveOne(final FnUserRole fnUserRole) { + return fnUserRoleDao.save(fnUserRole); + } + + public ExternalSystemAccess getExternalRequestAccess() { + ExternalSystemAccess res = null; + try { + res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE, + Boolean.parseBoolean( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE))); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage()); + } + return res; + } + + public List getUserAppCatalogRoles(FnUser userid, String appName) { + List tuples = entityManager.createQuery(USER_APP_CATALOG_ROLES, Tuple.class) + .setParameter("userid", userid.getUserId()) + .setParameter("appName", appName) + .getResultList(); + return Optional.of(tuples.stream().map(this::tupleToEPUserAppCatalogRoles).collect(Collectors.toList())) + .orElse(new ArrayList<>()); + } + + private EPUserAppCatalogRoles tupleToEPUserAppCatalogRoles(Tuple tuple) { + return new EPUserAppCatalogRoles((Long) tuple.get("reqId"), (Long) tuple.get("requestedRoleId"), + (String) tuple.get("roleName"), (String) tuple.get("requestStatus"), (Long) tuple.get("appId")); + } + + private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData, + ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId) + throws JsonProcessingException, HTTPException { + boolean result = false; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userRolesAsString = mapper.writeValueAsString(userAppRolesData); + logger.error(EELFLoggerDelegate.errorLogger, + "Should not be reached here, as the endpoint is not defined yet from the Mylogins"); + applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, + String.format("/user/%s/myLoginroles", userId)); + return result; + } + + public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser newAppRolesForUser, FnUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + List appRole; + try { + logger.error(EELFLoggerDelegate.errorLogger, + "Should not be reached here, still the endpoint is yet to be defined"); + boolean result = postUserRolesToMylogins(newAppRolesForUser, applicationsRestClientService, + newAppRolesForUser.getAppId(), user.getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "putUserAppRolesRequest: result {}", result); + FnApp app = fnAppService.getById(newAppRolesForUser.getAppId()); + EpUserRolesRequest epUserRolesRequest = new EpUserRolesRequest(); + epUserRolesRequest.setCreatedDate(LocalDateTime.now()); + epUserRolesRequest.setUpdatedDate(LocalDateTime.now()); + epUserRolesRequest.setUserId(user); + epUserRolesRequest.setAppId(app); + epUserRolesRequest.setRequestStatus("P"); + List appRoleIdList = newAppRolesForUser.getAppRoles(); + Set appRoleDetails = new LinkedHashSet<>(); + epUserRolesRequestService.saveOne(epUserRolesRequest); + for (RoleInAppForUser userAppRoles : appRoleIdList) { + Boolean isAppliedVal = userAppRoles.getIsApplied(); + if (isAppliedVal) { + appRole = fnRoleService + .retrieveAppRoleByAppRoleIdAndByAppId(newAppRolesForUser.getAppId(), + userAppRoles.getRoleId()); + if (!appRole.isEmpty()) { + EpUserRolesRequestDet epAppRoleDetail = new EpUserRolesRequestDet(); + epAppRoleDetail.setRequestedRoleId(appRole.get(0)); + epAppRoleDetail.setRequestType("P"); + epAppRoleDetail.setReqId(epUserRolesRequest); + epUserRolesRequestDetService.saveOne(epAppRoleDetail); + } + } + } + epUserRolesRequest.setEpRequestIdDetail(appRoleDetails); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_OK); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + public List importRolesFromRemoteApplication(Long appId) throws HTTPException { + FnRole[] appRolesFull = applicationsRestClientService.get(FnRole[].class, appId, "/rolesFull"); + List rolesList = Arrays.asList(appRolesFull); + for (FnRole externalAppRole : rolesList) { + + // Try to find an existing extern role for the app in the local + // onap DB. If so, then use its id to update the existing external + // application role record. + Long externAppId = externalAppRole.getId(); + FnRole existingAppRole = fnRoleService.getRole(appId, externAppId); + if (existingAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, + String.format( + "ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", + appId, externAppId)); + } + } + + return rolesList; + } + + public List getUsersFromAppEndpoint(Long appId) throws HTTPException { + ArrayList userApplicationRoles = new ArrayList<>(); + + FnApp app = fnAppService.getById(appId); + //If local or centralized application + if (PortalConstants.PORTAL_APP_ID.equals(appId) || app.getAuthCentral()) { + List userList = fnUserService.getActiveUsers(); + for (FnUser user : userList) { + UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app); + if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0) { + userApplicationRoles.add(userWithAppRoles); + } + } + + } + // remote app + else { + RemoteUserWithRoles[] remoteUsers; + String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users"); + + remoteUsers = doGetUsers(remoteUsersString); + + userApplicationRoles = new ArrayList<>(); + for (RemoteUserWithRoles remoteUser : remoteUsers) { + UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, + remoteUser); + if (userWithRemoteAppRoles.getRoles() != null + && userWithRemoteAppRoles.getRoles().size() > 0) { + userApplicationRoles.add(userWithRemoteAppRoles); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, + "User " + userWithRemoteAppRoles.getOrgUserId() + + " doesn't have any roles assigned to any app."); + } + } + } + + return userApplicationRoles; + } + + private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId()); + userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName()); + userWithRemoteAppRoles.setLastName(remoteUser.getLastName()); + userWithRemoteAppRoles.setRoles(remoteUser.getRoles()); + return userWithRemoteAppRoles; + } + + private RemoteUserWithRoles[] doGetUsers(String remoteUsersString) { + + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "doGetUsers : Failed : Unexpected property in incoming JSON", + e); + logger.error(EELFLoggerDelegate.errorLogger, + "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString); + } + + return new RemoteUserWithRoles[0]; + } + + private UserApplicationRoles convertToUserApplicationRoles(Long appId, FnUser user, FnApp app) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId()); + userWithRemoteAppRoles.setFirstName(user.getFirstName()); + userWithRemoteAppRoles.setLastName(user.getLastName()); + userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app)); + return userWithRemoteAppRoles; + } + + private List convertToRemoteRoleList(FnUser user, FnApp app) { + List roleList = new ArrayList<>(); + SortedSet roleSet = user.getAppEPRoles(app); + for (FnRole role : roleSet) { + logger.debug(EELFLoggerDelegate.debugLogger, + "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), + role.getRoleName()); + RemoteRole rRole = new RemoteRole(); + rRole.setId(role.getId()); + rRole.setName(role.getRoleName()); + roleList.add(rRole); + } + + //Get the active roles of user for that application using query + List userEpRoleList = fnRoleService.getUserRoleOnUserIdAndAppId(user.getId(), app.getId()); + + for (FnRole remoteUserRoleList : userEpRoleList) { + + RemoteRole remoteRoleListId = roleList.stream() + .filter(x -> remoteUserRoleList.getId().equals(x.getId())) + .findAny().orElse(null); + if (remoteRoleListId == null) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Adding the role to the rolelist () - for user {}, found Name {}", + user.getOrgUserId(), + + remoteUserRoleList.getRoleName()); + RemoteRole role = new RemoteRole(); + role.setId(remoteUserRoleList.getId()); + role.setName(remoteUserRoleList.getRoleName()); + + roleList.add(role); + } + + } + + logger.debug(EELFLoggerDelegate.debugLogger, + "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), + roleList.size()); + return roleList; + } + + public List getRoleFunctionsOfUserforAlltheApplications(Long userId) { + List tuples = entityManager + .createQuery(GET_ROLE_FUNCTIONS_OF_USERFOR_ALLTHE_APPLICATIONS, Tuple.class) + .setParameter("userid", userId) + .getResultList(); + return Optional.of(tuples.stream().map(tuple -> tuple.get("functionCd")).collect(Collectors.toList())) + .orElse(new ArrayList<>()); + } + + public List retrieveByAppIdAndUserId(final Long appId, final String userId) { + return Optional.of(fnUserRoleDao.retrieveByAppIdAndUserId(appId, userId)).orElse(new ArrayList<>()); + } + + public String updateRemoteUserProfile(String orgUserId, long appId) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + FnUser client = fnUserService.loadUserByUsername(orgUserId); + FnUser newUser = new FnUser(); + newUser.setActiveYn(client.getActiveYn()); + newUser.setFirstName(client.getFirstName()); + newUser.setLastName(client.getLastName()); + newUser.setLoginId(client.getLoginId()); + newUser.setLoginPwd(client.getLoginPwd()); + newUser.setMiddleName(client.getMiddleName()); + newUser.setEmail(client.getEmail()); + newUser.setOrgUserId(client.getLoginId()); + try { + String userAsString = mapper.writeValueAsString(newUser); + List appList = fnAppService.getUserRemoteApps(client.getId().toString()); + // applicationsRestClientService.post(EPUser.class, appId, + // userAsString, String.format("/user", orgUserId)); + for (FnApp eachApp : appList) { + try { + applicationsRestClientService.post(FnUser.class, eachApp.getId(), userAsString, + String.format("/user/%s", orgUserId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId() + + " in remote app. appId = " + eachApp.getId()); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e); + return "failure"; + } + return "success"; + } + + public void deleteById(final Long id) { + fnUserRoleDao.deleteById(id); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java index 5c1c84b5..01da50de 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java @@ -40,17 +40,11 @@ package org.onap.portal.service.fn; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.security.Principal; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import org.onap.portal.controller.UserRolesController; import org.onap.portal.dao.fn.FnUserDao; import org.onap.portal.domain.db.fn.FnUser; -import org.onap.portal.domain.dto.transport.UserWithNameSurnameTitle; -import org.onap.portal.utils.EcompPortalUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -73,7 +67,7 @@ public class FnUserService implements UserDetailsService { this.fnUserDao = fnUserDao; } - public FnUser saveFnUser(final Principal principal, final FnUser fnUser) { + public FnUser saveFnUser(final FnUser fnUser) { return fnUserDao.save(fnUser); } @@ -91,7 +85,7 @@ public class FnUserService implements UserDetailsService { return Optional.of(fnUserDao.getOne(id)); } - List getUserWithOrgUserId(final String orgUserIdValue) { + public List getUserWithOrgUserId(final String orgUserIdValue) { return fnUserDao.getUserWithOrgUserId(orgUserIdValue).orElse(new ArrayList<>()); } diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/old/AppsCacheService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/old/AppsCacheService.java deleted file mode 100644 index 7703420b..00000000 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/old/AppsCacheService.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * ============LICENSE_START========================================== - * ONAP Portal - * =================================================================== - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * Modifications Copyright (c) 2019 Samsung - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the "License"); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * - */ - -package org.onap.portal.service.fn.old; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import org.onap.portal.domain.db.fn.FnApp; -import org.onap.portal.domain.dto.transport.OnboardingApp; -import org.onap.portal.service.fn.FnAppService; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.stereotype.Service; - -@Service("appsCacheService") -@Configuration -@EnableAspectJAutoProxy -public class AppsCacheService { - @Autowired - private - FnAppService appsService; - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheService.class); - - final class CacheConfiguration { - - private long updateTime = 0; - private int updateInterval = 10; - - public CacheConfiguration (long _updateTime, int _updateInterval) { - updateTime = _updateTime; - updateInterval = _updateInterval; - } - } - - private CacheConfiguration quickRefreshCacheConf = null; - private CacheConfiguration slowRefreshCacheConf = null; - - - private static volatile Map appsMap; - private static volatile Map uebAppsMap; - - @PostConstruct - public void init() { - quickRefreshCacheConf = new CacheConfiguration(0, 120); - slowRefreshCacheConf = new CacheConfiguration(0, 3600); - - this.refreshAppsMap(quickRefreshCacheConf); - } - - private void refreshAppsMap(CacheConfiguration conf) { - long now = System.currentTimeMillis(); - - if(noNeedToUpdate(now, conf)) - return; - - synchronized (this) { - if(noNeedToUpdate(now, conf)) - return; - List allApps = appsService.getAppsFullList(); - Map newAppsMap = new HashMap<>(); - for (FnApp app : allApps) { - newAppsMap.put(app.getId(), app); - } - - Map newUebAppsMap = new HashMap<>(); - for (FnApp app : allApps) { - newUebAppsMap.put(app.getUebKey(), app); - } - // Switch cache with the new one. - appsMap = newAppsMap; - uebAppsMap = newUebAppsMap; - conf.updateTime = now; - } - - } - - private boolean noNeedToUpdate(long now, CacheConfiguration conf) { - long secondsPassed = (now - conf.updateTime)/1000; - if(secondsPassed < conf.updateInterval){ - logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + conf.updateInterval); - return true; // no need to update cache - } - return false; // its time to update - } - - public String getAppEndpoint(Long appId) { - refreshAppsMap(quickRefreshCacheConf); - FnApp app = appsMap.get(appId); - if(app != null) - return app.getAppRestEndpoint(); - return null; - } - - public List getAppsFullList() { - refreshAppsMap(quickRefreshCacheConf); - List appList = new ArrayList<>(appsMap.values()); - appList.removeIf(app -> app.getId() == 1); - List appsFinalList = appList.stream() - .filter(app -> app.getEnabled() && !app.getOpen()).collect(Collectors.toList()); - - List onboardingAppsList = new ArrayList<>(); - for (FnApp app : appsFinalList) { - OnboardingApp onboardingApp = new OnboardingApp(); - appsService.createOnboardingFromApp(app, onboardingApp); - onboardingAppsList.add(onboardingApp); - } - return onboardingAppsList; - } - - public FnApp getApp(Long appId) { - refreshAppsMap(quickRefreshCacheConf); - FnApp app = appsMap.get(appId); - return app; - } - - public FnApp getAppFromUeb(String appKey) { - return getAppFromUeb(appKey,0); - } - - public FnApp getAppFromUeb(String appKey, Integer quickCacheRefresh) { - refreshAppsMap(quickCacheRefresh == 1 ? quickRefreshCacheConf:slowRefreshCacheConf); - FnApp app = uebAppsMap.get(appKey); - return app; - } - -} diff --git a/portal-BE/src/main/java/org/onap/portal/utils/EPUserUtils.java b/portal-BE/src/main/java/org/onap/portal/utils/EPUserUtils.java index b72a8297..968e64f4 100644 --- a/portal-BE/src/main/java/org/onap/portal/utils/EPUserUtils.java +++ b/portal-BE/src/main/java/org/onap/portal/utils/EPUserUtils.java @@ -58,6 +58,7 @@ import lombok.NoArgsConstructor; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.onap.portal.domain.db.fn.FnRole; +import org.onap.portal.domain.db.fn.FnRoleComposite; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.db.fn.FnUserRole; import org.onap.portal.exception.RoleFunctionException; @@ -249,7 +250,7 @@ public class EPUserUtils { // Additionally; the account admin role is overloaded between onap // portal and partners; lets also include that - for (FnUserRole epUserApp : user.getFnUserRoles()) { + for (FnUserRole epUserApp : user.getUserApps()) { FnRole role = epUserApp.getRoleId(); if (role.getActiveYn() && role.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) { @@ -272,8 +273,8 @@ public class EPUserUtils { */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void addChildRoles(FnRole role, HashMap roles) { - Set childRoles = role.getFnRoles(); - if (childRoles != null && !childRoles.isEmpty()) { + Set childRoles = role.getChildRoles().stream().map(FnRoleComposite::getChildRoles).collect(Collectors.toSet()); + if (!childRoles.isEmpty()) { for (Object o : childRoles) { FnRole childRole = (FnRole) o; if (childRole.getActiveYn()) { diff --git a/portal-BE/src/test/java/org/onap/portal/controller/WidgetsCatalogControllerTest.java b/portal-BE/src/test/java/org/onap/portal/controller/WidgetsCatalogControllerTest.java index b82ac2f7..1eb88012 100644 --- a/portal-BE/src/test/java/org/onap/portal/controller/WidgetsCatalogControllerTest.java +++ b/portal-BE/src/test/java/org/onap/portal/controller/WidgetsCatalogControllerTest.java @@ -265,6 +265,7 @@ public class WidgetsCatalogControllerTest { .modifiedDate(LocalDateTime.now()) .createdDate(LocalDateTime.now()) .isInternalYn(true) + .isSystemUser(true) .guest(false) .build(); } diff --git a/portal-BE/src/test/java/org/onap/portal/controller/WidgetsControllerTest.java b/portal-BE/src/test/java/org/onap/portal/controller/WidgetsControllerTest.java index ebc0d9fa..8d984c06 100644 --- a/portal-BE/src/test/java/org/onap/portal/controller/WidgetsControllerTest.java +++ b/portal-BE/src/test/java/org/onap/portal/controller/WidgetsControllerTest.java @@ -364,6 +364,7 @@ public class WidgetsControllerTest { .modifiedDate(LocalDateTime.now()) .isInternalYn(true) .languageId(language) + .isSystemUser(true) .guest(true) .build(); } @@ -377,6 +378,7 @@ public class WidgetsControllerTest { .createdDate(LocalDateTime.now()) .modifiedDate(LocalDateTime.now()) .isInternalYn(true) + .isSystemUser(true) .languageId(language) .guest(false) .build(); diff --git a/portal-BE/src/test/java/org/onap/portal/service/ep/EpWidgetCatalogParameterServiceTest.java b/portal-BE/src/test/java/org/onap/portal/service/ep/EpWidgetCatalogParameterServiceTest.java index 6a6c06b9..50e09b3e 100644 --- a/portal-BE/src/test/java/org/onap/portal/service/ep/EpWidgetCatalogParameterServiceTest.java +++ b/portal-BE/src/test/java/org/onap/portal/service/ep/EpWidgetCatalogParameterServiceTest.java @@ -162,6 +162,7 @@ class EpWidgetCatalogParameterServiceTest { .modifiedDate(LocalDateTime.now()) .createdDate(LocalDateTime.now()) .isInternalYn(true) + .isSystemUser(true) .guest(false) .build(); } diff --git a/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserRoleServiceTest.java b/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserRoleServiceTest.java index bdbc2c03..b82c61eb 100644 --- a/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserRoleServiceTest.java +++ b/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserRoleServiceTest.java @@ -75,4 +75,6 @@ class FnUserRoleServiceTest { assertEquals(expected, actual); } + + } \ No newline at end of file diff --git a/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java b/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java index e4083881..2e16a4fb 100644 --- a/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java +++ b/portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java @@ -91,6 +91,7 @@ class FnUserServiceTest { expected.setModifiedDate(LocalDateTime.parse("2019-08-08T12:18:17")); expected.setIsInternalYn(false); expected.setStateCd("NJ"); + expected.setIsSystemUser(true); expected.setCountryCd("US"); expected.setLanguageId(language); expected.setGuest(false); @@ -99,7 +100,7 @@ class FnUserServiceTest { language.getFnUsers().add(expected); //When - fnUserService.saveFnUser(principal, expected); + fnUserService.saveFnUser(expected); FnUser actual = fnUserService.getUser(expected.getUserId()).get(); //Then assertEquals(expected.getUserId(), actual.getUserId());