diff options
author | 2019-10-10 09:35:19 +0200 | |
---|---|---|
committer | 2019-10-10 09:35:27 +0200 | |
commit | 009040bc056dee5e26e43244422e8e0b9c47144a (patch) | |
tree | 784c97a3207afae33e26b0793e1c8b790df4b659 /portal-BE/src/main/java | |
parent | 0cd9645a9dc83b9a5a2eddcc15cdfaf30fdade3a (diff) |
UserRolesController up + tests
UserRolesController checkIfUserIsSuperAdmin up + tests
Issue-ID: PORTAL-710
Change-Id: I1e483f2aafa064bbe9b98b46bb9c45e07b265978
Signed-off-by: Dominik Mizyn <d.mizyn@samsung.com>
Diffstat (limited to 'portal-BE/src/main/java')
15 files changed, 790 insertions, 43 deletions
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 new file mode 100644 index 00000000..fdd1de24 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java @@ -0,0 +1,536 @@ +/* + * ============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.controller; + +import java.security.Principal; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.service.AdminRolesService; +import org.onap.portal.service.fn.FnUserService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Configuration +public class UserRolesController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class); + + private final FnUserService fnUserService; + private final AdminRolesService adminRolesService; + + +/* + private final UserRolesService userRolesService; + private final ApplicationsRestClientService applicationsRestClientService; + private final SearchService searchService;*/ + + + private static final String FAILURE = "failure"; + + @Autowired + public UserRolesController(final FnUserService fnUserService, + final AdminRolesService adminRolesService) { + this.fnUserService = fnUserService; + this.adminRolesService = adminRolesService; + } + +/* + + @RequestMapping(value = {"/portalApi/queryUsers"}, method = RequestMethod.GET, produces = "application/json") + @PreAuthorize("hasRole('System_Administrator') and hasRole('Account_Administrator')") + public String getPhoneBookSearchResult(Principal principal, @RequestParam("search") String searchString, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + String searchResult = null; + if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user) + && !adminRolesService.isRoleAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult"); + } else { + searchString = searchString.trim(); + if (searchString.length() > 2) { + searchResult = searchService.searchUsersInPhoneBook(searchString); + } else { + logger.info(EELFLoggerDelegate.errorLogger, + "getPhoneBookSearchResult - too short search string: " + searchString); + } + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult); + + return searchResult; + } + + @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = { + RequestMethod.GET}, produces = "application/json") + public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(Principal principal, + @RequestParam("user") String orgUserId, HttpServletResponse response) { + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + AppsListWithAdminRole result = null; + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser"); + } else { + if (EcompPortalUtils.legitimateUserId(orgUserId)) { + result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId); + } else { + logger.info(EELFLoggerDelegate.errorLogger, + "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } + + StringBuilder adminAppRoles = new StringBuilder(); + if (result != null) { + if (!result.appsRoles.isEmpty()) { + adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {"); + for (AppNameIdIsAdmin adminAppRole : result.appsRoles) { + if (adminAppRole.isAdmin) { + adminAppRoles.append(adminAppRole.appName + ", "); + } + } + adminAppRoles.append("}."); + } else { + adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role."); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null"); + } + + logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString()); + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result); + + return result; + } + + @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = { + RequestMethod.PUT}, produces = "application/json") + public FieldsValidator putAppsWithAdminRoleStateForUser(Principal principal, + @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) { + + // newAppsListWithAdminRoles.appsRoles + FieldsValidator fieldsValidator = new FieldsValidator(); + StringBuilder newAppRoles = new StringBuilder(); + if (newAppsListWithAdminRoles != null) { + if (!newAppsListWithAdminRoles.appsRoles.isEmpty()) { + newAppRoles + .append("User '" + newAppsListWithAdminRoles.orgUserId + + "' has admin role to the apps = { "); + for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) { + if (adminAppRole.isAdmin) { + newAppRoles.append(adminAppRole.appName + " ,"); + } + } + newAppRoles.deleteCharAt(newAppRoles.length() - 1); + newAppRoles.append("}."); + } else { + newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + + "' has no Apps with Admin Role."); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null"); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString()); + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + boolean changesApplied = false; + + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser"); + } else { + changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN); + if (newAppsListWithAdminRoles != null) { + auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId); + } + auditLog.setComments( + EcompPortalUtils + .truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + if (newAppsListWithAdminRoles != null) { + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage( + "UserRolesController.putAppsWithAdminRoleStateForUser", + EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(), + newAppsListWithAdminRoles.orgUserId, newAppRoles.toString())); + } + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied); + + return fieldsValidator; + } + + + @RequestMapping(value = {"/portalApi/userAppRoles"}, method = { + RequestMethod.GET}, produces = "application/json") + public List<RoleInAppForUser> getAppRolesForUser(Principal principal, + @RequestParam("user") String orgUserId, + @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue, + @RequestParam("isSystemUser") Boolean isSystemUser, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<RoleInAppForUser> result = null; + String feErrorString = ""; + if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}", + adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user)); + EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser"); + feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus()); + } else { + if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) { + result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user); + logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", + result, appid); + int responseCode = EcompPortalUtils.getExternalAppResponseCode(); + if (responseCode != 0 && responseCode != 200) { + // external error + response.setStatus(responseCode); + feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode); + } else if (result == null) { + // If the result is null, there was an internal onap error + // in the service call. + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + feErrorString = EcompPortalUtils.getFEErrorString(true, + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } else { + logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST); + } + } + + StringBuilder sbUserApps = new StringBuilder(); + if (result != null && !result.isEmpty()) { + sbUserApps.append("User '" + orgUserId + "' has Roles={"); + for (RoleInAppForUser appRole : result) { + if (appRole.isApplied) { + sbUserApps.append(appRole.roleName + ", "); + } + } + sbUserApps.append("} assigned to the appId '" + appid + "'."); + } else { + // Not sure creating an empty object will make any difference + // but would like to give it a shot for defect #DE221057 + if (result == null) { + result = new ArrayList<>(); + } + sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles"); + } + logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString()); + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result); + if (feErrorString != "") { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString); + + response.addHeader("FEErrorString", feErrorString); + response.addHeader("Access-Control-Expose-Headers", "FEErrorString"); + } + return result; + } + + @RequestMapping(value = {"/portalApi/userAppRoles"}, method = { + RequestMethod.PUT}, produces = "application/json") + public PortalRestResponse<String> putAppWithUserRoleStateForUser(Principal principal, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { + // FieldsValidator fieldsValidator = new FieldsValidator(); + PortalRestResponse<String> 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 + " ,"); + } + } + 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"); + } 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); + } + } + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied); + return portalResponse; + } + + @RequestMapping(value = {"/portalApi/updateRemoteUserProfile"}, method = { + RequestMethod.GET}, produces = "application/json") + public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request) { + + String updateRemoteUserFlag = FAILURE; + try { + // saveNewUser = userService.saveNewUser(newUser); + String orgUserId = request.getParameter("loginId"); + Long appId = Long.parseLong(request.getParameter("appId")); + userRolesService.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<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, + @PathVariable("appId") Long appId) throws HTTPException { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId); + return userRolesService.getUsersFromAppEndpoint(appId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e); + return new ArrayList<>(); + } + } + + @RequestMapping(value = {"/portalApi/app/{appId}/roles"}, method = { + RequestMethod.GET}, produces = "application/json") + public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) + throws HTTPException { + EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + List<EcompRole> rolesList = Arrays.asList(appRoles); + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId, + rolesList); + + return rolesList; + } + + @RequestMapping(value = {"/portalApi/admin/import/app/{appId}/roles"}, method = { + RequestMethod.GET}, produces = "application/json") + public List<FnRole> importRolesFromRemoteApplication(HttpServletRequest request, + @PathVariable("appId") Long appId) + throws HTTPException { + List<FnRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles", + "response for appId=" + appId, rolesList); + + return rolesList; + } + + @RequestMapping(value = {"/portalApi/app/{appId}/user/{orgUserId}/roles"}, method = { + RequestMethod.GET}, produces = "application/json") + public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, + @PathVariable("orgUserId") String orgUserId) throws Exception { + if (!EcompPortalUtils.legitimateUserId(orgUserId)) { + String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); + } + EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", orgUserId)); + if (roles.length != 1) { + String msg = + "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); + } + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles", + "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]); + return roles[0]; + } + + @RequestMapping(value = {"/portalApi/saveUserAppRoles"}, method = { + RequestMethod.PUT}, produces = "application/json") + public FieldsValidator putAppWithUserRoleRequest(Principal principal, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { + FieldsValidator fieldsValidator = null; + try { + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e); + + } + // return fieldsValidator; + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =", + response.getStatus()); + return fieldsValidator; + } + + @RequestMapping(value = {"/portalApi/appCatalogRoles"}, method = { + RequestMethod.GET}, produces = "application/json") + public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(Principal principal, + @RequestParam("appName") String appName) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<EPUserAppCatalogRoles> userAppRoleList = null; + try { + userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e); + + } + Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator); + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList); + + return userAppRoleList; + + } + + private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = + Comparator.comparing(EPUserAppCatalogRoles::getRolename); + + @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, + produces = "application/json") + public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) { + ExternalSystemAccess result = null; + try { + result = userRolesService.getExternalRequestAccess(); + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =", + result); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "readExternalRequestAccess failed: " + e.getMessage()); + } + return result; + } +*/ + + + @RequestMapping(value = {"/portalApi/checkIfUserIsSuperAdmin"}, method = RequestMethod.GET, + produces = "application/json") + public boolean checkIfUserIsSuperAdmin(Principal principal) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + boolean isSuperAdmin = false; + try { + isSuperAdmin = adminRolesService.isSuperAdmin(user.getOrgUserId()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage()); + } + return isSuperAdmin; + } +} 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 new file mode 100644 index 00000000..c7d1c0e3 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java @@ -0,0 +1,52 @@ +/* + * ============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.fn; + +import org.onap.portal.domain.db.fn.FnRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional +public interface FnRoleDao extends JpaRepository<FnRole, Long> { + +} 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 ee1ebdd0..9c0a6fef 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 @@ -43,6 +43,7 @@ package org.onap.portal.dao.fn; import java.util.List; import java.util.Optional; import org.onap.portal.domain.db.fn.FnUserRole; +import org.onap.portal.domain.dto.ecomp.UserRole; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -54,5 +55,11 @@ import org.springframework.transaction.annotation.Transactional; public interface FnUserRoleDao extends JpaRepository<FnUserRole, Long> { @Query - Optional<List<FnUserRole>> getAdminUserRoles(final @Param("USERID") Long userId, final @Param("ROLEID") Long roleId, final @Param("APPID") Long appId); + Optional<List<FnUserRole>> getAdminUserRoles(final @Param("userId") Long userId, final @Param("roleId") Long roleId, final @Param("appId") Long appId); + + @Query + List<UserRole> isSuperAdmin(final @Param("orgUserId") String orgUserId, final @Param("roleId") Long roleId, final @Param("appId") Long appId); + + @Query + List<FnUserRole> getUserRolesForRoleIdAndAppId(final @Param("roleId") Long roleId, final @Param("appId") Long appId); } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java index 399cb55c..bada8e14 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java @@ -171,9 +171,9 @@ public class FnApp extends DomainVo implements Serializable { @SafeHtml @NotNull private String appPassword; - @Column(name = "open", length = 1, columnDefinition = "char(1) default 'N'") + @Column(name = "_open", length = 1, columnDefinition = "char(1) default 'N'") private Boolean open; - @Column(name = "ENABLED", length = 1, columnDefinition = "char(1) default 'N'") + @Column(name = "_enabled", length = 1, columnDefinition = "char(1) default 'N'") private Boolean enabled; @Column(name = "active_yn", length = 1, columnDefinition = "char(1) default 'Y'") @Pattern(regexp = "[YNyn]") @@ -181,7 +181,7 @@ public class FnApp extends DomainVo implements Serializable { @NotNull @SafeHtml private String activeYn; - @Column(name = "thumbnail", columnDefinition = "mediumblob null default null") + @Column(name = "_thumbnail", columnDefinition = "mediumblob null default null") private byte[] thumbnail; @Column(name = "app_username", length = 50) @Size(max = 50) 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 8465ce23..20589b8d 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 @@ -53,10 +53,13 @@ import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; +import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; 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 9b0727d9..ed79cb2c 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 @@ -43,6 +43,7 @@ package org.onap.portal.domain.db.fn; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Collection; +import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.CascadeType; 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 4e783764..06320c4c 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 @@ -43,6 +43,8 @@ package org.onap.portal.domain.db.fn; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.ColumnResult; +import javax.persistence.ConstructorResult; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -56,14 +58,17 @@ import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; +import javax.persistence.SqlResultSetMapping; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.Valid; import javax.validation.constraints.Digits; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.onap.portal.domain.dto.ecomp.UserRole; /* CREATE TABLE `fn_user_role` ( @@ -91,16 +96,56 @@ CREATE TABLE `fn_user_role` ( name = "FnUserRole.retrieveCachedAppRolesForUser", query = "FROM FnUserRole where user_id= :userId" + " and user_id= :userId" - + " and app_id= :appId") + + " and app_id= :appId"), + @NamedNativeQuery( + name = "FnUserRole.isSuperAdmin", + query = "SELECT" + + " user.USER_ID as userId," + + " user.org_user_id as orgUserId," + + " userrole.ROLE_ID as roleId," + + " userrole.APP_ID as appId" + + " FROM" + + " fn_user_role userrole" + + " INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID" + + " WHERE" + + " user.org_user_id = :orgUserId" + + " AND userrole.ROLE_ID =:roleId" + + " AND userrole.APP_ID =:appId", + resultSetMapping = "UserRole", + resultClass = UserRole.class + ) }) +@SqlResultSetMapping( + name = "UserRole", + classes = { + @ConstructorResult( + targetClass = UserRole.class, + columns = { + @ColumnResult(name = "userId", type = Long.class), + @ColumnResult(name = "orgUserId", type = String.class), + @ColumnResult(name = "roleId", type = Long.class), + @ColumnResult(name = "appId", type = Long.class) + } + ) + } +) + @NamedQueries({ @NamedQuery( name = "FnUserRole.getAdminUserRoles", query = "FROM FnUserRole fn " - + "WHERE fn.userId.userId = :USERID " - + "AND fn.roleId.roleId = :ROLEID " - + "AND fn.appId.appId = :APPID") + + "WHERE fn.userId.userId = :userId " + + "AND fn.roleId.roleId = :roleId " + + "AND fn.appId.appId = :appId"), + @NamedQuery( + name = "FnUserRole.getUserRolesForRoleIdAndAppId", + query = "FROM\n" + + " FnUserRole userrole\n" + + "WHERE\n" + + " userrole.roleId.roleId = :roleId\n" + + " AND userrole.appId.appId = :appId" + ) }) @Table( @@ -114,7 +159,7 @@ CREATE TABLE `fn_user_role` ( }) @NoArgsConstructor @AllArgsConstructor - +@Builder @Getter @Setter @Entity diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java index 75b4b2d7..824ea0a1 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java @@ -54,11 +54,18 @@ public class UserRole implements Serializable { private static final long serialVersionUID = 1L; - private Long user_Id; - private Long roleId; + private Long userId; private String orgUserId; + private Long roleId; + private Long appId; private String firstName; private String lastName; private String roleName; + public UserRole(Long userId, String orgUserId, Long roleId, Long appId) { + this.userId = userId; + this.orgUserId = orgUserId; + this.roleId = roleId; + this.appId = appId; + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java index 3b435e89..9b7e6a73 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java @@ -66,7 +66,7 @@ public class UserRoles implements Serializable { setOrgUserId(user.getOrgUserId()); setFirstName(user.getFirstName()); setLastName(user.getLastName()); - setGuestSession(user.getUser_Id() == -1); + setGuestSession(user.getUserId() == -1); addRole(user.getRoleName()); } 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 90a28df2..88e379ab 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 @@ -50,12 +50,15 @@ import org.onap.portal.domain.db.fn.FnUserRole; import org.onap.portal.domain.dto.ecomp.UserRole; import org.onap.portal.logging.format.EPAppMessagesEnum; import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.fn.FnUserRoleService; import org.onap.portal.service.fn.FnUserService; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service +@Transactional public class AdminRolesService { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); @@ -63,36 +66,31 @@ public class AdminRolesService { 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 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, - FnUserService fnUserService) { + final FnUserService fnUserService, final FnUserRoleService fnUserRoleService) { this.entityManager = entityManager; this.fnUserService = fnUserService; + this.fnUserRoleService = fnUserRoleService; } - public boolean isSuperAdmin(FnUser user) { - if ((user != null) && (user.getOrgUserId() != null)) { - String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole " - + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '" - + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' " - + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';"; - try { - List userRoleList = entityManager.createNativeQuery(sql, UserRole.class).getResultList(); - if (userRoleList != null && userRoleList.size() > 0) { - return true; - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while executing isSuperAdmin operation", e); - } + 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; } - return false; + logger.info("isSuperAdmin " + isSuperAdmin); + return isSuperAdmin; } public boolean isAccountAdmin(FnUser user) { @@ -102,21 +100,27 @@ public class AdminRolesService { logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); List<Integer> 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()); - + 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()); + 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", + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isAccountAdmin operation", e); } return false; @@ -129,7 +133,8 @@ public class AdminRolesService { 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.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId() + .equals(ACCOUNT_ADMIN_ROLE_ID)) { if (role.getActiveYn()) { return true; } @@ -139,7 +144,8 @@ public class AdminRolesService { } } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", + e); } return false; } diff --git a/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java b/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java index ba5deaa4..4b037919 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java @@ -72,7 +72,7 @@ public class WidgetService { " new org.onap.portal.domain.dto.transport.OnboardingWidget(" + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID," + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT," - + "widget.WDG_URL) widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"; + + "widget.WDG_URL, widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL) from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"; private static final String urlField = "url"; private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long( @@ -96,7 +96,7 @@ public class WidgetService { private static final Object syncRests = new Object(); public List<OnboardingWidget> getOnboardingWidgets(FnUser user, boolean managed) { - if (adminRolesService.isSuperAdmin(user)) { + if (adminRolesService.isSuperAdmin(user.getOrgUserId())) { return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList(); } else if (managed) { if (adminRolesService.isAccountAdmin(user)) { @@ -232,7 +232,7 @@ public class WidgetService { synchronized (syncRests) { FnWidget widget = fnWidgetDao.getOne(onboardingWidgetId); if (widget != null && widget.getAppId() != null) { // widget exists - if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getUserId(), + if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user.getOrgUserId()), user.getUserId(), widget.getAppId())) { fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN); } else { 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 75b32dd3..d8d88c97 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 @@ -41,6 +41,8 @@ package org.onap.portal.service.fn; import java.util.List; +import java.util.Optional; +import javax.persistence.EntityExistsException; import org.onap.portal.dao.fn.FnAppDao; import org.onap.portal.domain.db.fn.FnApp; import org.onap.portal.domain.dto.transport.OnboardingApp; @@ -67,6 +69,10 @@ public class FnAppService { return fnAppDao.findAll(); } + public FnApp getById(final Long id){ + return Optional.of(fnAppDao.getOne(id)).orElseThrow(EntityExistsException::new); + } + public void createOnboardingFromApp(FnApp app, OnboardingApp onboardingApp) { onboardingApp.setId(app.getId()); onboardingApp.setName(app.getAppName()); 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 new file mode 100644 index 00000000..539d4bdc --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java @@ -0,0 +1,63 @@ +/* + * ============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; + +import javax.persistence.EntityExistsException; +import org.onap.portal.dao.fn.FnRoleDao; +import org.onap.portal.domain.db.fn.FnRole; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FnRoleService { + private final FnRoleDao fnRoleDao; + + @Autowired + public FnRoleService(FnRoleDao fnRoleDao) { + this.fnRoleDao = fnRoleDao; + } + + public FnRole getById(final Long id){ + return fnRoleDao.findById(id).orElseThrow(EntityExistsException::new); + } +} 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 4b24f9f3..9f136df3 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 @@ -41,9 +41,13 @@ package org.onap.portal.service.fn; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import org.onap.portal.dao.fn.FnUserRoleDao; import org.onap.portal.domain.db.fn.FnUserRole; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -51,7 +55,7 @@ import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class FnUserRoleService { - + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class); private final FnUserRoleDao fnUserRoleDao; @Autowired @@ -62,4 +66,17 @@ public class FnUserRoleService { public List<FnUserRole> 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<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream().filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList()); + return !roles.isEmpty(); + } + + private List<FnUserRole> 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); + } } 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 855e827d..0565fc5d 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 @@ -103,4 +103,8 @@ public class FnUserService implements UserDetailsService { public boolean existById(final Long userId) { return fnUserDao.existsById(userId); } + + public List<FnUser> findAll(){ + return fnUserDao.findAll(); + } } |