[Users | Trunk]: Add new regisrty methods.

This commit is contained in:
Konstantinos Triantafyllou 2020-08-04 16:18:08 +00:00
parent 34b5678237
commit e6b08fa12e
11 changed files with 986 additions and 47 deletions

16
pom.xml
View File

@ -52,16 +52,6 @@
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>eu.dnetlib</groupId>
<artifactId>uoa-user-management</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
@ -93,11 +83,17 @@
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19.3</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,280 @@
package eu.dnetlib.openaire.usermanagement.api;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import eu.dnetlib.openaire.user.pojos.ManagerVerification;
import eu.dnetlib.openaire.usermanagement.dto.Role;
import eu.dnetlib.openaire.usermanagement.utils.JsonUtils;
import eu.dnetlib.openaire.usermanagement.utils.RegistryCalls;
import eu.dnetlib.openaire.usermanagement.utils.VerificationUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Component(value = "RegistryService")
@Path("/registry")
public class RegistryService {
private static final Logger logger = Logger.getLogger(RegistryService.class);
@Autowired
private RegistryCalls calls;
@Autowired
private JsonUtils jsonUtils;
@Autowired
private VerificationUtils verificationUtils;
/**
* Subscribe to type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/subscribe/{type}/{id}")
@POST
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("isAuthenticated()")
public Response subscribe(@PathParam("type") String type, @PathParam("id") String id) {
Integer coPersonId = calls.getCoPersonIdByIdentifier();
Integer couId = calls.getCouId(type, id);
if (couId != null) {
Integer role = calls.getRoleId(coPersonId, couId);
calls.assignMemberRole(coPersonId, couId, role);
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();
}
}
/**
* Subscribe from type(Community, etc.) with id(ee, egi, etc.).
* If user has manager role for this entity, it will be removed too.
*
* */
@Path("/unsubscribe/{type}/{id}")
@POST
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("isAuthenticated()")
public Response unsubscribe(@PathParam("type") String type, @PathParam("id") String id) {
Integer coPersonId = calls.getCoPersonIdByIdentifier();
Integer couId = calls.getCouId(type, id);
if (couId != null) {
Integer role = calls.getRoleId(coPersonId, couId);
if (role != null) {
calls.removeAdminRole(coPersonId, couId);
calls.removeMemberRole(coPersonId, couId, role);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
} else
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User does not have this role").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();
}
}
/**
* Create a new role with the given name and description.
*
* */
@Path("/createRole")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN)")
public Response createRole(@RequestBody Role role) {
calls.createRole(role);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
}
/**
* Invite user with email to manage a type(Community, etc.) with id(ee, egi, etc.)
* Auto generated link and code will be sent as response.
*
* */
@Path("/invite/{type}/{id}/manager/{email}")
@POST
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN, @AuthoritiesService.PORTAL_ADMIN, " +
"@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
public Response inviteUser(@PathParam("type") String type, @PathParam("id") String id, @PathParam("email") String email) {
Integer couId = calls.getCouId(type, id);
if (couId != null) {
JsonObject invitation = verificationUtils.createInvitation(email, type, id);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(invitation).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();
}
}
/**
* Get the verification with a specific id only if it refers to the logged in user
*
* */
@Path("verification/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("isAuthenticated()")
public Response getVerification(@PathParam("id") String id) {
ManagerVerification managerVerification = verificationUtils.getVerification(id);
if (managerVerification != null) {
if (calls.getCoPersonIdByEmail(managerVerification.getEmail()).equals(calls.getCoPersonIdByIdentifier())) {
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(jsonUtils.createVerification(managerVerification)).toString()).type(MediaType.APPLICATION_JSON).build();
} else {
return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
}
} else {
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Verification has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
}
}
/**
* Verify the verification with the specific id, if the code is correct and it refers to the logged in user.
* Manager role is assigned to this user, along with the member role.
*
* */
@Path("verification/{id}")
@POST
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("isAuthenticated()")
public Response verify(@PathParam("id") String id, @RequestBody String code) {
ManagerVerification managerVerification = verificationUtils.getVerification(id);
if (managerVerification != null) {
Integer coPersonId = calls.getCoPersonIdByEmail(managerVerification.getEmail());
if (coPersonId != null) {
if (coPersonId.equals(calls.getCoPersonIdByIdentifier())) {
if (managerVerification.getVerificationCode().equals(code)) {
verificationUtils.deleteVerification(managerVerification.getId());
Integer couId = calls.getCouId(managerVerification.getType(), managerVerification.getEntity());
if (couId != null) {
Integer role = calls.getRoleId(coPersonId, couId);
calls.assignMemberRole(coPersonId, couId, role);
if (calls.getUserAdminGroup(coPersonId, couId) == null) {
calls.assignAdminRole(coPersonId, couId);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Admin role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
} else {
return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("User is already admin of this cou").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();
}
} else {
return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Verification code is wrong").toString()).type(MediaType.APPLICATION_JSON).build();
}
} else {
return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
}
} else {
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
}
} else {
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Verification has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
}
}
/**
* Remove the manager role from user with email for a type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/{type}/{id}/manager/{email}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN," +
"@AuthoritiesService.PORTAL_ADMIN, @AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
public Response removeManagerRole(@PathParam("type") String type, @PathParam("id") String
id, @PathParam("email") String email) {
Integer coPersonId = calls.getCoPersonIdByEmail(email);
if (coPersonId != null) {
Integer couId = calls.getCouId(type, id);
if (couId != null) {
calls.removeAdminRole(coPersonId, couId);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").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();
}
} else {
return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
}
}
/**
* Get the names of the subscribers of a type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/{type}/{id}/subscribers")
@GET
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.PORTAL_ADMIN," +
"@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
public Response getSubscribers(@PathParam("type") String type, @PathParam("id") String id) {
Integer couId = calls.getCouId(type, id);
JsonArray subscribers = calls.getUserNamesByCouId(couId, false);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(subscribers).toString()).type(MediaType.APPLICATION_JSON).build();
}
/**
* Get the emails of the subscribers of a type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/{type}/{id}/subscribers/email")
@GET
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.PORTAL_ADMIN," +
"@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
public Response getSubscribersEmail(@PathParam("type") String type, @PathParam("id") String id) {
Integer couId = calls.getCouId(type, id);
JsonArray subscribers = calls.getUserEmailByCouId(couId, false);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(subscribers).toString()).type(MediaType.APPLICATION_JSON).build();
}
/**
* Get the number of the subscribers of a type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/{type}/{id}/subscribers/count")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getSubscribersCount(@PathParam("type") String type, @PathParam("id") String id) {
Integer couId = calls.getCouId(type, id);
int count = calls.getUserNamesByCouId(couId, false).size();
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(count).toString()).type(MediaType.APPLICATION_JSON).build();
}
/**
* Get the names of the managers of a type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/{type}/{id}/managers")
@GET
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.PORTAL_ADMIN," +
"@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
public Response getManagers(@PathParam("type") String type, @PathParam("id") String id) {
Integer couId = calls.getCouId(type, id);
JsonArray managers = calls.getUserNamesByCouId(couId, true);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(managers).toString()).type(MediaType.APPLICATION_JSON).build();
}
/**
* Get the emails of the managers of a type(Community, etc.) with id(ee, egi, etc.)
*
* */
@Path("/{type}/{id}/managers/email")
@GET
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.PORTAL_ADMIN," +
"@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
public Response getManagersEmail(@PathParam("type") String type, @PathParam("id") String id) {
Integer couId = calls.getCouId(type, id);
JsonArray managers = calls.getUserEmailByCouId(couId, true);
return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(managers).toString()).type(MediaType.APPLICATION_JSON).build();
}
}

