Compare commits

...

13 Commits

10 changed files with 317 additions and 295 deletions

View File

@ -1,109 +1,108 @@
package eu.dnetlib.repo.manager.controllers; //package eu.dnetlib.repo.manager.controllers;
//
import eu.dnetlib.repo.manager.domain.dto.Role; //import eu.dnetlib.repo.manager.domain.dto.Role;
import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService; //import eu.dnetlib.repo.manager.service.aai.registry.AaiRegistryService;
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater; //import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
import eu.dnetlib.repo.manager.service.security.AuthorizationService; //import eu.dnetlib.repo.manager.service.security.AuthorizationService;
import eu.dnetlib.repo.manager.service.security.RoleMappingService; //import eu.dnetlib.repo.manager.service.security.RoleMappingService;
import eu.dnetlib.repo.manager.utils.JsonUtils; //import eu.dnetlib.repo.manager.utils.JsonUtils;
import io.swagger.annotations.ApiOperation; //import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; //import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; //import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; //import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; //import org.springframework.web.bind.annotation.*;
//
import javax.ws.rs.core.MediaType; //import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; //import javax.ws.rs.core.Response;
import java.util.Collection; //import java.util.Collection;
//
//@RestController ////@RestController
//@RequestMapping(value = "/role-management") ////@RequestMapping(value = "/role-management")
//@Api(description = "Role Management", value = "role-management") ////@Api(description = "Role Management", value = "role-management")
public class UserRoleController { //public class UserRoleController {
//
private final AaiRegistryService aaiRegistryService; // private final AaiRegistryService aaiRegistryService;
private final AuthoritiesUpdater authoritiesUpdater; // private final AuthoritiesUpdater authoritiesUpdater;
private final RoleMappingService roleMappingService; // private final RoleMappingService roleMappingService;
private final AuthorizationService authorizationService; // private final AuthorizationService authorizationService;
//
@Autowired // @Autowired
UserRoleController(AaiRegistryService aaiRegistryService, // UserRoleController(AaiRegistryService aaiRegistryService,
AuthoritiesUpdater authoritiesUpdater, // AuthoritiesUpdater authoritiesUpdater,
RoleMappingService roleMappingService, // RoleMappingService roleMappingService,
AuthorizationService authorizationService) { // AuthorizationService authorizationService) {
this.aaiRegistryService = aaiRegistryService; // this.aaiRegistryService = aaiRegistryService;
this.authoritiesUpdater = authoritiesUpdater; // this.authoritiesUpdater = authoritiesUpdater;
this.roleMappingService = roleMappingService; // this.roleMappingService = roleMappingService;
this.authorizationService = authorizationService; // this.authorizationService = authorizationService;
} // }
//
/** // /**
* Get the role with the given id. // * Get the role with the given id.
**/ // **/
@RequestMapping(method = RequestMethod.GET, path = "/role/{id}") // @RequestMapping(method = RequestMethod.GET, path = "/role/{id}")
// @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") //// @PreAuthorize("hasAnyAuthority('REGISTERED_USER', 'SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) { // public Response getRole(@RequestParam(value = "type", defaultValue = "datasource") String type, @PathVariable("id") String id) {
int roleId = aaiRegistryService.getCouId(type, 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(); // 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. // * Create a new role with the given name and description.
**/ // **/
@RequestMapping(method = RequestMethod.POST, path = "/role") // @RequestMapping(method = RequestMethod.POST, path = "/role")
@PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')") // @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR')")
public Response createRole(@RequestBody Role role) { // public Response createRole(@RequestBody Role role) {
aaiRegistryService.createRole(role); // aaiRegistryService.createRole(role);
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build(); // 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.) // * Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
*/ // */
@ApiOperation(value = "subscribe") // @ApiOperation(value = "subscribe")
@RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}") // @RequestMapping(method = RequestMethod.POST, path = "/subscribe/{type}/{id}")
@PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") // @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) { // public Response subscribe(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier(); // Integer coPersonId = aaiRegistryService.getCoPersonIdByIdentifier();
if (coPersonId == null) { // if (coPersonId == null) {
coPersonId = aaiRegistryService.getCoPersonIdByEmail(); // coPersonId = aaiRegistryService.getCoPersonIdsByEmail();
} // }
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)); //
// return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
return Response.status(HttpStatus.OK.value()).entity(JsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build(); // } else {
} else { // return Response.status(HttpStatus.NOT_FOUND.value()).entity(JsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
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}")
@RequestMapping(method = RequestMethod.GET, path = "/users/couid/{id}") // @PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')")
@PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR')") // public ResponseEntity<String> getUsersByCouId(@PathVariable("id") Integer id) {
public ResponseEntity<String> getUsersByCouId(@PathVariable("id") Integer id) { //// calls.getUserByCoId()
// calls.getUserByCoId() // return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString());
return ResponseEntity.ok(aaiRegistryService.getUsersByCouId(id).toString()); // }
} //
//
// @RequestMapping(method = RequestMethod.GET, path = "/users/{email}/roles")
@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")
@PreAuthorize("hasAnyAuthority('SUPER_ADMINISTRATOR', 'CONTENT_PROVIDER_DASHBOARD_ADMINISTRATOR') or hasAuthority('REGISTERED_USER') and authentication.userInfo.email==#email") // public ResponseEntity<Collection<String>> getRolesByEmail(@PathVariable("email") String email) {
public ResponseEntity<Collection<String>> getRolesByEmail(@PathVariable("email") String email) { // return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email));
return ResponseEntity.ok(authorizationService.getUserRolesByEmail(email)); // }
} //
//
// @RequestMapping(method = RequestMethod.GET, path = "/user/roles/my")
@RequestMapping(method = RequestMethod.GET, path = "/user/roles/my") // @PreAuthorize("hasAuthority('REGISTERED_USER')")
@PreAuthorize("hasAuthority('REGISTERED_USER')") // public ResponseEntity<Collection<String>> getRoleNames() {
public ResponseEntity<Collection<String>> getRoleNames() { // return ResponseEntity.ok(authorizationService.getUserRoles());
return ResponseEntity.ok(authorizationService.getUserRoles()); // }
} //
//}
}

