changes for new aai registry

This commit is contained in:
Konstantinos Spyrou 2023-01-17 18:20:41 +02:00
parent 40b20b1122
commit 60ff3dce6e
8 changed files with 83 additions and 68 deletions

View File

@ -71,8 +71,7 @@ public class UserRoleController {
} }
Integer couId = aaiRegistryService.getCouId(type, id); Integer couId = aaiRegistryService.getCouId(type, id);
if (couId != null) { if (couId != null) {
Integer role = aaiRegistryService.getRoleId(coPersonId, couId); aaiRegistryService.assignMemberRole(coPersonId, couId);
aaiRegistryService.assignMemberRole(coPersonId, couId, role);
// Add role to current authorities // Add role to current authorities
authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id)); authoritiesUpdater.addRole(roleMappingService.convertRepoIdToAuthority(id));

View File

@ -8,7 +8,6 @@ import eu.dnetlib.api.functionality.ValidatorServiceException;
import eu.dnetlib.domain.enabling.Vocabulary; import eu.dnetlib.domain.enabling.Vocabulary;
import eu.dnetlib.domain.functionality.validator.JobForValidation; import eu.dnetlib.domain.functionality.validator.JobForValidation;
import eu.dnetlib.repo.manager.domain.*; 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.domain.dto.User;
import eu.dnetlib.repo.manager.exception.BrokerException; import eu.dnetlib.repo.manager.exception.BrokerException;
import eu.dnetlib.repo.manager.exception.RepositoryServiceException; 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.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
@ -499,32 +497,7 @@ public class RepositoryServiceImpl implements RepositoryService {
this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication()); this.latentUpdate(repository, SecurityContextHolder.getContext().getAuthentication());
} }
// TODO: move the following code elsewhere (creation and assignment of role to user) ?? authorizationService.createAndAssignRoleToAuthenticatedUser(repository.getId(), repository.getOfficialname());
// 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()));
}
return repository; return repository;
} }

View File

