Add methods to get user information by group and assign/revoke member or admin role from a users

This commit is contained in:
kostis30fyllou 2021-07-07 17:38:58 +03:00
parent a3585af683
commit 57520de6b9
9 changed files with 263 additions and 94 deletions

View File

@ -12,7 +12,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf();
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
http.httpBasic().authenticationEntryPoint(new EntryPoint());
}

View File

@ -2,28 +2,39 @@ package eu.dnetlib.dnetrolemanagement.controllers;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import eu.dnetlib.dnetrolemanagement.dto.Response;
import eu.dnetlib.dnetrolemanagement.dto.User;
import eu.dnetlib.dnetrolemanagement.exception.UnprocessableException;
import eu.dnetlib.dnetrolemanagement.exception.ConflictException;
import eu.dnetlib.dnetrolemanagement.exception.ResourceNotFoundException;
import eu.dnetlib.dnetrolemanagement.services.RegistryService;
import eu.dnetlib.dnetrolemanagement.utils.AuthoritiesUpdater;
import eu.dnetlib.dnetrolemanagement.utils.AuthoritiesUtils;
import eu.dnetlib.dnetrolemanagement.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@RestController
@RequestMapping("/admin")
public class AdminController {
private final RegistryService registryService;
private final AuthoritiesUpdater authoritiesUpdater;
private final Gson gson;
@Autowired
public AdminController(RegistryService registryService) {
this.gson = new Gson();
public AdminController(RegistryService registryService, AuthoritiesUpdater authoritiesUpdater) {
this.registryService = registryService;
this.authoritiesUpdater = authoritiesUpdater;
this.gson = new Gson();
}
/**
@ -32,26 +43,80 @@ public class AdminController {
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.GET)
public ResponseEntity<User[]> getInfos(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer couId = registryService.getCouId(type, id);
if(couId != null) {
if (couId != null) {
JsonArray users = registryService.getUserIdByCouId(couId, true);
JsonArray emails = registryService.getUserEmailByCouId(couId, true);
JsonArray names = registryService.getUserNamesByCouId(couId, true);
for (int i = 0; i < users.size(); i++) {
users.get(i).getAsJsonObject().addProperty("email", emails.get(i).getAsJsonObject().get("email").getAsString());
users.get(i).getAsJsonObject().addProperty("name", names.get(i).getAsJsonObject().get("name").getAsString());
}
return ResponseEntity.ok(gson.fromJson(users, User[].class));
return ResponseEntity.ok(JsonUtils.mergeUserInfo(users, emails, names, gson));
}
throw new ResourceNotFoundException("Role has not been found");
}
/**
* Assign admin role to logged in user or user with @email
*/
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.POST)
@PreAuthorize("hasAuthority('REGISTERED_USER') || @registryService.getCoPersonIdsByEmail(#email).size() > 0")
public ResponseEntity<Response> assignRole(@PathVariable("type") String type, @PathVariable("id") String id, @RequestParam(required = false) String email) {
Integer coPersonId = (email != null) ? registryService.getCoPersonIdsByEmail(email).get(0) : registryService.getCoPersonIdByIdentifier();
if (coPersonId != null) {
String identifier = registryService.getIdentifierByCoPersonId(coPersonId);
Integer couId = registryService.getCouId(type, id);
if (couId != null) {
Integer role = registryService.getRoleId(coPersonId, couId);
if (role != null) {
if (registryService.getUserAdminGroup(coPersonId, couId) == null) {
registryService.assignAdminRole(coPersonId, couId);
authoritiesUpdater.update(identifier, old -> {
HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
authorities.add(new SimpleGrantedAuthority(AuthoritiesUtils.manager(type, id)));
return authorities;
});
return ResponseEntity.ok(new Response("Role has been assigned successfully"));
}
throw new ConflictException("User is already an admin of this group");
}
throw new UnprocessableException("User must be member of this group in order to become an admin.");
}
throw new ResourceNotFoundException("Role has not been found");
}
throw new ResourceNotFoundException("User has not been found");
}
/**
* Remove admin role from logged in user or user with @email
*/
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.DELETE)
@PreAuthorize("hasAuthority('REGISTERED_USER') || @registryService.getCoPersonIdsByEmail(#email).size() > 0")
public ResponseEntity<Response> removeRole(@PathVariable("type") String type, @PathVariable("id") String id, @RequestParam(required = false) String email) {
List<Integer> coPersonIds = (email != null) ? registryService.getCoPersonIdsByEmail(email) : Collections.singletonList(registryService.getCoPersonIdByIdentifier());
if (coPersonIds.size() > 0) {
Integer couId = registryService.getCouId(type, id);
if (couId != null) {
coPersonIds.forEach(coPersonId -> {
registryService.removeAdminRole(coPersonId, couId);
String identifier = registryService.getIdentifierByCoPersonId(coPersonId);
authoritiesUpdater.update(identifier, old -> {
HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
authorities.remove(new SimpleGrantedAuthority(AuthoritiesUtils.manager(type, id)));
return authorities;
});
});
return ResponseEntity.ok(new Response("Role has been revoked successfully"));
}
throw new ResourceNotFoundException("Role has not been found");
}
throw new ResourceNotFoundException("User has not been found");
}
/**
* Get the names of the managers of a type(Community, etc.) with id(ee, egi, etc.)
*/
@RequestMapping(value = "/{type}/{id}/name", method = RequestMethod.GET)
public ResponseEntity<User[]> getNames(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer couId = registryService.getCouId(type, id);
if(couId != null) {
if (couId != null) {
JsonArray users = registryService.getUserNamesByCouId(couId, true);
return ResponseEntity.ok(gson.fromJson(users, User[].class));
}
@ -65,7 +130,7 @@ public class AdminController {
@RequestMapping(value = "/{type}/{id}/id", method = RequestMethod.GET)
public ResponseEntity<User[]> getIds(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer couId = registryService.getCouId(type, id);
if(couId != null) {
if (couId != null) {
JsonArray users = registryService.getUserIdByCouId(couId, true);
return ResponseEntity.ok(gson.fromJson(users, User[].class));
}
@ -78,7 +143,7 @@ public class AdminController {
@RequestMapping(value = "/{type}/{id}/email", method = RequestMethod.GET)
public ResponseEntity<User[]> getEmails(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer couId = registryService.getCouId(type, id);
if(couId != null) {
if (couId != null) {
JsonArray users = registryService.getUserEmailByCouId(couId, true);
return ResponseEntity.ok(gson.fromJson(users, User[].class));
}

View File

@ -2,22 +2,25 @@ package eu.dnetlib.dnetrolemanagement.controllers;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import eu.dnetlib.dnetrolemanagement.dto.Response;
import eu.dnetlib.dnetrolemanagement.dto.User;
import eu.dnetlib.dnetrolemanagement.exception.ResourceNotFoundException;
import eu.dnetlib.dnetrolemanagement.exception.UnprocessableException;
import eu.dnetlib.dnetrolemanagement.services.RegistryService;
import eu.dnetlib.dnetrolemanagement.utils.AuthoritiesUpdater;
import eu.dnetlib.dnetrolemanagement.utils.AuthoritiesUtils;
import eu.dnetlib.dnetrolemanagement.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/member")
@ -38,7 +41,6 @@ public class MemberController {
/**
* Get the user info of the members of a type(Community, etc.) with id(ee, egi, etc.)
*/
@PreAuthorize("hasAuthority('REGISTERED_USER')")
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.GET)
public ResponseEntity<User[]> getInfos(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer couId = registryService.getCouId(type, id);
@ -46,15 +48,68 @@ public class MemberController {
JsonArray users = registryService.getUserIdByCouId(couId, false);
JsonArray emails = registryService.getUserEmailByCouId(couId, false);
JsonArray names = registryService.getUserNamesByCouId(couId, false);
for (int i = 0; i < users.size(); i++) {
users.get(i).getAsJsonObject().addProperty("email", emails.get(i).getAsJsonObject().get("email").getAsString());
users.get(i).getAsJsonObject().addProperty("name", names.get(i).getAsJsonObject().get("name").getAsString());
}
return ResponseEntity.ok(gson.fromJson(users, User[].class));
return ResponseEntity.ok(JsonUtils.mergeUserInfo(users, emails, names, gson));
}
throw new ResourceNotFoundException("Role has not been found");
}
/**
* Assign member role to logged in user or user with @email
*/
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.POST)
@PreAuthorize("hasAuthority('REGISTERED_USER') || @registryService.getCoPersonIdsByEmail(#email).size() > 0")
public ResponseEntity<Response> assignRole(@PathVariable("type") String type, @PathVariable("id") String id, @RequestParam(required = false) String email) {
Integer coPersonId = (email != null)?registryService.getCoPersonIdsByEmail(email).get(0):registryService.getCoPersonIdByIdentifier();
if (coPersonId != null) {
String identifier = registryService.getIdentifierByCoPersonId(coPersonId);
Integer couId = registryService.getCouId(type, id);
if (couId != null) {
Integer role = registryService.getRoleId(coPersonId, couId);
registryService.assignMemberRole(coPersonId, couId, role);
authoritiesUpdater.update(identifier, old -> {
HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
authorities.add(new SimpleGrantedAuthority(AuthoritiesUtils.member(type, id)));
return authorities;
});
return ResponseEntity.ok(new Response("Role has been assigned successfully"));
}
throw new ResourceNotFoundException("Role has not been found");
}
throw new ResourceNotFoundException("User has not been found");
}
/**
* Remove member role from logged in user or user with @email
*/
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.DELETE)
@PreAuthorize("hasAuthority('REGISTERED_USER') || @registryService.getCoPersonIdsByEmail(#email).size() > 0")
public ResponseEntity<Response> removeRole(@PathVariable("type") String type, @PathVariable("id") String id, @RequestParam(required = false) String email) {
List<Integer> coPersonIds = (email != null) ? registryService.getCoPersonIdsByEmail(email) : Collections.singletonList(registryService.getCoPersonIdByIdentifier());
if (coPersonIds.size() > 0) {
Integer couId = registryService.getCouId(type, id);
if (couId != null) {
// If none of the accounts has admin role for this group remove member role
if(coPersonIds.stream().filter(coPersonId -> registryService.getUserAdminGroup(coPersonId, couId) != null).collect(Collectors.toList()).size() == 0) {
coPersonIds.forEach(coPersonId -> {
String identifier = registryService.getIdentifierByCoPersonId(coPersonId);
Integer role = registryService.getRoleId(coPersonId, couId);
registryService.removeMemberRole(coPersonId, couId, role);
authoritiesUpdater.update(identifier, old -> {
HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
authorities.remove(new SimpleGrantedAuthority(AuthoritiesUtils.member(type, id)));
return authorities;
});
});
return ResponseEntity.ok(new Response("Role has been revoked successfully"));
}
throw new UnprocessableException("User is admin of this group, so you must remove admin role first instead of member role");
}
throw new ResourceNotFoundException("Role has not been found");
}
throw new ResourceNotFoundException("User has not been found");
}
/**
* Get the names of the members of a type(Community, etc.) with id(ee, egi, etc.)
*/
@ -93,27 +148,4 @@ public class MemberController {
}
throw new ResourceNotFoundException("Role has not been found");
}
/**
* Assign member role to logged in user
*/
@RequestMapping(value = "/{type}/{id}", method = RequestMethod.POST)
@PreAuthorize("hasAuthority('REGISTRED_USER')")
public ResponseEntity<User[]> assignRole(@PathVariable("type") String type, @PathVariable("id") String id) {
Integer coPersonId = registryService.getCoPersonIdByIdentifier();
if (coPersonId != null) {
Integer couId = registryService.getCouId(type, id);
if (couId != null) {
Integer role = registryService.getRoleId(coPersonId, couId);
registryService.assignMemberRole(coPersonId, couId, role);
authoritiesUpdater.update(AuthoritiesUtils.getAaiId(), old -> {
HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
authorities.add(new SimpleGrantedAuthority(AuthoritiesUtils.member(type, id)));
return authorities;
});
}
throw new ResourceNotFoundException("Role has not been found");
}
throw new ResourceNotFoundException("Role has not been found");
}
}

View File

@ -0,0 +1,18 @@
package eu.dnetlib.dnetrolemanagement.dto;
public class Response {
String response;
public Response(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}

View File

@ -0,0 +1,20 @@
package eu.dnetlib.dnetrolemanagement.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.CONFLICT) // 409
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
public ConflictException(String message, Throwable err) {
super(message, err);
}
public HttpStatus getStatus() {
return HttpStatus.NOT_FOUND;
}
}

View File

@ -0,0 +1,20 @@
package eu.dnetlib.dnetrolemanagement.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) // 422
public class UnprocessableException extends RuntimeException {
public UnprocessableException(String message) {
super(message);
}
public UnprocessableException(String message, Throwable err) {
super(message, err);
}
public HttpStatus getStatus() {
return HttpStatus.NOT_FOUND;
}
}

View File

@ -36,46 +36,17 @@ public class RegistryService {
}
/**
* 1. Get CoPersonId by Email
* 1.1 Get CoPersonId by Email
*/
public Integer getCoPersonIdByEmail() {
try {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getUserInfo().getEmail();
Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("mail", email);
JsonElement response = httpUtils.get("co_people.json", params);
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
} catch (Exception e) {
logger.error("Get User info: An error occurred ", e);
return null;
}
}
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;
}
public List<Integer> getCoPersonIdsByEmail(String email) {
List<Integer> coPersonIds = new ArrayList<>();
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) {
if (response != null) {
JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
for(int i = 0; i < coPeople.size(); i++) {
for (int i = 0; i < coPeople.size(); i++) {
coPersonIds.add(coPeople.get(i).getAsJsonObject().get("Id").getAsInt());
}
}
@ -83,17 +54,13 @@ public class RegistryService {
}
/**
* 2. Get CoPersonId by AAI identifier
* 1.2 Get CoPersonId by AAI identifier
*/
public Integer getCoPersonIdByIdentifier() {
try {
OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
String sub = authentication.getUserInfo().getSub();
Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("search.identifier", sub);
JsonElement response = httpUtils.get("co_people.json", params);
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
return getCoPersonIdByIdentifier(sub);
} catch (Exception e) {
logger.error("Get User info: An error occurred ", e);
return null;
@ -108,13 +75,28 @@ public class RegistryService {
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
}
/**
* 2 Get AAI identifier by CoPersonId
*/
public String getIdentifierByCoPersonId(Integer coPersonId) {
Map<String, String> params = new HashMap<>();
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("identifiers.json", params);
JsonArray ids = (response != null)?response.getAsJsonObject().get("Identifiers").getAsJsonArray():new JsonArray();
if(ids.size() > 0) {
return ids.get(0).getAsJsonObject().get("Identifier").getAsString();
}
return null;
}
/**
* 3.1 Get OpenAIRE cous with a specific name(or substring)
*/
public JsonArray getCous(String name) {
Map<String, String> params = new HashMap<>();
params.put("coid", coid);
if(name != null) {
if (name != null) {
params.put("name", name.toLowerCase());
}
JsonElement response = httpUtils.get("cous.json", params);
@ -152,7 +134,7 @@ public class RegistryService {
* @return
*/
public Integer getCouId(String type, String id) {
return getCouId(type+ "." + id);
return getCouId(type + "." + id);
}
/**
@ -259,12 +241,12 @@ public class RegistryService {
JsonObject user = new JsonObject();
boolean add = true;
String email = info.getAsJsonObject().get("Mail").getAsString();
for(JsonElement element : emails) {
if(element.getAsJsonObject().get("email").getAsString().equals(email)) {
for (JsonElement element : emails) {
if (element.getAsJsonObject().get("email").getAsString().equals(email)) {
add = false;
}
}
if(add) {
if (add) {
user.addProperty("email", email);
user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
emails.add(user);
@ -330,7 +312,7 @@ public class RegistryService {
* 16. Remove a member role from a User
*/
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"));
}
}

View File

@ -6,6 +6,28 @@ import org.springframework.security.core.context.SecurityContextHolder;
public class AuthoritiesUtils {
/**
* Type = FUNDER | COMMUNITY | INSTITUTION | PROJECT
*
* */
public static String curator(String type) {
return "CURATOR_" + type.toUpperCase();
}
/**
* Type = FUNDER | COMMUNITY | INSTITUTION | PROJECT
*
* Id = EE, EGI, etc
* */
public static String manager(String type, String id) {
return type.toUpperCase() + "_" + id.toUpperCase() + "_MANAGER";
}
/**
* Type = FUNDER | COMMUNITY | RI | INSTITUTION | PROJECT
*
* Id = EE, EGI, etc
* */
public static String member(String type, String id) {
return type.toUpperCase() + "_" + id.toUpperCase();
}

View File

@ -1,9 +1,11 @@
package eu.dnetlib.dnetrolemanagement.utils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import eu.dnetlib.dnetrolemanagement.config.properties.RegistryProperties;
import eu.dnetlib.dnetrolemanagement.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -19,6 +21,14 @@ public class JsonUtils {
this.coid = registryProperties.getCoid();
}
public static User[] mergeUserInfo(JsonArray users, JsonArray emails, JsonArray names, Gson gson) {
for (int i = 0; i < users.size(); i++) {
users.get(i).getAsJsonObject().addProperty("email", emails.get(i).getAsJsonObject().get("email").getAsString());
users.get(i).getAsJsonObject().addProperty("name", names.get(i).getAsJsonObject().get("name").getAsString());
}
return gson.fromJson(users, User[].class);
}
public JsonObject coPersonRoles(Integer coPersonId, Integer couId, String status) {
JsonObject role = new JsonObject();
JsonArray coPersonRoles = new JsonArray();