View File

@ -1,12 +1,12 @@
package eu.dnetlib.repo.manager.service; package eu.dnetlib.repo.manager.service;
import eu.dnetlib.api.functionality.ValidatorServiceException;
import eu.dnetlib.repo.manager.domain.*; import eu.dnetlib.repo.manager.domain.*;
import eu.dnetlib.repo.manager.exception.RepositoryServiceException; import eu.dnetlib.repo.manager.exception.RepositoryServiceException;
import eu.dnetlib.repo.manager.exception.ResourceNotFoundException; import eu.dnetlib.repo.manager.exception.ResourceNotFoundException;
import org.json.JSONException; import org.json.JSONException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -27,16 +27,14 @@ public interface RepositoryService {
List<RepositorySnippet> getRepositoriesByCountry(String country, String mode, Boolean managed); List<RepositorySnippet> getRepositoriesByCountry(String country, String mode, Boolean managed);
// TODO: remove? // TODO: remove?
List<Repository> getRepositoriesOfUser(String page, String size) throws JSONException, IOException; List<Repository> getRepositoriesOfUser(String page, String size);
// TODO: remove? // TODO: remove?
List<Repository> getRepositoriesOfUser(String userEmail, List<Repository> getRepositoriesOfUser(String userEmail, String page, String size);
String page,
String size) throws JSONException, IOException;
List<RepositorySnippet> getRepositoriesSnippetsOfUser(String page, String size) throws Exception; List<RepositorySnippet> getRepositoriesSnippetsOfUser(String page, String size);
List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception; List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size);
RepositorySnippet getRepositorySnippetById(String id) throws ResourceNotFoundException; RepositorySnippet getRepositorySnippetById(String id) throws ResourceNotFoundException;
@ -72,9 +70,7 @@ public interface RepositoryService {
Repository updateRepository(Repository repository, Authentication authentication); Repository updateRepository(Repository repository, Authentication authentication);
List<String> getUrlsOfUserRepos(String user_email, List<String> getUrlsOfUserRepos(String userEmail, String page, String size);
String page,
String size);
Map<String, String> getCompatibilityClasses(String mode); Map<String, String> getCompatibilityClasses(String mode);
@ -86,7 +82,7 @@ public interface RepositoryService {
Map<String, String> getListLatestUpdate(String mode); Map<String, String> 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); void updateInterfaceCompliance(String repositoryId, String repositoryInterfaceId, String compliance);
} }

