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

View File

@ -434,7 +434,7 @@ public class RepositoryServiceImpl implements RepositoryService {
}
@Override
public List<RepositoryInterface> getRepositoryInterface(String id) throws JSONException {
public List<RepositoryInterface> getRepositoryInterface(String id) {
UriComponents uriComponents = UriComponentsBuilder
.fromHttpUrl(baseAddress + "/ds/api/")
@ -629,6 +629,12 @@ public class RepositoryServiceImpl implements RepositoryService {
String desiredCompatibilityLevel) throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
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());
@ -988,7 +994,7 @@ public class RepositoryServiceImpl implements RepositoryService {
}
private List<String> getRoleIdsFromUserRoles(String userEmail) {
Integer coPersonId = registryCalls.getCoPersonIdByEmail(userEmail);
List<Integer> coPersonId = registryCalls.getCoPersonIdsByEmail(userEmail);
JsonArray roles;
ArrayList<String> roleIds = new ArrayList<>();
ArrayList<Integer> couIds = new ArrayList<>();

View File

@ -11,19 +11,19 @@ import java.util.Map;
public interface AaiRegistryService {
/**
* 1.1 Get CoPersonId by authenticated user's Email
* 1.1 Get CoPersonId List by authenticated user's Email
*
* @return
*/
Integer getCoPersonIdByEmail();
List<Integer> getCoPersonIdsByEmail();
/**
* 1.2 Get CoPersonId by Email
* 1.2 Get CoPersonId List by Email
*
* @param email
* @return
*/
Integer getCoPersonIdByEmail(String email);
List<Integer> getCoPersonIdsByEmail(String email);
/**
* 1.3 Get a list of User Identifiers by Email
@ -34,12 +34,12 @@ public interface AaiRegistryService {
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
*/
List<Integer> getCoPersonIdsByEmail(String email);
List<String> getUserIdentifiersByCoPersonId(Integer coPersonId);
/**
* 2. Get CoPersonId by AAI identifier
@ -105,6 +105,14 @@ public interface AaiRegistryService {
*/
JsonArray getRolesWithStatus(Integer coPersonId, RoleStatus status);
/**
* 5.3 Get User non admin active roles
*
* @param coPersonIds
* @return
*/
JsonArray getRolesWithStatus(List<Integer> coPersonIds, RoleStatus status);
/**
* 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 java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
@Service
public class RegistryCalls implements AaiRegistryService {
@ -46,41 +43,20 @@ public class RegistryCalls implements AaiRegistryService {
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
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", getCoPersonIdByEmail(email).toString());
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("identifiers.json", params);
if (response != null) {
@ -95,6 +71,18 @@ public class RegistryCalls implements AaiRegistryService {
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
public List<Integer> getCoPersonIdsByEmail(String email) {
List<Integer> coPersonIds = new ArrayList<>();
@ -177,7 +165,14 @@ public class RegistryCalls implements AaiRegistryService {
@Override
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) {
roles = new JsonArray();
}

View File

@ -43,7 +43,7 @@ public interface AuthorizationService {
* @return
* @throws ResourceNotFoundException
*/
boolean addAdmin(String resourceId, String email) throws ResourceNotFoundException;
void addAdmin(String resourceId, String email) throws ResourceNotFoundException;
/**
* Remove user from resource admins.
@ -53,7 +53,7 @@ public interface AuthorizationService {
* @return
* @throws ResourceNotFoundException
*/
boolean removeAdmin(String resourceId, String email) throws ResourceNotFoundException;
void removeAdmin(String resourceId, String email) throws ResourceNotFoundException;
/**
* Creates a role based on the resourceId and assigns it to the current user.

View File

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