View File

@ -5,14 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.unboundid.ldap.sdk.LDAPException;
import eu.dnetlib.openaire.user.pojos.migration.LDAPUser;
import eu.dnetlib.openaire.user.pojos.migration.MigrationUser;
import eu.dnetlib.openaire.user.pojos.migration.Role;
import eu.dnetlib.openaire.user.dao.RoleDAO;
import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO;
import eu.dnetlib.openaire.user.ldap.MUserActionsLDAP;
import eu.dnetlib.openaire.user.pojos.migration.LDAPUser;
import eu.dnetlib.openaire.user.store.DataSourceConnector;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
@ -28,26 +23,27 @@ import org.mitre.openid.connect.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import sun.net.www.http.HttpClient;
import javax.ws.rs.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by sofia on 24/11/2016.
@ -123,10 +119,10 @@ public class Test3Service {
@GET
@Path("/getUserInfo")
@Produces(MediaType.APPLICATION_JSON)
//TODO REMOVE THIS and make the request directly to aai service {oidc.issuer} OR! see what is done with redis
public Response getUserInfo(@QueryParam("accessToken") String accessToken) throws JsonProcessingException {
//return Response.status(404).entity(compose404Message("This is a test message.")).type(MediaType.APPLICATION_JSON).build();
// call aai with accessToken
logger.info(accessToken);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
protected boolean hasError(HttpStatus statusCode) {
@ -134,16 +130,12 @@ public class Test3Service {
}});
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer " + accessToken);
HttpEntity request = new HttpEntity(null, headers);
String fooResourceUrl = issuer +"userinfo";
HttpEntity<String> request = new HttpEntity<>(headers);
//logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class));
ResponseEntity response1 = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class);
logger.info(response1.getBody().toString());
ResponseEntity<String> response = restTemplate.exchange(issuer +"userinfo", HttpMethod.GET, request, String.class);
ObjectMapper mapper = new ObjectMapper();
return Response.status(response1.getStatusCode().value()).entity(mapper.writeValueAsString(response1.getBody())).type(MediaType.APPLICATION_JSON).build();
return Response.status(response.getStatusCode().value()).entity(response.getBody()).type(MediaType.APPLICATION_JSON).build();
}
@ -172,14 +164,14 @@ public class Test3Service {
userInfoJson.addProperty("given_name", userInfo.getGivenName());
userInfoJson.addProperty("family_name", userInfo.getFamilyName());
userInfoJson.addProperty("email", userInfo.getEmail());
JsonArray roles = new JsonArray();
JsonObject source = authentication.getUserInfo().getSource();
roles = source.getAsJsonArray("edu_person_entitlements");
userInfoJson.add("edu_person_entitlements", roles);
authentication.getAuthorities().forEach(grantedAuthority -> {
roles.add(grantedAuthority.toString());
});
userInfoJson.add("roles", roles);
}catch (Exception e){
logger.error("Get User info: An error occured ",e);
return Response.status(500).entity(compose500Message("Get User info: An error occured ",e)).type(MediaType.APPLICATION_JSON).build();
logger.error("Get User info: An error occurred ",e);
return Response.status(500).entity(compose500Message("Get User info: An error occurred ",e)).type(MediaType.APPLICATION_JSON).build();
}
return Response.status(200).entity(userInfoJson.toString()).type(MediaType.APPLICATION_JSON).build();
}
@ -241,12 +233,4 @@ public class Test3Service {
private String composeDataResponse(String fullname) {
return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(fullname) + " }";
}
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
}

