diff --git a/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java b/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java index 255bac7..9f4d8b7 100644 --- a/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java +++ b/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java @@ -1,109 +1,108 @@ -package eu.dnetlib.repo.manager.controllers; - -import eu.dnetlib.repo.manager.domain.dto.Role; -import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; -import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; -import eu.dnetlib.repo.manager.service.security.AuthorizationService; -import eu.dnetlib.repo.manager.service.security.RoleMappingService; -import eu.dnetlib.repo.manager.utils.JsonUtils; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.Collection; - -//@RestController -//@RequestMapping(value = "/role-management") -//@Api(description = "Role Management", value = "role-management") -public class UserRoleController { - - private final AaiRegistryService aaiRegistryService; - private final AuthoritiesUpdater authoritiesUpdater; - private final RoleMappingService roleMappingService; - private final AuthorizationService authorizationService; - - @Autowired - UserRoleController(AaiRegistryService aaiRegistryService, - AuthoritiesUpdater authoritiesUpdater, - RoleMappingService roleMappingService, - AuthorizationService authorizationService) { - this.aaiRegistryService = aaiRegistryService; - this.authoritiesUpdater = authoritiesUpdater; - this.roleMappingService = roleMappingService; - this.authorizationService = authorizationService; - } - - /** - * Get the role with the given id. - **/ - @RequestMapping(method = RequestMethod.GET, path = "/role/{id}") -// @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") - public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) { - int roleId = aaiRegistryService.getCouId(type, id); - return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build(); - } - - /** - * Create a new role with the given name and description. - **/ - @RequestMapping(method = RequestMethod.POST, path = "/role") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')") - public Response createRole(@RequestBody Role role) { - aaiRegistryService.createRole(role); - return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build(); - } - - /** - * Subscribe to a type(Community, etc.) with id(ee, egi, etc.) - */ - @ApiOperation(value = "subscribe") - @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") - public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) { - Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); - if (coPersonId == null) { - coPersonId = aaiRegistryService.getCoPersonIdByEmail(); - } - Integer couId = aaiRegistryService.getCouId(type, id); - if (couId != null) { - Integer role = aaiRegistryService.getRoleId(coPersonId, couId); - aaiRegistryService.assignMemberRole(coPersonId, couId, role); - - // Add role to current authorities - authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id)); - - return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build(); - } else { - return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build(); - } - } - ///////////////////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////////////////////////////////////////////////////////////////// - - @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") - public ResponseEntity getUsersByCouId(@PathVariable("id") Integer id) { -// calls.getUserByCoId() - return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString()); - } - - - @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles") - @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email") - public ResponseEntity> getRolesByEmail(@PathVariable("email") String email) { - return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email)); - } - - - @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my") - @PreAuthorize("hasAuthority('REGISTERED_USER')") - public ResponseEntity> getRoleNames() { - return ResponseEntity.ok(authorizationService.getUserRoles()); - } - -} +//package eu.dnetlib.repo.manager.controllers; +// +//import eu.dnetlib.repo.manager.domain.dto.Role; +//import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; +//import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; +//import eu.dnetlib.repo.manager.service.security.AuthorizationService; +//import eu.dnetlib.repo.manager.service.security.RoleMappingService; +//import eu.dnetlib.repo.manager.utils.JsonUtils; +//import io.swagger.annotations.ApiOperation; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.http.HttpStatus; +//import org.springframework.http.ResponseEntity; +//import org.springframework.security.access.prepost.PreAuthorize; +//import org.springframework.web.bind.annotation.*; +// +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.Response; +//import java.util.Collection; +// +////@RestController +////@RequestMapping(value = "/role-management") +////@Api(description = "Role Management", value = "role-management") +//public class UserRoleController { +// +// private final AaiRegistryService aaiRegistryService; +// private final AuthoritiesUpdater authoritiesUpdater; +// private final RoleMappingService roleMappingService; +// private final AuthorizationService authorizationService; +// +// @Autowired +// UserRoleController(AaiRegistryService aaiRegistryService, +// AuthoritiesUpdater authoritiesUpdater, +// RoleMappingService roleMappingService, +// AuthorizationService authorizationService) { +// this.aaiRegistryService = aaiRegistryService; +// this.authoritiesUpdater = authoritiesUpdater; +// this.roleMappingService = roleMappingService; +// this.authorizationService = authorizationService; +// } +// +// /** +// * Get the role with the given id. +// **/ +// @RequestMapping(method = RequestMethod.GET, path = "/role/{id}") +//// @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") +// public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) { +// int roleId = aaiRegistryService.getCouId(type, id); +// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role id is: " + roleId).toString()).type(MediaType.APPLICATION_JSON).build(); +// } +// +// /** +// * Create a new role with the given name and description. +// **/ +// @RequestMapping(method = RequestMethod.POST, path = "/role") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')") +// public Response createRole(@RequestBody Role role) { +// aaiRegistryService.createRole(role); +// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build(); +// } +// +// /** +// * Subscribe to a type(Community, etc.) with id(ee, egi, etc.) +// */ +// @ApiOperation(value = "subscribe") +// @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") +// public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) { +// Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); +// if (coPersonId == null) { +// coPersonId = aaiRegistryService.getCoPersonIdsByEmail(); +// } +// Integer couId = aaiRegistryService.getCouId(type, id); +// if (couId != null) { +// aaiRegistryService.assignMemberRole(coPersonId, couId); +// +// // Add role to current authorities +// authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id)); +// +// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build(); +// } else { +// return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build(); +// } +// } +// ///////////////////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////////////////////// +// +// @RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") +// public ResponseEntity getUsersByCouId(@PathVariable("id") Integer id) { +//// calls.getUserByCoId() +// return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString()); +// } +// +// +// @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles") +// @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email") +// public ResponseEntity> getRolesByEmail(@PathVariable("email") String email) { +// return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email)); +// } +// +// +// @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my") +// @PreAuthorize("hasAuthority('REGISTERED_USER')") +// public ResponseEntity> getRoleNames() { +// return ResponseEntity.ok(authorizationService.getUserRoles()); +// } +// +//} diff --git a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java index 0cd4288..369f21d 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryService.java @@ -1,12 +1,12 @@ package eu.dnetlib.repo.manager.service; +import eu.dnetlib.api.functionality.ValidatorServiceException; import eu.dnetlib.repo.manager.domain.*; import eu.dnetlib.repo.manager.exception.RepositoryServiceException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import org.json.JSONException; import org.springframework.security.core.Authentication; -import java.io.IOException; import java.util.List; import java.util.Map; @@ -27,16 +27,14 @@ public interface RepositoryService { List getRepositoriesByCountry(String country, String mode, Boolean managed); // TODO: remove? - List getRepositoriesOfUser(String page, String size) throws JSONException, IOException; + List getRepositoriesOfUser(String page, String size); // TODO: remove? - List getRepositoriesOfUser(String userEmail, - String page, - String size) throws JSONException, IOException; + List getRepositoriesOfUser(String userEmail, String page, String size); - List getRepositoriesSnippetsOfUser(String page, String size) throws Exception; + List getRepositoriesSnippetsOfUser(String page, String size); - List getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception; + List getRepositoriesSnippetsOfUser(String userEmail, String page, String size); RepositorySnippet getRepositorySnippetById(String id) throws ResourceNotFoundException; @@ -72,9 +70,7 @@ public interface RepositoryService { Repository updateRepository(Repository repository, Authentication authentication); - List getUrlsOfUserRepos(String user_email, - String page, - String size); + List getUrlsOfUserRepos(String userEmail, String page, String size); Map getCompatibilityClasses(String mode); @@ -86,7 +82,7 @@ public interface RepositoryService { Map getListLatestUpdate(String mode); - RepositoryInterface updateRepositoryInterface(String repoId, String comment, RepositoryInterface repositoryInterface, String desiredCompatibilityLevel) throws Exception; + RepositoryInterface updateRepositoryInterface(String repoId, String comment, RepositoryInterface repositoryInterface, String desiredCompatibilityLevel) throws ResourceNotFoundException, ValidatorServiceException; void updateInterfaceCompliance(String repositoryId, String repositoryInterfaceId, String compliance); } diff --git a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java index 05faa63..00eeeda 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java @@ -8,12 +8,10 @@ import eu.dnetlib.api.functionality.ValidatorServiceException; import eu.dnetlib.domain.enabling.Vocabulary; import eu.dnetlib.domain.functionality.validator.JobForValidation; import eu.dnetlib.repo.manager.domain.*; -import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.User; import eu.dnetlib.repo.manager.exception.RepositoryServiceException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; -import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; import eu.dnetlib.repo.manager.service.security.AuthorizationService; import eu.dnetlib.repo.manager.service.security.RoleMappingService; import eu.dnetlib.repo.manager.utils.Converter; @@ -32,7 +30,6 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; @@ -50,7 +47,6 @@ public class RepositoryServiceImpl implements RepositoryService { private final AuthorizationService authorizationService; private final RoleMappingService roleMappingService; private final AaiRegistryService registryCalls; - private final AuthoritiesUpdater authoritiesUpdater; private final RestTemplate restTemplate; private final ObjectMapper objectMapper; private final VocabularyLoader vocabularyLoader; @@ -85,7 +81,6 @@ public class RepositoryServiceImpl implements RepositoryService { public RepositoryServiceImpl(AuthorizationService authorizationService, RoleMappingService roleMappingService, AaiRegistryService registryCalls, - AuthoritiesUpdater authoritiesUpdater, VocabularyLoader vocabularyLoader, RestTemplate restTemplate, ObjectMapper objectMapper, @@ -96,7 +91,6 @@ public class RepositoryServiceImpl implements RepositoryService { this.authorizationService = authorizationService; this.roleMappingService = roleMappingService; this.registryCalls = registryCalls; - this.authoritiesUpdater = authoritiesUpdater; this.vocabularyLoader = vocabularyLoader; this.piWikService = piWikService; this.emailUtils = emailUtils; @@ -132,7 +126,7 @@ public class RepositoryServiceImpl implements RepositoryService { } httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE)); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); for (String vocName : vocabularyNames) { vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT)); @@ -186,7 +180,7 @@ public class RepositoryServiceImpl implements RepositoryService { // and the "requestFilter.setId(repoId)" should return only one result at a time, thus, // another way for paging must be implemented. @Override - public List getRepositoriesSnippets(List ids) throws Exception { + public List getRepositoriesSnippets(List ids) { return getRepositoriesSnippets(ids, 0, 10); } @@ -194,8 +188,8 @@ public class RepositoryServiceImpl implements RepositoryService { // and the "requestFilter.setId(repoId)" should return only one result at a time, thus, // another way for paging must be implemented. @Override - public List getRepositoriesSnippets(List ids, int page, int size) throws Exception { - List resultSet; + public List getRepositoriesSnippets(List ids, int page, int size) { + List resultSet = null; List datasourceDetailsList = new ArrayList<>(); // here page should be 0 @@ -205,21 +199,25 @@ public class RepositoryServiceImpl implements RepositoryService { for (String repoId : ids) { requestFilter.setId(repoId); DatasourceResponse rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, DatasourceResponse.class); - if ( rs == null ) + if (rs == null) { logger.error("The \"DatasourceResponse\" is null!"); - else + } else { datasourceDetailsList.addAll(rs.getDatasourceInfo()); + } } - resultSet = objectMapper.readValue(objectMapper.writeValueAsString(datasourceDetailsList), - objectMapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)); - - if (logger.isTraceEnabled()) { - logger.trace("resultSet: {}", objectMapper.writeValueAsString(resultSet)); + try { + resultSet = objectMapper.readValue(objectMapper.writeValueAsString(datasourceDetailsList), + objectMapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)); + if (logger.isDebugEnabled()) { + logger.debug("resultSet: {}", objectMapper.writeValueAsString(resultSet)); + } + resultSet.parallelStream().forEach(repositorySnippet -> { + repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId())); + }); + } catch (JsonProcessingException e) { + logger.error("Error deserializing.", e); } - resultSet.parallelStream().forEach(repositorySnippet -> { - repositorySnippet.setPiwikInfo(piWikService.getPiwikSiteForRepo(repositorySnippet.getId())); - }); return resultSet; } @@ -298,12 +296,12 @@ public class RepositoryServiceImpl implements RepositoryService { } @Override - public List getRepositoriesSnippetsOfUser(String page, String size) throws Exception { + public List getRepositoriesSnippetsOfUser(String page, String size) { return getRepositoriesSnippetsOfUser(null, page, size); } @Override - public List getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception { + public List getRepositoriesSnippetsOfUser(String userEmail, String page, String size) { int from = Integer.parseInt(page) * Integer.parseInt(size); int to = from + Integer.parseInt(size); List repoIds = new ArrayList<>(); @@ -427,32 +425,7 @@ public class RepositoryServiceImpl implements RepositoryService { this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication()); } - // TODO: move the following code elsewhere (creation and assignment of role to user) ?? - // Create new role - String newRoleName = roleMappingService.getRoleIdByRepoId(repository.getId()); - Role newRole = new Role(newRoleName, repository.getOfficialname()); - Integer couId = null; - try { - couId = registryCalls.createRole(newRole); - } catch (HttpClientErrorException e) { - couId = registryCalls.getCouId(newRoleName); - if (couId == null) { - logger.error(String.format("Could not create role '%s'", newRoleName), e); - } - } catch (Exception e) { - logger.error(String.format("Could not create role '%s'", newRoleName), e); - throw e; - } - - // Assign new role to the user that created it - Integer coPersonId = registryCalls.getCoPersonIdByIdentifier(); - if (couId != null) { - Integer role = registryCalls.getRoleId(coPersonId, couId); - registryCalls.assignMemberRole(coPersonId, couId, role); - - // Add role to current user authorities - authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(repository.getId())); - } + authorizationService.createAndAssignRoleToAuthenticatedUser(repository.getId(), repository.getOfficialname()); return repository; } @@ -576,7 +549,7 @@ public class RepositoryServiceImpl implements RepositoryService { public RepositoryInterface updateRepositoryInterface(String repoId, String comment, RepositoryInterface repositoryInterface, - String desiredCompatibilityLevel) throws Exception { + String desiredCompatibilityLevel) throws ResourceNotFoundException, ValidatorServiceException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Repository repository = this.getRepositoryById(repoId); if (repositoryInterface.getId() != null) { @@ -716,7 +689,7 @@ public class RepositoryServiceImpl implements RepositoryService { public Map getCompatibilityClasses(String mode) { logger.debug("Getting compatibility classes for mode: {}", mode); - Map retMap = new HashMap(); + Map retMap = new HashMap<>(); Map compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap(); boolean foundData = false; @@ -751,7 +724,7 @@ public class RepositoryServiceImpl implements RepositoryService { logger.debug("Getting datasource classes for mode: {}", mode); - Map retMap = new HashMap(); + Map retMap = new HashMap<>(); // TODO: refactor (remove?) for (Map.Entry entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) { @@ -845,7 +818,7 @@ public class RepositoryServiceImpl implements RepositoryService { return Collections.singletonMap("lastCollectionDate", DateUtils.toString(getRepositoryInterface("openaire____::" + mode).get(0).getLastCollectionDate())); } - private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) throws Exception { + private void updateValidationSet(String repositoryId, String repositoryInterfaceId, String validationSet) { UriComponents uriComponents = UriComponentsBuilder .fromHttpUrl(baseAddress + "/ds/api/oaiset") .queryParam("dsId", repositoryId) @@ -989,7 +962,7 @@ public class RepositoryServiceImpl implements RepositoryService { } private List getRoleIdsFromUserRoles(String userEmail) { - Integer coPersonId = registryCalls.getCoPersonIdByEmail(userEmail); + List coPersonId = registryCalls.getCoPersonIdsByEmail(userEmail); JsonArray roles; ArrayList roleIds = new ArrayList<>(); ArrayList couIds = new ArrayList<>(); diff --git a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java index 6fe4888..6cb453f 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/AaiRegistryService.java @@ -11,28 +11,36 @@ import java.util.Map; public interface AaiRegistryService { /** - * 1.1 Get CoPersonId by authenticated user's Email + * 1.1 Get CoPersonId List by authenticated user's Email * * @return */ - Integer getCoPersonIdByEmail(); + List getCoPersonIdsByEmail(); /** - * 1.2 Get CoPersonId by Email - * - * @param email - * @return - */ - Integer getCoPersonIdByEmail(String email); - - /** - * 1. Get CoPersonId List by Email + * 1.2 Get CoPersonId List by Email * * @param email * @return */ List getCoPersonIdsByEmail(String email); + /** + * 1.3 Get a list of User Identifiers by Email + * + * @param email + * @return + */ + List getUserIdentifiersByEmail(String email); + + /** + * 1.3 Get a list of User Identifiers by Email + * + * @param coPersonId + * @return + */ + List getUserIdentifiersByCoPersonId(Integer coPersonId); + /** * 2. Get CoPersonId by AAI identifier * @@ -97,6 +105,14 @@ public interface AaiRegistryService { */ JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status); + /** + * 5.3 Get User non admin active roles + * + * @param coPersonIds + * @return + */ + JsonArray getRolesWithStatus(List coPersonIds, RoleStatus status); + /** * 6. Get Role id of User base on couId. * @@ -188,9 +204,8 @@ public interface AaiRegistryService { * * @param coPersonId * @param couId - * @param id */ - void assignMemberRole(Integer coPersonId, Integer couId, Integer id); + void assignMemberRole(Integer coPersonId, Integer couId); /** * 16. Remove a member role from a User diff --git a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java index be987bb..c7d4743 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/RegistryCalls.java @@ -6,8 +6,8 @@ import com.google.gson.JsonObject; import com.nimbusds.jose.util.StandardCharset; import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.User; +import eu.dnetlib.repo.manager.service.aai.registry.utils.HttpUtils; import eu.dnetlib.repo.manager.service.aai.registry.utils.RegistryUtils; -import eu.dnetlib.repo.manager.utils.HttpUtils; import org.mitre.openid.connect.model.OIDCAuthenticationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,26 +18,22 @@ import org.springframework.stereotype.Service; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Service public class RegistryCalls implements AaiRegistryService { private static final Logger logger = LoggerFactory.getLogger(RegistryCalls.class); - private final String coid; public final HttpUtils httpUtils; public final RegistryUtils jsonUtils; + private final String coid; @Autowired - RegistryCalls(@Value("${services.provide.aai.registry.coid:2}") String coid, - HttpUtils httpUtils, RegistryUtils registryUtils) { - this.coid = coid; + RegistryCalls(HttpUtils httpUtils, RegistryUtils registryUtils, @Value("${services.provide.aai.registry.coid}") String coid) { this.httpUtils = httpUtils; this.jsonUtils = registryUtils; + this.coid = coid; } private String mapType(String type, boolean communityMap) { @@ -50,42 +46,51 @@ public class RegistryCalls implements AaiRegistryService { } @Override - public Integer getCoPersonIdByEmail() { + public List getUserIdentifiersByEmail(String email) { + List ids = new ArrayList<>(); + for (Integer coPersonId : getCoPersonIdsByEmail(email)) { + ids.addAll(getUserIdentifiersByCoPersonId(coPersonId)); + } + return ids; + } + + @Override + public List getUserIdentifiersByCoPersonId(Integer coPersonId) { + List ids = new ArrayList<>(); + Map params = new HashMap<>(); + params.put("copersonid", coPersonId.toString()); + + JsonElement response = httpUtils.get("identifiers.json", params); + if (response != null) { + JsonArray infos = response.getAsJsonObject().get("Identifiers").getAsJsonArray(); + infos.forEach(info -> { + JsonObject jsonInfo = info.getAsJsonObject(); + if (!jsonInfo.get("Deleted").getAsBoolean()) { + ids.add(jsonInfo.get("Identifier").getAsString()); + } + }); + } + return ids; + } + + @Override + public List getCoPersonIdsByEmail() { try { OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); String email = authentication.getUserInfo().getEmail(); - Map params = new HashMap<>(); - params.put("coid", coid); - params.put("mail", email); - JsonElement response = httpUtils.get("co_people.json", params); - return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; + return getCoPersonIdsByEmail(email); } catch (Exception e) { logger.error("Get User info: An error occurred ", e); return null; } } - @Override - public Integer getCoPersonIdByEmail(String email) { - Map params = new HashMap<>(); - params.put("coid", coid); - params.put("mail", email); - JsonElement response = httpUtils.get("co_people.json", params); - if (response != null) { - JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray(); - if (coPeople.size() > 0) { - return coPeople.get(0).getAsJsonObject().get("Id").getAsInt(); - } - } - return null; - } - @Override public List getCoPersonIdsByEmail(String email) { List coPersonIds = new ArrayList<>(); Map params = new HashMap<>(); - params.put("coid", coid); params.put("mail", email); + params.put("coid", coid); JsonElement response = httpUtils.get("co_people.json", params); if (response != null) { JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray(); @@ -110,8 +115,8 @@ public class RegistryCalls implements AaiRegistryService { public Integer getCoPersonIdByIdentifier(String sub) { Map params = new HashMap<>(); - params.put("coid", coid); params.put("search.identifier", sub); + params.put("coid", coid); JsonElement response = httpUtils.get("co_people.json", params); return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; } @@ -119,7 +124,6 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getCous(String name) { Map params = new HashMap<>(); - params.put("coid", coid); if (name != null) { try { params.put("name", URLEncoder.encode(name, StandardCharset.UTF_8.name()).toLowerCase()); @@ -168,10 +172,13 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status) { - JsonArray roles = getRoles(coPersonId); - if (roles == null) { - roles = new JsonArray(); - } + return getRolesWithStatus(Collections.singletonList(coPersonId), status); + } + + @Override + public JsonArray getRolesWithStatus(List coPersonIds, RoleStatus status) { + JsonArray roles = new JsonArray(); + coPersonIds.parallelStream().forEach(coPersonId -> roles.addAll(getRoles(coPersonId))); JsonArray activeRoles = new JsonArray(); if (status != null) { for (JsonElement role : roles) { @@ -180,7 +187,6 @@ public class RegistryCalls implements AaiRegistryService { } } } - assert activeRoles != null; return activeRoles; } @@ -224,7 +230,6 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getCouGroups(Integer couId) { Map params = new HashMap<>(); - params.put("coid", coid); params.put("couid", couId.toString()); JsonElement response = httpUtils.get("co_groups.json", params); return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray(); @@ -355,18 +360,15 @@ public class RegistryCalls implements AaiRegistryService { } @Override - public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) { - if (id != null) { - httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Active")); - } else { - httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active")); - } + public void assignMemberRole(Integer coPersonId, Integer couId) { + httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active")); } + @Override public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) { if (id != null) { - httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted")); + httpUtils.put("co_person_roles/" + id + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted")); } } @@ -391,7 +393,7 @@ public class RegistryCalls implements AaiRegistryService { params.put("copersonid", coPersonId.toString()); JsonElement response = httpUtils.get("names.json", params); JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null; - if ( info != null ) { + if (info != null) { JsonObject jsonInfo = info.getAsJsonObject(); return jsonInfo.get("Given").getAsString() + " " + jsonInfo.get("Family").getAsString(); } else @@ -426,7 +428,7 @@ public class RegistryCalls implements AaiRegistryService { } } if (id != null) { - httpUtils.delete("co_group_members/" + id.toString() + ".json"); + httpUtils.delete("co_group_members/" + id + ".json"); } } diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/HttpUtils.java similarity index 77% rename from src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java rename to src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/HttpUtils.java index 245fc58..b294717 100644 --- a/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/HttpUtils.java @@ -1,4 +1,4 @@ -package eu.dnetlib.repo.manager.utils; +package eu.dnetlib.repo.manager.service.aai.registry.utils; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -9,9 +9,13 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; import java.nio.charset.StandardCharsets; +import java.util.Collections; import java.util.Map; @Component @@ -48,8 +52,9 @@ public class HttpUtils { public JsonElement get(String path, Map params) { RestTemplate restTemplate = new RestTemplate(); - String url = registryUrl + path + ((params != null) ? createParams(params) : null); - ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class); + String url = createUrl(registryUrl + path, params); + ResponseEntity responseEntity = restTemplate.exchange + (url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class); return getResponseEntityAsJsonElement(responseEntity); } @@ -60,18 +65,14 @@ public class HttpUtils { return getResponseEntityAsJsonElement(responseEntity); } - - private String createParams(Map params) { - StringBuilder ret = new StringBuilder("?"); - int count = 0; - for (Map.Entry param : params.entrySet()) { - ret.append(param.getKey()).append("=").append(param.getValue()); - count++; - if (count != params.entrySet().size()) { - ret.append("&"); - } - } - return ret.toString(); + private String createUrl(String baseAddress, Map params) { + LinkedMultiValueMap multiValueMap = new LinkedMultiValueMap<>(); + params.forEach((k, v) -> multiValueMap.put(k, Collections.singletonList(v))); + UriComponents uriComponents = UriComponentsBuilder + .fromHttpUrl(baseAddress) + .queryParams(multiValueMap) + .build().encode(); + return uriComponents.toString(); } private HttpHeaders createHeaders(String username, String password) { @@ -85,12 +86,13 @@ public class HttpUtils { private JsonElement getResponseEntityAsJsonElement(ResponseEntity responseEntity) { - if ( responseEntity == null ) + if (responseEntity == null) return null; String responseBody = responseEntity.getBody(); - if ( responseBody != null ) { + if (responseBody != null) { logger.trace(responseBody); + try { return new JsonParser().parse(responseBody); } catch (Exception e) { diff --git a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java index 7fe74f1..24576b0 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/aai/registry/utils/RegistryUtils.java @@ -6,6 +6,8 @@ import eu.dnetlib.repo.manager.domain.dto.Role; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import java.util.Date; + @Component public class RegistryUtils { @@ -29,8 +31,11 @@ public class RegistryUtils { coPersonRole.addProperty("Title", ""); coPersonRole.addProperty("O", "Openaire"); coPersonRole.addProperty("Status", status); - coPersonRole.addProperty("ValidFrom", ""); - coPersonRole.addProperty("ValidThrough", ""); + if(status.equals("Active")) { + coPersonRole.addProperty("ValidFrom", new Date().toString()); + } else { + coPersonRole.addProperty("ValidThrough", new Date().toString()); + } coPersonRoles.add(coPersonRole); role.addProperty("RequestType", "CoPersonRoles"); role.addProperty("Version", version); diff --git a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java index 3696321..8c8a665 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationService.java @@ -43,7 +43,7 @@ public interface AuthorizationService { * @return * @throws ResourceNotFoundException */ - boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException; + void addAdmin(String resourceId, String email) throws ResourceNotFoundException; /** * Remove user from resource admins. @@ -53,12 +53,20 @@ public interface AuthorizationService { * @return * @throws ResourceNotFoundException */ - boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException; + void removeAdmin(String resourceId, String email) throws ResourceNotFoundException; + + /** + * Creates a role based on the resourceId and assigns it to the current user. + * + * @param resourceId usually the repository Id. + * @param roleDescription usually the repository official name. + */ + void createAndAssignRoleToAuthenticatedUser(String resourceId, String roleDescription); /** * Returns the roles of the authenticated user. - * + * * @return */ Collection getUserRoles(); diff --git a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java index af8647e..e1f66f9 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/security/AuthorizationServiceImpl.java @@ -1,6 +1,7 @@ package eu.dnetlib.repo.manager.service.security; import com.google.gson.JsonElement; +import eu.dnetlib.repo.manager.domain.dto.Role; import eu.dnetlib.repo.manager.domain.dto.User; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; @@ -11,6 +12,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import java.util.ArrayList; import java.util.Collection; @@ -79,49 +81,74 @@ public class AuthorizationServiceImpl implements AuthorizationService { @Override - public boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException { - Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); - if (coPersonId != null) { - String role = roleMappingService.getRoleIdByRepoId(resourceId); - Integer couId = aaiRegistryService.getCouId(role); - if (couId != null) { - Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); - aaiRegistryService.assignMemberRole(coPersonId, couId, roleId); + public void addAdmin(String resourceId, String email) throws ResourceNotFoundException { + String role = roleMappingService.getRoleIdByRepoId(resourceId); + Integer couId = aaiRegistryService.getCouId(role); + if (couId == null) { + throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + } + List coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email); + for (Integer coPersonId : coPersonIds) { + assert coPersonId != null; + aaiRegistryService.assignMemberRole(coPersonId, couId); - // Add role to user current authorities - authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); - - return true; - } else { - throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + // Add role to user current authorities + for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { + authoritiesUpdater.addRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); } - } else { - throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email); } } @Override - public boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException { - Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); - if (coPersonId != null) { - String role = roleMappingService.getRoleIdByRepoId(resourceId); - Integer couId = aaiRegistryService.getCouId(role); - Integer roleId = null; - if (couId != null) { - roleId = aaiRegistryService.getRoleId(coPersonId, couId); - } - if (couId != null && roleId != null) { + public void removeAdmin(String resourceId, String email) throws ResourceNotFoundException { + String role = roleMappingService.getRoleIdByRepoId(resourceId); + Integer couId = aaiRegistryService.getCouId(role); + if (couId == null) { + throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + } + List coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email); + for (Integer coPersonId : coPersonIds) { + assert coPersonId != null; + Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); + if (roleId != null) { aaiRegistryService.removeMemberRole(coPersonId, couId, roleId); // Remove role from user current authorities - authoritiesUpdater.removeRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); - - return true; + for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { + authoritiesUpdater.removeRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); + } } else { - throw new ResourceNotFoundException("Cannot find CouId for role: " + role); + logger.error("Cannot find RoleId for role: {}", role); } - } else { - throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email); + } + } + + @Override + public void createAndAssignRoleToAuthenticatedUser(String resourceId, String roleDescription) { + // Create new role + String newRoleName = roleMappingService.getRoleIdByRepoId(resourceId); + Role newRole = new Role(newRoleName, roleDescription); + + Integer couId; + try { + couId = aaiRegistryService.createRole(newRole); + } catch (HttpClientErrorException e) { + couId = aaiRegistryService.getCouId(newRoleName); + if (couId == null) { + logger.error(String.format("Could not create role '%s'", newRoleName), e); + } + } catch (Exception e) { + logger.error(String.format("Could not create role '%s'", newRoleName), e); + throw e; + } + + // Assign new role to the current authenticated user + Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); + if (couId != null) { + aaiRegistryService.assignMemberRole(coPersonId, couId); + + // Add role to current user authorities + authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(resourceId)); } } @@ -139,9 +166,9 @@ public class AuthorizationServiceImpl implements AuthorizationService { @Override public Collection getUserRolesByEmail(String email) { - int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); + List coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email); List list = new ArrayList<>(); - for (JsonElement element : aaiRegistryService.getRolesWithStatus(coPersonId, AaiRegistryService.RoleStatus.ACTIVE)) { + for (JsonElement element : aaiRegistryService.getRolesWithStatus(coPersonIds, AaiRegistryService.RoleStatus.ACTIVE)) { if (element.getAsJsonObject().get("CouId") != null) { list.add(element.getAsJsonObject().get("CouId").getAsInt()); } diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/DatasourceManagerClient.java b/src/main/java/eu/dnetlib/repo/manager/utils/DatasourceManagerClient.java deleted file mode 100644 index 118dd05..0000000 --- a/src/main/java/eu/dnetlib/repo/manager/utils/DatasourceManagerClient.java +++ /dev/null @@ -1,5 +0,0 @@ -package eu.dnetlib.repo.manager.utils; - -public class DatasourceManagerClient { - // -}