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..bc4dcf2 100644 --- a/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java +++ b/src/main/java/eu/dnetlib/repo/manager/controllers/UserRoleController.java @@ -71,8 +71,7 @@ public class UserRoleController { } Integer couId = aaiRegistryService.getCouId(type, id); if (couId != null) { - Integer role = aaiRegistryService.getRoleId(coPersonId, couId); - aaiRegistryService.assignMemberRole(coPersonId, couId, role); + aaiRegistryService.assignMemberRole(coPersonId, couId); // Add role to current authorities authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id)); 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 06e67f3..b89746a 100644 --- a/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java +++ b/src/main/java/eu/dnetlib/repo/manager/service/RepositoryServiceImpl.java @@ -8,7 +8,6 @@ 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.BrokerException; import eu.dnetlib.repo.manager.exception.RepositoryServiceException; @@ -36,7 +35,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; @@ -499,32 +497,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; } 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..e54aebb 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 @@ -188,9 +188,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 050b20a..8d93ac9 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 @@ -11,7 +11,6 @@ import org.mitre.openid.connect.model.OIDCAuthenticationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -26,14 +25,11 @@ 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; @Autowired - RegistryCalls(@Value("${services.provide.aai.registry.coid:2}") String coid, - HttpUtils httpUtils, RegistryUtils registryUtils) { - this.coid = coid; + RegistryCalls(HttpUtils httpUtils, RegistryUtils registryUtils) { this.httpUtils = httpUtils; this.jsonUtils = registryUtils; } @@ -53,7 +49,6 @@ public class RegistryCalls implements AaiRegistryService { 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; @@ -66,7 +61,6 @@ public class RegistryCalls implements AaiRegistryService { @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) { @@ -82,7 +76,6 @@ public class RegistryCalls implements AaiRegistryService { public List getCoPersonIdsByEmail(String email) { List coPersonIds = new ArrayList<>(); Map params = new HashMap<>(); - params.put("coid", coid); params.put("mail", email); JsonElement response = httpUtils.get("co_people.json", params); if (response != null) { @@ -108,7 +101,6 @@ public class RegistryCalls implements AaiRegistryService { public Integer getCoPersonIdByIdentifier(String sub) { Map params = new HashMap<>(); - params.put("coid", coid); params.put("search.identifier", sub); JsonElement response = httpUtils.get("co_people.json", params); return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; @@ -117,7 +109,6 @@ public class RegistryCalls implements AaiRegistryService { @Override public JsonArray getCous(String name) { Map params = new HashMap<>(); - params.put("coid", coid); if (name != null) { params.put("name", URLEncoder.encode(name).toLowerCase()); } @@ -214,7 +205,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(); @@ -345,18 +335,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")); } } @@ -416,7 +403,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/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..88abcd7 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 @@ -55,10 +55,18 @@ public interface AuthorizationService { */ boolean 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 cd6812e..ad4dcfc 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; @@ -85,8 +87,7 @@ public class AuthorizationServiceImpl implements AuthorizationService { String role = roleMappingService.getRoleIdByRepoId(resourceId); Integer couId = aaiRegistryService.getCouId(role); if (couId != null) { - Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); - aaiRegistryService.assignMemberRole(coPersonId, couId, roleId); + aaiRegistryService.assignMemberRole(coPersonId, couId); // Add role to user current authorities authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); @@ -125,6 +126,35 @@ public class AuthorizationServiceImpl implements AuthorizationService { } } + @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)); + } + } + @Override public Collection getUserRoles() { Collection roles; diff --git a/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java b/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java index 957da55..65bed60 100644 --- a/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java +++ b/src/main/java/eu/dnetlib/repo/manager/utils/HttpUtils.java @@ -9,9 +9,14 @@ 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.HashMap; import java.util.Map; @Component @@ -28,6 +33,9 @@ public class HttpUtils { @Value("${services.provide.aai.registry.password}") private String password; + @Value("2") + private String coid; + public JsonElement post(String path, JsonObject body) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = createHeaders(user, password); @@ -48,7 +56,7 @@ public class HttpUtils { public JsonElement get(String path, Map params) { RestTemplate restTemplate = new RestTemplate(); - String url = registryUrl + path + ((params != null) ? createParams(params) : null); + String url = createUrl(registryUrl + path, params); ResponseEntity responseEntity = restTemplate.exchange (url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class); return getResponseEntityAsJsonElement(responseEntity); @@ -62,18 +70,24 @@ 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("&"); - } + private Map addCoId(Map params) { + if(params == null) { + params = new HashMap<>(); } - return ret.toString(); + params.put("coid", coid); + return params; + } + + + private String createUrl(String baseAddress, Map params) { + params = addCoId(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) {