View File

@ -0,0 +1,32 @@
package eu.dnetlib.openaire.usermanagement.dto;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Role {
String name;
String description;
public Role() {}
public Role(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,37 @@
package eu.dnetlib.openaire.usermanagement.utils;
import org.springframework.stereotype.Component;
@Component("AuthoritiesService")
public class AuthoritiesService {
public final String SUPER_ADMIN = "SUPER_ADMINISTRATOR";
public final String PORTAL_ADMIN = "PORTAL_ADMINISTRATOR";
public final String USER_ADMIN = "USER_ADMINISTRATOR";
/**
* Type = FUNDER | COMMUNITY | INSTITUTION | PROJECT
*
* */
public String curator(String type) {
return type.toUpperCase() + "_CURATOR";
}
/**
* Type = FUNDER | COMMUNITY | INSTITUTION | PROJECT
*
* Id = EE, EGI, etc
* */
public String manager(String type, String id) {
return type.toUpperCase() + "_" + id.toUpperCase() + "_MANAGER";
}
/**
* Type = FUNDER | COMMUNITY | INSTITUTION | PROJECT
*
* Id = EE, EGI, etc
* */
public String subscriber(String type, String id) {
return type.toUpperCase() + "_" + id.toUpperCase();
}
}

View File

@ -0,0 +1,103 @@
package eu.dnetlib.openaire.usermanagement.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.Map;
@Component
public class HttpUtils {
private static final Logger logger = Logger.getLogger(HttpUtils.class);
@Value("${registry.issuer}")
private String issuer;
@Value("${registry.user}")
private String user;
@Value("${registry.password}")
private String password;
public JsonElement post(String path, JsonObject body) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = createHeaders(user, password);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.POST, request, String.class);
if(responseEntity.getBody() != null) {
return new JsonParser().parse(responseEntity.getBody());
} else {
return null;
}
}
public JsonElement put(String path, JsonObject body) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = createHeaders(user, password);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.PUT, request, String.class);
if(responseEntity.getBody() != null) {
return new JsonParser().parse(responseEntity.getBody());
} else {
return null;
}
}
public JsonElement get(String path, Map<String, String> params) {
RestTemplate restTemplate = new RestTemplate();
String url = issuer + path + ((params != null) ? createParams(params) : null);
ResponseEntity<String> responseEntity = restTemplate.exchange
(url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class);
if(responseEntity.getBody() != null) {
return new JsonParser().parse(responseEntity.getBody());
} else {
return null;
}
}
public JsonElement delete(String path) {
RestTemplate restTemplate = new RestTemplate();
String url = issuer + path;
ResponseEntity<String> responseEntity = restTemplate.exchange
(url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(user, password)), String.class);
if(responseEntity.getBody() != null) {
return new JsonParser().parse(responseEntity.getBody());
} else {
return null;
}
}
private String createParams(Map<String, String> params) {
StringBuilder ret = new StringBuilder("?");
int count = 0;
for (Map.Entry<String, String> param : params.entrySet()) {
ret.append(param.getKey()).append("=").append(param.getValue());
count++;
if (count != params.entrySet().size()) {
ret.append("&");
}
}
return ret.toString();
}
private HttpHeaders createHeaders(String username, String password) {
return new HttpHeaders() {{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
set("Authorization", authHeader);
}};
}
}