@ -188,9 +188,8 @@ public interface AaiRegistryService {
* *
* @param coPersonId * @param coPersonId
* @param couId * @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 * 16. Remove a member role from a User

View File

@ -11,7 +11,6 @@ import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -26,14 +25,11 @@ public class RegistryCalls implements AaiRegistryService {
private static final Logger logger = LoggerFactory.getLogger(RegistryCalls.class); private static final Logger logger = LoggerFactory.getLogger(RegistryCalls.class);
private final String coid;
public final HttpUtils httpUtils; public final HttpUtils httpUtils;
public final RegistryUtils jsonUtils; public final RegistryUtils jsonUtils;
@Autowired @Autowired
RegistryCalls(@Value("${services.provide.aai.registry.coid:2}") String coid, RegistryCalls(HttpUtils httpUtils, RegistryUtils registryUtils) {
HttpUtils httpUtils, RegistryUtils registryUtils) {
this.coid = coid;
this.httpUtils = httpUtils; this.httpUtils = httpUtils;
this.jsonUtils = registryUtils; this.jsonUtils = registryUtils;
} }
@ -53,7 +49,6 @@ public class RegistryCalls implements AaiRegistryService {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getUserInfo().getEmail(); String email = authentication.getUserInfo().getEmail();
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("mail", email); params.put("mail", email);
JsonElement response = httpUtils.get("co_people.json", params); JsonElement response = httpUtils.get("co_people.json", params);
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; 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 @Override
public Integer getCoPersonIdByEmail(String email) { public Integer getCoPersonIdByEmail(String email) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("mail", email); params.put("mail", email);
JsonElement response = httpUtils.get("co_people.json", params); JsonElement response = httpUtils.get("co_people.json", params);
if (response != null) { if (response != null) {
@ -82,7 +76,6 @@ public class RegistryCalls implements AaiRegistryService {
public List<Integer> getCoPersonIdsByEmail(String email) { public List<Integer> getCoPersonIdsByEmail(String email) {
List<Integer> coPersonIds = new ArrayList<>(); List<Integer> coPersonIds = new ArrayList<>();
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("mail", email); params.put("mail", email);
JsonElement response = httpUtils.get("co_people.json", params); JsonElement response = httpUtils.get("co_people.json", params);
if (response != null) { if (response != null) {
@ -108,7 +101,6 @@ public class RegistryCalls implements AaiRegistryService {
public Integer getCoPersonIdByIdentifier(String sub) { public Integer getCoPersonIdByIdentifier(String sub) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("search.identifier", sub); params.put("search.identifier", sub);
JsonElement response = httpUtils.get("co_people.json", params); JsonElement response = httpUtils.get("co_people.json", params);
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null; 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 @Override
public JsonArray getCous(String name) { public JsonArray getCous(String name) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
if (name != null) { if (name != null) {
params.put("name", URLEncoder.encode(name).toLowerCase()); params.put("name", URLEncoder.encode(name).toLowerCase());
} }
@ -214,7 +205,6 @@ public class RegistryCalls implements AaiRegistryService {
@Override @Override
public JsonArray getCouGroups(Integer couId) { public JsonArray getCouGroups(Integer couId) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("couid", couId.toString()); params.put("couid", couId.toString());
JsonElement response = httpUtils.get("co_groups.json", params); JsonElement response = httpUtils.get("co_groups.json", params);
return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray(); return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
@ -345,18 +335,15 @@ public class RegistryCalls implements AaiRegistryService {
} }
@Override @Override
public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) { public void assignMemberRole(Integer coPersonId, Integer couId) {
if (id != null) { httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
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"));
}
} }
@Override @Override
public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) { public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) {
if (id != null) { 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) { if (id != null) {
httpUtils.delete("co_group_members/" + id.toString() + ".json"); httpUtils.delete("co_group_members/" + id + ".json");
} }
} }

View File

@ -6,6 +6,8 @@ import eu.dnetlib.repo.manager.domain.dto.Role;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Date;
@Component @Component
public class RegistryUtils { public class RegistryUtils {
@ -29,8 +31,11 @@ public class RegistryUtils {
coPersonRole.addProperty("Title", ""); coPersonRole.addProperty("Title", "");
coPersonRole.addProperty("O", "Openaire"); coPersonRole.addProperty("O", "Openaire");
coPersonRole.addProperty("Status", status); coPersonRole.addProperty("Status", status);
coPersonRole.addProperty("ValidFrom", ""); if(status.equals("Active")) {
coPersonRole.addProperty("ValidThrough", ""); coPersonRole.addProperty("ValidFrom", new Date().toString());
} else {
coPersonRole.addProperty("ValidThrough", new Date().toString());
}
coPersonRoles.add(coPersonRole); coPersonRoles.add(coPersonRole);
role.addProperty("RequestType", "CoPersonRoles"); role.addProperty("RequestType", "CoPersonRoles");
role.addProperty("Version", version); role.addProperty("Version", version);

View File

@ -55,10 +55,18 @@ public interface AuthorizationService {
*/ */
boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException; 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. * Returns the roles of the authenticated user.
* *
* @return * @return
*/ */
Collection<String> getUserRoles(); Collection<String> getUserRoles();

View File

@ -1,6 +1,7 @@
package eu.dnetlib.repo.manager.service.security; package eu.dnetlib.repo.manager.service.security;
import com.google.gson.JsonElement; 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.domain.dto.User;
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; 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.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -85,8 +87,7 @@ public class AuthorizationServiceImpl implements AuthorizationService {
String role = roleMappingService.getRoleIdByRepoId(resourceId); String role = roleMappingService.getRoleIdByRepoId(resourceId);
Integer couId = aaiRegistryService.getCouId(role); Integer couId = aaiRegistryService.getCouId(role);
if (couId != null) { if (couId != null) {
Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); aaiRegistryService.assignMemberRole(coPersonId, couId);
aaiRegistryService.assignMemberRole(coPersonId, couId, roleId);
// Add role to user current authorities // Add role to user current authorities
authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); 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 @Override
public Collection<String> getUserRoles() { public Collection<String> getUserRoles() {
Collection<String> roles; Collection<String> roles;

View File

@ -9,9 +9,14 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*; import org.springframework.http.*;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate; 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.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Component @Component
@ -28,6 +33,9 @@ public class HttpUtils {
@Value("${services.provide.aai.registry.password}") @Value("${services.provide.aai.registry.password}")
private String password; private String password;
@Value("2")
private String coid;
public JsonElement post(String path, JsonObject body) { public JsonElement post(String path, JsonObject body) {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = createHeaders(user, password); HttpHeaders headers = createHeaders(user, password);
@ -48,7 +56,7 @@ public class HttpUtils {
public JsonElement get(String path, Map<String, String> params) { public JsonElement get(String path, Map<String, String> params) {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
String url = registryUrl + path + ((params != null) ? createParams(params) : null); String url = createUrl(registryUrl + path, params);
ResponseEntity<String> responseEntity = restTemplate.exchange ResponseEntity<String> responseEntity = restTemplate.exchange
(url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class); (url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class);
return getResponseEntityAsJsonElement(responseEntity); return getResponseEntityAsJsonElement(responseEntity);
@ -62,18 +70,24 @@ public class HttpUtils {
return getResponseEntityAsJsonElement(responseEntity); return getResponseEntityAsJsonElement(responseEntity);
} }
private Map<String, String> addCoId(Map<String, String> params) {
private String createParams(Map<String, String> params) { if(params == null) {
StringBuilder ret = new StringBuilder("?"); params = new HashMap<>();
int count = 0;
for (Map.Entry<String, String> param : params.entrySet()) {
ret.append(param.getKey()).append("=").append(param.getValue());
count++;
if (count != params.entrySet().size()) {
ret.append("&");
}
} }
return ret.toString(); params.put("coid", coid);
return params;
}
private String createUrl(String baseAddress, Map<String, String> params) {
params = addCoId(params);
LinkedMultiValueMap<String, String> 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) { private HttpHeaders createHeaders(String username, String password) {