View File

@ -8,12 +8,10 @@ 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.RepositoryServiceException; import eu.dnetlib.repo.manager.exception.RepositoryServiceException;
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;
import eu.dnetlib.repo.manager.service.security.AuthoritiesUpdater;
import eu.dnetlib.repo.manager.service.security.AuthorizationService; import eu.dnetlib.repo.manager.service.security.AuthorizationService;
import eu.dnetlib.repo.manager.service.security.RoleMappingService; import eu.dnetlib.repo.manager.service.security.RoleMappingService;
import eu.dnetlib.repo.manager.utils.Converter; 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.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;
@ -50,7 +47,6 @@ public class RepositoryServiceImpl implements RepositoryService {
private final AuthorizationService authorizationService; private final AuthorizationService authorizationService;
private final RoleMappingService roleMappingService; private final RoleMappingService roleMappingService;
private final AaiRegistryService registryCalls; private final AaiRegistryService registryCalls;
private final AuthoritiesUpdater authoritiesUpdater;
private final RestTemplate restTemplate; private final RestTemplate restTemplate;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final VocabularyLoader vocabularyLoader; private final VocabularyLoader vocabularyLoader;
@ -85,7 +81,6 @@ public class RepositoryServiceImpl implements RepositoryService {
public RepositoryServiceImpl(AuthorizationService authorizationService, public RepositoryServiceImpl(AuthorizationService authorizationService,
RoleMappingService roleMappingService, RoleMappingService roleMappingService,
AaiRegistryService registryCalls, AaiRegistryService registryCalls,
AuthoritiesUpdater authoritiesUpdater,
VocabularyLoader vocabularyLoader, VocabularyLoader vocabularyLoader,
RestTemplate restTemplate, RestTemplate restTemplate,
ObjectMapper objectMapper, ObjectMapper objectMapper,
@ -96,7 +91,6 @@ public class RepositoryServiceImpl implements RepositoryService {
this.authorizationService = authorizationService; this.authorizationService = authorizationService;
this.roleMappingService = roleMappingService; this.roleMappingService = roleMappingService;
this.registryCalls = registryCalls; this.registryCalls = registryCalls;
this.authoritiesUpdater = authoritiesUpdater;
this.vocabularyLoader = vocabularyLoader; this.vocabularyLoader = vocabularyLoader;
this.piWikService = piWikService; this.piWikService = piWikService;
this.emailUtils = emailUtils; this.emailUtils = emailUtils;
@ -132,7 +126,7 @@ public class RepositoryServiceImpl implements RepositoryService {
} }
httpHeaders = new HttpHeaders(); httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE)); httpHeaders.setContentType(MediaType.APPLICATION_JSON);
for (String vocName : vocabularyNames) { for (String vocName : vocabularyNames) {
vocabularyMap.put(vocName, vocabularyLoader.getVocabulary(vocName, Locale.ENGLISH, Locale.ROOT)); 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, // and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
// another way for paging must be implemented. // another way for paging must be implemented.
@Override @Override
public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids) throws Exception { public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids) {
return getRepositoriesSnippets(ids, 0, 10); 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, // and the "requestFilter.setId(repoId)" should return only one result at a time, thus,
// another way for paging must be implemented. // another way for paging must be implemented.
@Override @Override
public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids, int page, int size) throws Exception { public List<RepositorySnippet> getRepositoriesSnippets(List<String> ids, int page, int size) {
List<RepositorySnippet> resultSet; List<RepositorySnippet> resultSet = null;
List<DatasourceDetails> datasourceDetailsList = new ArrayList<>(); List<DatasourceDetails> datasourceDetailsList = new ArrayList<>();
// here page should be 0 // here page should be 0
@ -205,21 +199,25 @@ public class RepositoryServiceImpl implements RepositoryService {
for (String repoId : ids) { for (String repoId : ids) {
requestFilter.setId(repoId); requestFilter.setId(repoId);
DatasourceResponse rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, DatasourceResponse.class); DatasourceResponse rs = restTemplate.postForObject(uriComponents.toUri(), requestFilter, DatasourceResponse.class);
if ( rs == null ) if (rs == null) {
logger.error("The \"DatasourceResponse\" is null!"); logger.error("The \"DatasourceResponse\" is null!");
else } else {
datasourceDetailsList.addAll(rs.getDatasourceInfo()); datasourceDetailsList.addAll(rs.getDatasourceInfo());
}
} }
resultSet = objectMapper.readValue(objectMapper.writeValueAsString(datasourceDetailsList), try {
objectMapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class)); resultSet = objectMapper.readValue(objectMapper.writeValueAsString(datasourceDetailsList),
objectMapper.getTypeFactory().constructCollectionType(List.class, RepositorySnippet.class));
if (logger.isTraceEnabled()) { if (logger.isDebugEnabled()) {
logger.trace("resultSet: {}", objectMapper.writeValueAsString(resultSet)); 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; return resultSet;
} }
@ -298,12 +296,12 @@ public class RepositoryServiceImpl implements RepositoryService {
} }
@Override @Override
public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String page, String size) throws Exception { public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String page, String size) {
return getRepositoriesSnippetsOfUser(null, page, size); return getRepositoriesSnippetsOfUser(null, page, size);
} }
@Override @Override
public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) throws Exception { public List<RepositorySnippet> getRepositoriesSnippetsOfUser(String userEmail, String page, String size) {
int from = Integer.parseInt(page) * Integer.parseInt(size); int from = Integer.parseInt(page) * Integer.parseInt(size);
int to = from + Integer.parseInt(size); int to = from + Integer.parseInt(size);
List<String> repoIds = new ArrayList<>(); List<String> repoIds = new ArrayList<>();
@ -427,32 +425,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;
} }
@ -576,7 +549,7 @@ public class RepositoryServiceImpl implements RepositoryService {
public RepositoryInterface updateRepositoryInterface(String repoId, public RepositoryInterface updateRepositoryInterface(String repoId,
String comment, String comment,
RepositoryInterface repositoryInterface, RepositoryInterface repositoryInterface,
String desiredCompatibilityLevel) throws Exception { String desiredCompatibilityLevel) throws ResourceNotFoundException, ValidatorServiceException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Repository repository = this.getRepositoryById(repoId); Repository repository = this.getRepositoryById(repoId);
if (repositoryInterface.getId() != null) { if (repositoryInterface.getId() != null) {
@ -716,7 +689,7 @@ public class RepositoryServiceImpl implements RepositoryService {
public Map<String, String> getCompatibilityClasses(String mode) { public Map<String, String> getCompatibilityClasses(String mode) {
logger.debug("Getting compatibility classes for mode: {}", mode); logger.debug("Getting compatibility classes for mode: {}", mode);
Map<String, String> retMap = new HashMap<String, String>(); Map<String, String> retMap = new HashMap<>();
Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap(); Map<String, String> compatibilityClasses = this.getVocabulary("dnet:compatibilityLevel").getAsMap();
boolean foundData = false; boolean foundData = false;
@ -751,7 +724,7 @@ public class RepositoryServiceImpl implements RepositoryService {
logger.debug("Getting datasource classes for mode: {}", mode); logger.debug("Getting datasource classes for mode: {}", mode);
Map<String, String> retMap = new HashMap<String, String>(); Map<String, String> retMap = new HashMap<>();
// TODO: refactor (remove?) // TODO: refactor (remove?)
for (Map.Entry<String, String> entry : this.getVocabulary("dnet:datasource_typologies").getAsMap().entrySet()) { for (Map.Entry<String, String> 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())); 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 UriComponents uriComponents = UriComponentsBuilder
.fromHttpUrl(baseAddress + "/ds/api/oaiset") .fromHttpUrl(baseAddress + "/ds/api/oaiset")
.queryParam("dsId", repositoryId) .queryParam("dsId", repositoryId)
@ -989,7 +962,7 @@ public class RepositoryServiceImpl implements RepositoryService {
} }
private List<String> getRoleIdsFromUserRoles(String userEmail) { private List<String> getRoleIdsFromUserRoles(String userEmail) {
Integer coPersonId = registryCalls.getCoPersonIdByEmail(userEmail); List<Integer> coPersonId = registryCalls.getCoPersonIdsByEmail(userEmail);
JsonArray roles; JsonArray roles;
ArrayList<String> roleIds = new ArrayList<>(); ArrayList<String> roleIds = new ArrayList<>();
ArrayList<Integer> couIds = new ArrayList<>(); ArrayList<Integer> couIds = new ArrayList<>();

View File

@ -11,28 +11,36 @@ import java.util.Map;
public interface AaiRegistryService { public interface AaiRegistryService {
/** /**
* 1.1 Get CoPersonId by authenticated user's Email * 1.1 Get CoPersonId List by authenticated user's Email
* *
* @return * @return
*/ */
Integer getCoPersonIdByEmail(); List<Integer> getCoPersonIdsByEmail();
/** /**
* 1.2 Get CoPersonId by Email * 1.2 Get CoPersonId List by Email
*
* @param email
* @return
*/
Integer getCoPersonIdByEmail(String email);
/**
* 1. Get CoPersonId List by Email
* *
* @param email * @param email
* @return * @return
*/ */
List<Integer> getCoPersonIdsByEmail(String email); List<Integer> getCoPersonIdsByEmail(String email);
/**
* 1.3 Get a list of User Identifiers by Email
*
* @param email
* @return
*/
List<String> getUserIdentifiersByEmail(String email);
/**
* 1.3 Get a list of User Identifiers by Email
*
* @param coPersonId
* @return
*/
List<String> getUserIdentifiersByCoPersonId(Integer coPersonId);
/** /**
* 2. Get CoPersonId by AAI identifier * 2. Get CoPersonId by AAI identifier
* *
@ -97,6 +105,14 @@ public interface AaiRegistryService {
*/ */
JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status); JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status);
/**
* 5.3 Get User non admin active roles
*
* @param coPersonIds
* @return
*/
JsonArray getRolesWithStatus(List<Integer> coPersonIds, RoleStatus status);
/** /**
* 6. Get Role id of User base on couId. * 6. Get Role id of User base on couId.
* *
@ -188,9 +204,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

@ -6,8 +6,8 @@ import com.google.gson.JsonObject;
import com.nimbusds.jose.util.StandardCharset; import com.nimbusds.jose.util.StandardCharset;
import eu.dnetlib.repo.manager.domain.dto.Role; 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.service.aai.registry.utils.HttpUtils;
import eu.dnetlib.repo.manager.service.aai.registry.utils.RegistryUtils; 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.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -18,26 +18,22 @@ import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service @Service
public class RegistryCalls implements AaiRegistryService { 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;
private final String coid;
@Autowired @Autowired
RegistryCalls(@Value("${services.provide.aai.registry.coid:2}") String coid, RegistryCalls(HttpUtils httpUtils, RegistryUtils registryUtils, @Value("${services.provide.aai.registry.coid}") String coid) {
HttpUtils httpUtils, RegistryUtils registryUtils) {
this.coid = coid;
this.httpUtils = httpUtils; this.httpUtils = httpUtils;
this.jsonUtils = registryUtils; this.jsonUtils = registryUtils;
this.coid = coid;
} }
private String mapType(String type, boolean communityMap) { private String mapType(String type, boolean communityMap) {
@ -50,42 +46,51 @@ public class RegistryCalls implements AaiRegistryService {
} }
@Override @Override
public Integer getCoPersonIdByEmail() { public List<String> getUserIdentifiersByEmail(String email) {
List<String> ids = new ArrayList<>();
for (Integer coPersonId : getCoPersonIdsByEmail(email)) {
ids.addAll(getUserIdentifiersByCoPersonId(coPersonId));
}
return ids;
}
@Override
public List<String> getUserIdentifiersByCoPersonId(Integer coPersonId) {
List<String> ids = new ArrayList<>();
Map<String, String> 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<Integer> getCoPersonIdsByEmail() {
try { try {
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<>(); return getCoPersonIdsByEmail(email);
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;
} catch (Exception e) { } catch (Exception e) {
logger.error("Get User info: An error occurred ", e); logger.error("Get User info: An error occurred ", e);
return null; return null;
} }
} }
@Override
public Integer getCoPersonIdByEmail(String email) {
Map<String, String> 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 @Override
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);
params.put("coid", coid);
JsonElement response = httpUtils.get("co_people.json", params); JsonElement response = httpUtils.get("co_people.json", params);
if (response != null) { if (response != null) {
JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray(); JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
@ -110,8 +115,8 @@ 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);
params.put("coid", coid);
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;
} }
@ -119,7 +124,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) {
try { try {
params.put("name", URLEncoder.encode(name, StandardCharset.UTF_8.name()).toLowerCase()); params.put("name", URLEncoder.encode(name, StandardCharset.UTF_8.name()).toLowerCase());
@ -168,10 +172,13 @@ public class RegistryCalls implements AaiRegistryService {
@Override @Override
public JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status) { public JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status) {
JsonArray roles = getRoles(coPersonId); return getRolesWithStatus(Collections.singletonList(coPersonId), status);
if (roles == null) { }
roles = new JsonArray();
} @Override
public JsonArray getRolesWithStatus(List<Integer> coPersonIds, RoleStatus status) {
JsonArray roles = new JsonArray();
coPersonIds.parallelStream().forEach(coPersonId -> roles.addAll(getRoles(coPersonId)));
JsonArray activeRoles = new JsonArray(); JsonArray activeRoles = new JsonArray();
if (status != null) { if (status != null) {
for (JsonElement role : roles) { for (JsonElement role : roles) {
@ -180,7 +187,6 @@ public class RegistryCalls implements AaiRegistryService {
} }
} }
} }
assert activeRoles != null;
return activeRoles; return activeRoles;
} }
@ -224,7 +230,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();
@ -355,18 +360,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"));
} }
} }
@ -391,7 +393,7 @@ public class RegistryCalls implements AaiRegistryService {
params.put("copersonid", coPersonId.toString()); params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("names.json", params); JsonElement response = httpUtils.get("names.json", params);
JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null; JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null;
if ( info != null ) { if (info != null) {
JsonObject jsonInfo = info.getAsJsonObject(); JsonObject jsonInfo = info.getAsJsonObject();
return jsonInfo.get("Given").getAsString() + " " + jsonInfo.get("Family").getAsString(); return jsonInfo.get("Given").getAsString() + " " + jsonInfo.get("Family").getAsString();
} else } else
@ -426,7 +428,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

@ -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.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@ -9,9 +9,13 @@ 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.Map; import java.util.Map;
@Component @Component
@ -48,8 +52,9 @@ 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(url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class); ResponseEntity<String> responseEntity = restTemplate.exchange
(url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class);
return getResponseEntityAsJsonElement(responseEntity); return getResponseEntityAsJsonElement(responseEntity);
} }
@ -60,18 +65,14 @@ public class HttpUtils {
return getResponseEntityAsJsonElement(responseEntity); return getResponseEntityAsJsonElement(responseEntity);
} }
private String createUrl(String baseAddress, Map<String, String> params) {
private String createParams(Map<String, String> params) { LinkedMultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
StringBuilder ret = new StringBuilder("?"); params.forEach((k, v) -> multiValueMap.put(k, Collections.singletonList(v)));
int count = 0; UriComponents uriComponents = UriComponentsBuilder
for (Map.Entry<String, String> param : params.entrySet()) { .fromHttpUrl(baseAddress)
ret.append(param.getKey()).append("=").append(param.getValue()); .queryParams(multiValueMap)
count++; .build().encode();
if (count != params.entrySet().size()) { return uriComponents.toString();
ret.append("&");
}
}
return ret.toString();
} }
private HttpHeaders createHeaders(String username, String password) { private HttpHeaders createHeaders(String username, String password) {
@ -85,12 +86,13 @@ public class HttpUtils {
private JsonElement getResponseEntityAsJsonElement(ResponseEntity<String> responseEntity) { private JsonElement getResponseEntityAsJsonElement(ResponseEntity<String> responseEntity) {
if ( responseEntity == null ) if (responseEntity == null)
return null; return null;
String responseBody = responseEntity.getBody(); String responseBody = responseEntity.getBody();
if ( responseBody != null ) { if (responseBody != null) {
logger.trace(responseBody); logger.trace(responseBody);
try { try {
return new JsonParser().parse(responseBody); return new JsonParser().parse(responseBody);
} catch (Exception e) { } catch (Exception e) {

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

@ -43,7 +43,7 @@ public interface AuthorizationService {
* @return * @return
* @throws ResourceNotFoundException * @throws ResourceNotFoundException
*/ */
boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException; void addAdmin(String resourceId, String email) throws ResourceNotFoundException;
/** /**
* Remove user from resource admins. * Remove user from resource admins.
@ -53,12 +53,20 @@ public interface AuthorizationService {
* @return * @return
* @throws ResourceNotFoundException * @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. * 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;
@ -79,49 +81,74 @@ public class AuthorizationServiceImpl implements AuthorizationService {
@Override @Override
public boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException { public void addAdmin(String resourceId, String email) throws ResourceNotFoundException {
Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); String role = roleMappingService.getRoleIdByRepoId(resourceId);
if (coPersonId != null) { Integer couId = aaiRegistryService.getCouId(role);
String role = roleMappingService.getRoleIdByRepoId(resourceId); if (couId == null) {
Integer couId = aaiRegistryService.getCouId(role); throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
if (couId != null) { }
Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId); List<Integer> coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email);
aaiRegistryService.assignMemberRole(coPersonId, couId, roleId); for (Integer coPersonId : coPersonIds) {
assert coPersonId != null;
aaiRegistryService.assignMemberRole(coPersonId, couId);
// Add role to user current authorities // Add role to user current authorities
authoritiesUpdater.addRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) {
authoritiesUpdater.addRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId));
return true;
} else {
throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
} }
} else {
throw new ResourceNotFoundException("Cannot find coPersonId for user with email: " + email);
} }
} }
@Override @Override
public boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException { public void removeAdmin(String resourceId, String email) throws ResourceNotFoundException {
Integer coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); String role = roleMappingService.getRoleIdByRepoId(resourceId);
if (coPersonId != null) { Integer couId = aaiRegistryService.getCouId(role);
String role = roleMappingService.getRoleIdByRepoId(resourceId); if (couId == null) {
Integer couId = aaiRegistryService.getCouId(role); throw new ResourceNotFoundException("Cannot find CouId for role: " + role);
Integer roleId = null; }
if (couId != null) { List<Integer> coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email);
roleId = aaiRegistryService.getRoleId(coPersonId, couId); for (Integer coPersonId : coPersonIds) {
} assert coPersonId != null;
if (couId != null && roleId != null) { Integer roleId = aaiRegistryService.getRoleId(coPersonId, couId);
if (roleId != null) {
aaiRegistryService.removeMemberRole(coPersonId, couId, roleId); aaiRegistryService.removeMemberRole(coPersonId, couId, roleId);
// Remove role from user current authorities // Remove role from user current authorities
authoritiesUpdater.removeRole(email, roleMappingService.convertRepoIdToAuthority(resourceId)); for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) {
authoritiesUpdater.removeRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId));
return true; }
} else { } 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 @Override
public Collection<String> getUserRolesByEmail(String email) { public Collection<String> getUserRolesByEmail(String email) {
int coPersonId = aaiRegistryService.getCoPersonIdByEmail(email); List<Integer> coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email);
List<Integer> list = new ArrayList<>(); List<Integer> 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) { if (element.getAsJsonObject().get("CouId") != null) {
list.add(element.getAsJsonObject().get("CouId").getAsInt()); list.add(element.getAsJsonObject().get("CouId").getAsInt());
} }

View File

@ -1,5 +0,0 @@
package eu.dnetlib.repo.manager.utils;
public class DatasourceManagerClient {
//
}