View File

@ -0,0 +1,121 @@
package eu.dnetlib.openaire.usermanagement.utils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import eu.dnetlib.openaire.user.pojos.ManagerVerification;
import eu.dnetlib.openaire.usermanagement.dto.Role;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.Date;
@Component
public class JsonUtils {
@Value("${registry.version}")
private String version;
@Value("${registry.coid}")
private String coid;
public JsonObject coPersonRoles(Integer coPersonId, Integer couId, String status) {
JsonObject role = new JsonObject();
JsonArray coPersonRoles = new JsonArray();
JsonObject coPersonRole = new JsonObject();
JsonObject person = new JsonObject();
person.addProperty("Type", "CO");
person.addProperty("Id", coPersonId.toString());
coPersonRole.addProperty("Version", version);
coPersonRole.add("Person", person);
coPersonRole.addProperty("CouId", couId.toString());
coPersonRole.addProperty("Affiliation", "member");
coPersonRole.addProperty("Title", "");
coPersonRole.addProperty("O", "Openaire");
coPersonRole.addProperty("Status", status);
coPersonRole.addProperty("ValidFrom", "");
coPersonRole.addProperty("ValidThrough", "");
coPersonRoles.add(coPersonRole);
role.addProperty("RequestType", "CoPersonRoles");
role.addProperty("Version", version);
role.add("CoPersonRoles", coPersonRoles);
return role;
}
public JsonObject coGroupMembers(Integer coGroupId, Integer coPersonId, boolean member) {
JsonObject coGroup = new JsonObject();
JsonArray coGroupMembers = new JsonArray();
JsonObject coGroupMember = new JsonObject();
JsonObject person = new JsonObject();
person.addProperty("Type", "CO");
person.addProperty("Id", coPersonId.toString());
coGroupMember.addProperty("Version", version);
coGroupMember.add("Person", person);
coGroupMember.addProperty("CoGroupId", coGroupId.toString());
coGroupMember.addProperty("Member", member);
coGroupMember.addProperty("Owner", false);
coGroupMember.addProperty("ValidFrom", "");
coGroupMember.addProperty("ValidThrough", "");
coGroupMembers.add(coGroupMember);
coGroup.addProperty("RequestType", "CoGroupMembers");
coGroup.addProperty("Version", version);
coGroup.add("CoGroupMembers", coGroupMembers);
return coGroup;
}
public JsonObject createNewCou(Role role) {
JsonObject cou = new JsonObject();
JsonArray cous = new JsonArray();
JsonObject newCou = new JsonObject();
newCou.addProperty("Version", version);
newCou.addProperty("CoId", coid);
newCou.addProperty("Name", role.getName());
newCou.addProperty("Description", role.getDescription());
cous.add(newCou);
cou.addProperty("RequestType", "Cous");
cou.addProperty("Version", version);
cou.add("Cous", cous);
return cou;
}
public JsonObject createVerification(ManagerVerification managerVerification) {
JsonObject verification = new JsonObject();
verification.addProperty("id", managerVerification.getId());
verification.addProperty("email", managerVerification.getEmail());
verification.addProperty("type", managerVerification.getType());
verification.addProperty("entity", managerVerification.getEntity());
verification.addProperty("date", managerVerification.getDate().getTime());
return verification;
}
public JsonObject createResponse(JsonElement response) {
JsonObject json = new JsonObject();
json.add("response", response);
return json;
}
public JsonObject createResponse(String response) {
JsonObject json = new JsonObject();
json.addProperty("response", response);
return json;
}
public JsonObject createResponse(Number response) {
JsonObject json = new JsonObject();
json.addProperty("response", response);
return json;
}
public JsonObject createResponse(Boolean response) {
JsonObject json = new JsonObject();
json.addProperty("response", response);
return json;
}
public JsonObject createResponse(Character response) {
JsonObject json = new JsonObject();
json.addProperty("response", response);
return json;
}
}

