diff options
author | Dominik Mizyn <d.mizyn@samsung.com> | 2020-03-04 13:32:22 +0100 |
---|---|---|
committer | Dominik Mizyn <d.mizyn@samsung.com> | 2020-03-04 13:32:26 +0100 |
commit | ba32fe77c7874fdfe7888d1c9b2e28005f1fa9a3 (patch) | |
tree | 537faf6114c04b76fa101732c6f60596818cf97a | |
parent | 7929b78e2d59904a847f4498242a55096eb2dac8 (diff) |
PortalAdminController up
PortalAdminController up and all needed services
Issue-ID: PORTAL-710
Change-Id: I5a835454b56e1b51cb502b1dd037cdd9c55355af
Signed-off-by: Dominik Mizyn <d.mizyn@samsung.com>
6 files changed, 554 insertions, 12 deletions
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/PortalAdminController.java b/portal-BE/src/main/java/org/onap/portal/controller/PortalAdminController.java new file mode 100644 index 00000000..b9477185 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/PortalAdminController.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portal.controller; + +import java.security.Principal; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.domain.db.fn.FnRole; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.ecomp.EcompAuditLog; +import org.onap.portal.domain.dto.transport.FieldsValidator; +import org.onap.portal.domain.dto.transport.PortalAdmin; +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.PortalAdminService; +import org.onap.portal.service.user.FnUserService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portal.validation.DataValidator; +import org.onap.portal.validation.SecureString; +import org.onap.portalsdk.core.domain.AuditLog; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.AuditService; +import org.onap.portalsdk.core.service.AuditServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Configuration +@EnableAspectJAutoProxy +public class PortalAdminController { + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class); + private static final DataValidator DATA_VALIDATOR = new DataValidator(); + + private PortalAdminService portalAdminService; + private final FnUserService fnUserService; + private AdminRolesService adminRolesService; + private AuditServiceImpl auditService = new AuditServiceImpl(); + + @Autowired + public PortalAdminController(PortalAdminService portalAdminService, + FnUserService fnUserService, AdminRolesService adminRolesService) { + this.portalAdminService = portalAdminService; + this.fnUserService = fnUserService; + this.adminRolesService = adminRolesService; + } + + @RequestMapping(value = {"/portalApi/portalAdmins"}, method = RequestMethod.GET, produces = "application/json") + public List<PortalAdmin> getPortalAdmins(Principal principal, HttpServletRequest request, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<PortalAdmin> portalAdmins = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user"); + EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins"); + } else if (!adminRolesService.isSuperAdmin(user.getLoginId())) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + // return the list of portal admins + portalAdmins = portalAdminService.getPortalAdmins(); + logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()"); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins); + } + + return portalAdmins; + } + + @RequestMapping(value = {"/portalApi/portalAdmin"}, method = RequestMethod.POST) + public FieldsValidator createPortalAdmin(Principal principal, HttpServletRequest request, + @RequestBody String userId, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + FieldsValidator fieldsValidator = null; + if (!DATA_VALIDATOR.isValid(new SecureString(userId))) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin not valid userId"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else if (!adminRolesService.isSuperAdmin(user.getLoginId())) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + fieldsValidator = portalAdminService.createPortalAdmin(userId); + int statusCode = fieldsValidator.getHttpStatusCode().intValue(); + response.setStatus(statusCode); + if (statusCode == 200) { + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN); + auditLog.setAffectedRecordId(userId); + try { + auditService.logActivity(auditLog, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin: failed for save audit log", e); + } + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin", + EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), userId, + "A new Portal Admin has been added")); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = {"/portalApi/portalAdmin/{userInfo}"}, method = RequestMethod.DELETE) + public FieldsValidator deletePortalAdmin(Principal principal, HttpServletRequest request, + @PathVariable("userInfo") String userInfo, + HttpServletResponse response) { + if (!DATA_VALIDATOR.isValid(new SecureString(userInfo))) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.deletePortalAdmin not valid userId"); + return null; + } + int userIdIdx = userInfo.indexOf("-"); + Long userId = null; + String sbcid = null; + FieldsValidator fieldsValidator = null; + try { + if (userIdIdx == -1) { + logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin missing userId"); + return fieldsValidator; + } else { + String userIdStr = userInfo.substring(0, userIdIdx); + userId = Long.valueOf(userIdStr); + sbcid = userInfo.substring(userIdIdx + 1, userInfo.length()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin error while parsing the userInfo", e); + } + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + if (!adminRolesService.isSuperAdmin(user.getLoginId())) { + EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin"); + } else { + fieldsValidator = portalAdminService.deletePortalAdmin(userId); + int statusCode = fieldsValidator.getHttpStatusCode().intValue(); + response.setStatus(statusCode); + if (statusCode == 200) { + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN); + auditLog.setAffectedRecordId(sbcid); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin", + EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid, + "A Portal Admin has been deleted")); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = { + "/portalApi/adminAppsRoles/{appId}"}, method = RequestMethod.GET, produces = "application/json") + public List<FnRole> getRolesByApp(Principal principal, HttpServletRequest request, + @PathVariable("appId") Long appId, HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<FnRole> rolesByApp = null; + try { + if (user == null) { + EcompPortalUtils.setBadPermissions(user, response, "getUserApps"); + } else { + rolesByApp = adminRolesService.getRolesByApp(appId); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRolesByApp failed", e); + } + return rolesByApp; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/PortalAdmin.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/PortalAdmin.java index c68f5a26..b967b2d0 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/PortalAdmin.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/PortalAdmin.java @@ -41,6 +41,11 @@ package org.onap.portal.domain.dto.transport; import java.io.Serializable; +import javax.persistence.ColumnResult; +import javax.persistence.ConstructorResult; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; +import javax.persistence.SqlResultSetMapping; import javax.validation.constraints.Digits; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; @@ -49,24 +54,63 @@ import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.validator.constraints.SafeHtml; + +@NamedNativeQuery( + name = "PortalAdmin.PortalAdminDTO", + query = "SELECT " + + "u.id AS userId, " + + "u.loginId AS loginId " + + "u.firstName AS firstName " + + "u.lastName AS lastName " + + "FROM " + + "FnUser u, " + + "FnUserRole ur " + + "WHERE u.activeYn = 'true' AND u.user_id = ur.user_id AND ur.role_id= :adminRoleId", + resultSetMapping = "PortalAdminDTO") +@NamedNativeQuery( + name = "PortalAdmin.ActivePortalAdminDTO", + query = "SELECT " + + "u.id AS userId, " + + "u.loginId AS loginId " + + "u.firstName AS firstName " + + "u.lastName AS lastName " + + "FROM fn_user u, fn_user_role ur " + + "WHERE u.user_id = ur.user_id " + + "AND ur.user_id= :userId " + + "AND ur.role_id=:SYS_ADMIN_ROLE_ID", + resultSetMapping = "PortalAdminDTO") + +@SqlResultSetMapping( + name = "PortalAdminDTO", + classes = @ConstructorResult( + targetClass = PortalAdmin.class, + columns = { + @ColumnResult(name = "userId"), + @ColumnResult(name = "loginId"), + @ColumnResult(name = "firstName"), + @ColumnResult(name = "lastName") + } + ) +) + @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class PortalAdmin implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Digits(integer = 11, fraction = 0) - private Long userId; - @Size(max = 25) - @SafeHtml - private String loginId; - @Size(max = 50) - @SafeHtml - private String firstName; - @Size(max = 50) - @SafeHtml - private String lastName; + @Digits(integer = 11, fraction = 0) + private Long userId; + @Size(max = 25) + @SafeHtml + private String loginId; + @Size(max = 50) + @SafeHtml + private String firstName; + @Size(max = 50) + @SafeHtml + private String lastName; } diff --git a/portal-BE/src/main/java/org/onap/portal/restTemplates/AAFTemplate.java b/portal-BE/src/main/java/org/onap/portal/restTemplates/AAFTemplate.java new file mode 100644 index 00000000..420307da --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/restTemplates/AAFTemplate.java @@ -0,0 +1,31 @@ +package org.onap.portal.restTemplates; + +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +@Component +public class AAFTemplate { + + private final RestTemplate template = new RestTemplate(); + + public ResponseEntity<String> addPortalAdminInAAF(HttpEntity<String> addUserRole){ + return template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", + HttpMethod.POST, addUserRole, String.class); + } + + public void deletePortalAdminFromAAF(final String name, final String extRole, final HttpEntity<String> addUserRole){ + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + extRole, + HttpMethod.DELETE, addUserRole, String.class); + } +} 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 27a5eeaf..a9d5f6c4 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 @@ -2217,4 +2217,8 @@ public class AdminRolesService { logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e); } } + + public List<FnRole> getRolesByApp(final Long appId) { + return fnRoleService.retrieveActiveRolesOfApplication(appId); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/PortalAdminService.java b/portal-BE/src/main/java/org/onap/portal/service/PortalAdminService.java new file mode 100644 index 00000000..13be1f34 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/PortalAdminService.java @@ -0,0 +1,222 @@ +package org.onap.portal.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; +import javax.annotation.PostConstruct; +import javax.persistence.EntityExistsException; +import javax.persistence.EntityManager; +import javax.servlet.http.HttpServletResponse; +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.ExternalAccessUser; +import org.onap.portal.domain.dto.transport.FieldsValidator; +import org.onap.portal.domain.dto.transport.PortalAdmin; +import org.onap.portal.restTemplates.AAFTemplate; +import org.onap.portal.service.app.FnAppService; +import org.onap.portal.service.role.FnRoleService; +import org.onap.portal.service.user.FnUserService; +import org.onap.portal.service.userRole.FnUserRoleService; +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.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +@Service +public class PortalAdminService { + + private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminService.class); + + private String SYS_ADMIN_ROLE_ID = "1"; + private String ECOMP_APP_ID = "1"; + + private final ExternalAccessRolesService externalAccessRolesService; + private final FnAppService fnAppService; + private final FnRoleService fnRoleService; + private final FnUserRoleService fnUserRoleService; + private final FnUserService fnUserService; + private final EntityManager entityManager; + private final AAFTemplate aafTemplate; + + @Autowired + public PortalAdminService(ExternalAccessRolesService externalAccessRolesService, + FnAppService fnAppService, FnRoleService fnRoleService, + FnUserRoleService fnUserRoleService, FnUserService fnUserService, + EntityManager entityManager, AAFTemplate aafTemplate) { + this.externalAccessRolesService = externalAccessRolesService; + this.fnAppService = fnAppService; + this.fnRoleService = fnRoleService; + this.fnUserRoleService = fnUserRoleService; + this.fnUserService = fnUserService; + this.entityManager = entityManager; + this.aafTemplate = aafTemplate; + } + + @PostConstruct + public void init() { + SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID); + ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID); + } + + + @SuppressWarnings("unchecked") + public List<PortalAdmin> getPortalAdmins() { + try { + List<PortalAdmin> portalAdmins = entityManager.createNamedQuery("PortalAdminDTO") + .setParameter("adminRoleId", SYS_ADMIN_ROLE_ID).getResultList(); + logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful"); + return portalAdmins; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getPortalAdmins failed", e); + return null; + } + } + + public FieldsValidator createPortalAdmin(String orgUserId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: orgUserId is {}", orgUserId); + FnUser user = null; + boolean createNewUser = false; + List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId); + if (!localUserList.isEmpty()) { + user = localUserList.get(0); + } else { + createNewUser = true; + } + + if (user != null && isLoggedInUserPortalAdmin(user.getId())) { + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_CONFLICT); + logger.error(EELFLoggerDelegate.errorLogger, + "User '" + user.getOrgUserId() + "' already has PortalAdmin role assigned."); + } else if (user != null || createNewUser) { + try { + if (createNewUser) { + user = fnUserService.getUserWithOrgUserId(orgUserId).get(0); + if (user != null) { + user.setActiveYn(true); + fnUserService.save(user); + } + } + if (user != null) { + FnUserRole userRole = new FnUserRole(); + userRole.setUserId(user); + userRole.setRoleId(fnRoleService.getById(Long.valueOf(SYS_ADMIN_ROLE_ID))); + userRole.setFnAppId(fnAppService.getById(Long.valueOf(ECOMP_APP_ID))); + fnUserRoleService.saveOne(userRole); + } + if (user != null && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + List<FnRole> roleList = externalAccessRolesService + .getPortalAppRoleInfo(PortalConstants.SYS_ADMIN_ROLE_ID); + FnRole role = new FnRole(); + if (roleList.size() > 0) { + role = roleList.get(0); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Requested RoleName is " + role.getRoleName()); + addPortalAdminInExternalCentralAuth(user.getOrgUserId(), role.getRoleName()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin failed", e); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + return fieldsValidator; + } + + private void addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole) throws Exception { + try { + String name = ""; + if (EPCommonSystemProperties.containsProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = loginId + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + //TODO HARDCODED ID + FnApp app = fnAppService.getById(PortalConstants.PORTAL_APP_ID); + String extRole = app.getAuthNamespace() + "." + portalAdminRole.replaceAll(" ", "_"); + ObjectMapper addUserRoleMapper = new ObjectMapper(); + ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); + String userRole = addUserRoleMapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + aafTemplate.addPortalAdminInAAF(new HttpEntity<>(userRole, headers)); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e); + throw e; + } + } + } + + public FieldsValidator deletePortalAdmin(Long userId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: test 1"); + try { + //TODO HARDCODED ID + fnUserRoleService.deleteByUserIdAndRoleId(userId, SYS_ADMIN_ROLE_ID); + if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { + + List<FnRole> roleList = externalAccessRolesService + .getPortalAppRoleInfo(PortalConstants.SYS_ADMIN_ROLE_ID); + FnRole role = new FnRole(); + if (roleList.size() > 0) { + role = roleList.get(0); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Requested RoleName is " + role.getRoleName()); + deletePortalAdminInExternalCentralAuth(userId, role.getRoleName()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin failed", e); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + + private void deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole) throws Exception { + try { + String name = ""; + FnUser localUserList = fnUserService.getUser(userId) + .orElseThrow(() -> new EntityExistsException("User with id:" + userId + "do not exists.")); + if (EPCommonSystemProperties.containsProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = localUserList.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + //TODO HARDCODED ID + FnApp app = fnAppService.getById(PortalConstants.PORTAL_APP_ID); + String extRole = app.getAuthNamespace() + "." + portalAdminRole.replaceAll(" ", "_"); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + aafTemplate.deletePortalAdminFromAAF(name, extRole, new HttpEntity<>(headers)); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found", + e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e); + throw e; + } + } + } + + @SuppressWarnings("unchecked") + private boolean isLoggedInUserPortalAdmin(Long userId) { + try { + List<PortalAdmin> portalAdmins = entityManager.createNamedQuery("ActivePortalAdminDTO") + .setParameter("userId", userId) + .setParameter("adminRoleId", SYS_ADMIN_ROLE_ID) + .getResultList(); + logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString()); + return portalAdmins.size() > 0; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "isLoggedInUserPortalAdmin failed", e); + return false; + } + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/userRole/FnUserRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/userRole/FnUserRoleService.java index eb7ece2b..86ee03fb 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/userRole/FnUserRoleService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/userRole/FnUserRoleService.java @@ -474,6 +474,11 @@ public class FnUserRoleService { fnUserRoleDao.deleteById(id); } + public void deleteByUserIdAndRoleId(final Long userId, final String roleId){ + final String query = "DELETE FROM FnUserRole id = :userId AND roleId.id = :roleId"; + entityManager.createQuery(query).setParameter("userId", userId).setParameter("roleId", roleId).executeUpdate(); + } + public List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, FnRole[] userAppRoles, Boolean extRequestValue) { List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>(); |