get all ids of user using email in registry

This commit is contained in:
Konstantinos Spyrou 2023-01-20 19:15:59 +02:00
parent 125b64ec3b
commit 607c417e3f
6 changed files with 191 additions and 189 deletions

View File

@ -1,108 +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) {
aaiRegistryService.assignMemberRole(coPersonId, couId); // aaiRegistryService.assignMemberRole(coPersonId, couId);
//
// 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

@ -434,7 +434,7 @@ public class RepositoryServiceImpl implements RepositoryService {
} }
@Override @Override
public List<RepositoryInterface> getRepositoryInterface(String id) throws JSONException { public List<RepositoryInterface> getRepositoryInterface(String id) {
UriComponents uriComponents = UriComponentsBuilder UriComponents uriComponents = UriComponentsBuilder
.fromHttpUrl(baseAddress + "/ds/api/") .fromHttpUrl(baseAddress + "/ds/api/")
@ -629,6 +629,12 @@ public class RepositoryServiceImpl implements RepositoryService {
String desiredCompatibilityLevel) throws Exception { String desiredCompatibilityLevel) throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Repository repository = this.getRepositoryById(repoId); Repository repository = this.getRepositoryById(repoId);
if (repositoryInterface.getId() != null) {
RepositoryInterface existing = getRepositoryInterface(repoId).stream().filter(iFace -> iFace.getId().equals(repositoryInterface.getId())).findFirst().orElse(null);
if (existing != null && (existing.getBaseurl() == null || "".equals(existing.getBaseurl()))) {
this.updateBaseUrl(repoId, repositoryInterface.getId(), repositoryInterface.getBaseurl());
}
}
this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet()); this.updateValidationSet(repoId, repositoryInterface.getId(), repositoryInterface.getAccessSet());
@ -988,7 +994,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,19 +11,19 @@ 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 * @param email
* @return * @return
*/ */
Integer getCoPersonIdByEmail(String email); List<Integer> getCoPersonIdsByEmail(String email);
/** /**
* 1.3 Get a list of User Identifiers by Email * 1.3 Get a list of User Identifiers by Email
@ -34,12 +34,12 @@ public interface AaiRegistryService {
List<String> getUserIdentifiersByEmail(String email); List<String> getUserIdentifiersByEmail(String email);
/** /**
* 1.4 Get CoPersonId List by Email * 1.3 Get a list of User Identifiers by Email
* *
* @param email * @param coPersonId
* @return * @return
*/ */
List<Integer> getCoPersonIdsByEmail(String email); List<String> getUserIdentifiersByCoPersonId(Integer coPersonId);
/** /**
* 2. Get CoPersonId by AAI identifier * 2. Get CoPersonId by AAI identifier
@ -105,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.
* *

View File

@ -16,10 +16,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
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 {
@ -46,41 +43,20 @@ public class RegistryCalls implements AaiRegistryService {
return type; return type;
} }
@Override
public Integer getCoPersonIdByEmail() {
try {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getUserInfo().getEmail();
Map<String, String> params = new HashMap<>();
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) {
logger.error("Get User info: An error occurred ", e);
return null;
}
}
@Override
public Integer getCoPersonIdByEmail(String email) {
Map<String, String> params = new HashMap<>();
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();
if (coPeople.size() > 0) {
return coPeople.get(0).getAsJsonObject().get("Id").getAsInt();
}
}
return null;
}
@Override @Override
public List<String> getUserIdentifiersByEmail(String email) { 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<>(); List<String> ids = new ArrayList<>();
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("copersonid", getCoPersonIdByEmail(email).toString()); params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("identifiers.json", params); JsonElement response = httpUtils.get("identifiers.json", params);
if (response != null) { if (response != null) {
@ -95,6 +71,18 @@ public class RegistryCalls implements AaiRegistryService {
return ids; return ids;
} }
@Override
public List<Integer> getCoPersonIdsByEmail() {
try {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getUserInfo().getEmail();
return getCoPersonIdsByEmail(email);
} catch (Exception e) {
logger.error("Get User info: An error occurred ", e);
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<>();
@ -177,7 +165,14 @@ 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);
}
@Override
public JsonArray getRolesWithStatus(List<Integer> coPersonIds, RoleStatus status) {
JsonArray roles = new JsonArray();
JsonArray finalRoles = roles;
coPersonIds.parallelStream().forEach(coPersonId -> finalRoles.addAll(getRoles(coPersonId)));
if (roles == null) { if (roles == null) {
roles = new JsonArray(); roles = new JsonArray();
} }

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,7 +53,7 @@ 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. * Creates a role based on the resourceId and assigns it to the current user.

View File

@ -81,52 +81,45 @@ 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) { }
aaiRegistryService.assignMemberRole(coPersonId, couId); List<Integer> coPersonIds = aaiRegistryService.getCoPersonIdsByEmail(email);
for (Integer coPersonId : coPersonIds) {
assert coPersonId != null;
aaiRegistryService.assignMemberRole(coPersonId, couId);
// Add role to user current authorities // Add role to user current authorities
for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) {
authoritiesUpdater.addRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); 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
for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) { for (String userId : aaiRegistryService.getUserIdentifiersByEmail(email)) {
authoritiesUpdater.removeRole(userId, roleMappingService.convertRepoIdToAuthority(resourceId)); 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);
} }
} }
@ -173,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());
} }