View File

@ -0,0 +1,317 @@
package eu.dnetlib.openaire.usermanagement.utils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import eu.dnetlib.openaire.usermanagement.dto.Role;
import net.minidev.json.JSONObject;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class RegistryCalls {
private static final Logger logger = Logger.getLogger(RegistryCalls.class);
@Value("${registry.coid}")
private String coid;
@Autowired
public HttpUtils httpUtils;
@Autowired
public JsonUtils jsonUtils;
/**
* 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);
return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
}
/**
* 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;
} catch (Exception e) {
logger.error("Get User info: An error occurred ", e);
return null;
}
}
public Integer getCoPersonIdByIdentifier(String sub) {
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;
}
/**
* 3. Get all OpenAIRE cous
*/
public JsonArray getCous() {
Map<String, String> params = new HashMap<>();
params.put("coid", coid);
JsonElement response = httpUtils.get("cous.json", params);
return (response != null) ? response.getAsJsonObject().get("Cous").getAsJsonArray() : new JsonArray();
}
/**
* 4. Get a couId by type.id
*
* @param type
* @param id
* @return
*/
public Integer getCouId(String type, String id) {
JsonArray cous = getCous();
Integer couId = null;
for (JsonElement cou : cous) {
if (cou.getAsJsonObject().get("Name").getAsString().equals(type + "." + id)) {
couId = cou.getAsJsonObject().get("Id").getAsInt();
}
}
return couId;
}
/**
* 5. Get User non admin roles
*/
public JsonArray getRoles(Integer coPersonId) {
Map<String, String> params = new HashMap<>();
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("co_person_roles.json", params);
return (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();
}
/**
* 6. Get Role id of User base on couId.
*/
public Integer getRoleId(Integer coPersonId, Integer couId) {
JsonArray roles = getRoles(coPersonId);
for (JsonElement role : roles) {
JsonObject object = role.getAsJsonObject();
if (object.get("CouId").getAsInt() == couId) {
return object.get("Id").getAsInt();
}
}
return null;
}
/**
* 7. Get User Groups
*/
public JsonArray getUserGroups(Integer coPersonId) {
Map<String, String> params = new HashMap<>();
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("co_groups.json", params);
return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
}
/**
* 8. Get User Admin Group of a Cou
*/
public JsonObject getUserAdminGroup(Integer coPersonId, Integer couId) {
Map<String, String> params = new HashMap<>();
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("co_groups.json", params);
JsonArray roles = (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
for (JsonElement role : roles) {
JsonObject object = role.getAsJsonObject();
if (object.get("CouId") != null && object.get("CouId").getAsInt() == couId) {
if (object.get("Name").getAsString().contains("admins")) {
return object;
}
}
}
return null;
}
/**
* 9. Get Groups of a Cou
*/
public JsonArray getCouGroups(Integer couId) {
Map<String, String> params = new HashMap<>();
params.put("coid", coid);
params.put("couid", couId.toString());
JsonElement response = httpUtils.get("co_groups.json", params);
return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
}
/**
* 10. Get Admin Group of a Cou
*/
public JsonObject getCouAdminGroup(Integer couId) {
JsonArray groups = getCouGroups(couId);
for (JsonElement group : groups) {
if (group.getAsJsonObject().get("Name").getAsString().contains("admins")) {
return group.getAsJsonObject();
}
}
return null;
}
/**
* 11. Get users of a group
*/
public JsonArray getGroupMembers(Integer coGroupId) {
Map<String, String> params = new HashMap<>();
params.put("cogroupid", coGroupId.toString());
JsonElement response = httpUtils.get("co_group_members.json", params);
return (response != null) ? response.getAsJsonObject().get("CoGroupMembers").getAsJsonArray() : new JsonArray();
}
/**
* 12. Get Users' email of a Cou
*/
public JsonArray getUserEmailByCouId(Integer couId, boolean admin) {
Map<String, String> params = new HashMap<>();
params.put("couid", couId.toString());
if (admin) {
params.put("admin", "true");
}
JsonElement response = httpUtils.get("email_addresses.json", params);
JsonArray infos = (response != null) ? response.getAsJsonObject().get("EmailAddresses").getAsJsonArray() : new JsonArray();
JsonArray emails = new JsonArray();
infos.forEach(info -> {
JsonObject user = new JsonObject();
user.addProperty("email", info.getAsJsonObject().get("Mail").getAsString());
user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
emails.add(user);
});
return emails;
}
/**
* 13. Get Users' names of a Cou
*/
public JsonArray getUserNamesByCouId(Integer couId, boolean admin) {
Map<String, String> params = new HashMap<>();
params.put("couid", couId.toString());
if (admin) {
params.put("admin", "true");
}
JsonElement response = httpUtils.get("names.json", params);
JsonArray infos = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray() : new JsonArray();
JsonArray names = new JsonArray();
infos.forEach(info -> {
JsonObject user = new JsonObject();
user.addProperty("email", info.getAsJsonObject().get("Given").getAsString() + " " + info.getAsJsonObject().get("Family").getAsString());
user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
names.add(user);
});
return names;
}
/**
* 14. Assign a member role to a User
*/
public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) {
if (id != null) {
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"));
}
}
/**
* 15. Remove a member role from a User
*/
public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) {
httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted"));
}
/**
* 16. Create a new role
*/
public void createRole(Role role) {
httpUtils.post("cous.json", jsonUtils.createNewCou(role));
}
/**
* 17. Get User's email
*/
public String getUserEmail(Integer coPersonId) {
Map<String, String> params = new HashMap<>();
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("email_addresses.json", params);
JsonObject info = (response != null) ? response.getAsJsonObject().get("EmailAddresses").getAsJsonArray().get(0).getAsJsonObject() : null;
return (info != null) ? info.getAsJsonObject().get("Mail").getAsString() : null;
}
/**
* 18. Get User's names
*/
public String getUserNames(Integer coPersonId) {
Map<String, String> params = new HashMap<>();
params.put("copersonid", coPersonId.toString());
JsonElement response = httpUtils.get("names.json", params);
JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null;
return (info != null) ? info.getAsJsonObject().get("Given").getAsString() + " " + info.getAsJsonObject().get("Family").getAsString() : null;
}
/**
* 14. Assign an admin role to a User
*/
public void assignAdminRole(Integer coPersonId, Integer couId) {
JsonObject group = getCouAdminGroup(couId);
if (group != null) {
httpUtils.post("co_group_members.json", jsonUtils.coGroupMembers(group.get("Id").getAsInt(), coPersonId, true));
}
}
/**
* 15. Remove an admin role from a User
*/
public void removeAdminRole(Integer coPersonId, Integer couId) {
JsonObject adminGroup = this.getCouAdminGroup(couId);
JsonArray admins = this.getGroupMembers(adminGroup.get("Id").getAsInt());
Integer id = null;
for (JsonElement admin : admins) {
if (admin.getAsJsonObject().get("Person").getAsJsonObject().get("Id").getAsInt() == coPersonId) {
id = admin.getAsJsonObject().get("Id").getAsInt();
}
}
if (id != null) {
httpUtils.delete("co_group_members/" + id.toString() + ".json");
}
}
}

View File

@ -0,0 +1,63 @@
package eu.dnetlib.openaire.usermanagement.utils;
import com.google.gson.JsonObject;
import eu.dnetlib.openaire.user.pojos.ManagerVerification;
import eu.dnetlib.openaire.user.utils.ManagerVerificationActions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Random;
@Component
public class VerificationUtils {
private final Random random = new Random();
@Autowired
private ManagerVerificationActions actions;
public JsonObject createInvitation(String email, String type, String entity) {
String id;
do {
id = createId();
}while (exists(id));
ManagerVerification managerVerification = actions.addVerificationEntry(id, email, type, entity, createVerificationCode(), new Timestamp(new Date().getTime()));
JsonObject invitation = new JsonObject();
invitation.addProperty("link", managerVerification.getId());
invitation.addProperty("code", managerVerification.getVerificationCode());
return invitation;
}
public void deleteVerification(String id) {
actions.deleteVerificationEntry(id);
}
public ManagerVerification getVerification(String id) {
return actions.getManagerVerification(id);
}
public boolean exists(String id) {
return actions.verificationEntryExists(id);
}
private String createId() {
return random.ints(48, 123)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
.limit(16)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
private String createVerificationCode() {
StringBuilder code = new StringBuilder();
for (int i = 0; i < 6; i++) {
code.append(random.nextInt(9));
}
return code.toString();
}
}

View File

@ -1,2 +1,8 @@
google.recaptcha.secret = 6LfYrU8UAAAAADwrbImPvDo_XcxEZvrkkgMy9yU0
google.recaptcha.key = 6LfYrU8UAAAAAFsl3m2YhP1uavdmAdFEXBkoY_vd
google.recaptcha.key = 6LfYrU8UAAAAAFsl3m2YhP1uavdmAdFEXBkoY_vd
registry.issuer = https://openaire-dev.aai-dev.grnet.gr/registry
registry.user = user
registry.password = pass
registry.version = 1.0
registry.coid = 2

View File

@ -152,7 +152,7 @@
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST</param-value>
<param-value>GET, POST, DELETE OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>