test get Roles new

This commit is contained in:
Massimiliano Assante 2023-12-06 17:28:03 +01:00
parent a7bd85ec57
commit 5dd5497cf0
2 changed files with 123 additions and 80 deletions

60
pom.xml
View File

@ -1,6 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@ -20,7 +20,7 @@
<maven.compiler.target>1.8</maven.compiler.target>
<enunciate.version>2.14.0</enunciate.version>
<cassandra.driver.oss.version>4.13.0</cassandra.driver.oss.version>
<jackson.version>2.8.11</jackson.version>
<jackson.version>2.12.6</jackson.version>
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
@ -94,7 +94,7 @@
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>storagehub-client-library</artifactId>
<!-- <version>2.0.0-SNAPSHOT</version> -->
<!-- <version>2.0.0-SNAPSHOT</version> -->
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
@ -176,42 +176,42 @@
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<artifactId>jackson-dataformat-yaml</artifactId>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<version>2.8.6</version>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
<version>21.0.1</version>
</dependency>
<dependency>
<artifactId>jackson-dataformat-smile</artifactId>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.6</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-smile</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<artifactId>jackson-dataformat-cbor</artifactId>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-cbor</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
@ -235,7 +235,7 @@
<version>2.6</version>
</dependency>
<!-- Please note that the elasticsearch client needs a compress-lzf version
<!-- Please note that the elasticsearch client needs a compress-lzf version
>= 1.0.2 -->
<dependency>
<groupId>com.ning</groupId>
@ -391,24 +391,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
<additionalJOption>-Xdoclint:none</additionalJOption>
</configuration>
<version>3.1.0</version>
<executions>
<execution>
<id>generate-doc</id>
<phase>install</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -35,6 +35,11 @@ import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
@ -47,9 +52,9 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
*/
@Path("2/users")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class Users {
// Logger
@ -228,7 +233,7 @@ public class Users {
}
return Response.status(status).entity(responseBean).build();
}
private static final Function<GCubeUser, UserProfileExtendedWithVerifiedEmail> GCUBE_TO_EXTENDED_PROFILE_MAP_WITH_VERIFIED_EMAIL
= new Function<GCubeUser, UserProfileExtendedWithVerifiedEmail>() {
@ -250,7 +255,7 @@ public class Users {
return profile;
}
};
/**
* @responseExample application/json {
"id": "john.smith",
@ -367,7 +372,7 @@ public class Users {
return Response.status(status).entity(responseBean).build();
}
/**
* Get the map of couples username/fullname of the users belonging to a given context
* @return the map of couples username/fullname of the users belonging to the context linked to the provided token.
@ -472,6 +477,13 @@ public class Users {
return Response.status(status).entity(responseBean).build();
}
private static final String REALM_NAME = "d4science";
private static final String clientId = "id.d4science.org";
private static final String SERVER_URL = "https://accounts.dev.d4science.org/auth";
private static final String client_secret = "09c26f24-3c65-4039-9fa0-e5cc4f4032cd";
/**
* @pathExample /get-usernames-by-role?role-name=VRE-Manager
* @param roleName the role name
@ -493,51 +505,100 @@ public class Users {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
String context = ScopeProvider.instance.get();
Keycloak keycloak;
keycloak = KeycloakBuilder.builder()
.serverUrl(SERVER_URL)
.realm("d4science")
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId(clientId) //
.clientSecret(client_secret).build();
List<String> usernames = new ArrayList<String>();
try{
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
long roleId = roleManager.getRoleIdByName(roleName);
if(roleId > 0){
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
List<GCubeUser> users = null;
long groupId = groupManager.getGroupIdFromInfrastructureScope(context);
// first check if for any reason this is a global role, then (if result is null or exception arises) check for site role
// Global role's users are retrieved much faster
try{
if(GLOBAL_ROLES_ALLOWED_BY_LOCAL_CALL_METHOD.contains(roleName)){
// TODO inconsistent value can be returned
users = userManager.listUsersByGlobalRole(roleId);
}
}catch(Exception globalExp){
logger.warn("Failed while checking for global role... trying with local one", globalExp);
try {
List<UserRepresentation> users = searchByRole(keycloak, context, roleName);
if(users != null){
for (UserRepresentation user : users) {
usernames.add(user.getUsername());
}
if(users == null || users.isEmpty()){
logger.debug("User list is still null/empty, checking for local information");
users = userManager.listUsersByGroupAndRole(groupId, roleId);
}
if(users != null){
for (GCubeUser gCubeUser : users) {
usernames.add(gCubeUser.getUsername());
}
}
responseBean.setResult(usernames);
responseBean.setSuccess(true);
}else{
responseBean.setMessage("No role exists whit such a name");
status = Status.BAD_REQUEST;
}
}catch(Exception e){
logger.error("Unable to retrieve user's usernames", e);
responseBean.setResult(usernames);
responseBean.setSuccess(true);
} catch(Exception e){
logger.error("Unable to retrieve user with the requested role", e);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
// try{
// GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
// RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
// long roleId = roleManager.getRoleIdByName(roleName);
// if(roleId > 0){
// UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
// List<GCubeUser> users = null;
// long groupId = groupManager.getGroupIdFromInfrastructureScope(context);
// // first check if for any reason this is a global role, then (if result is null or exception arises) check for site role
// // Global role's users are retrieved much faster
// try{
// if(GLOBAL_ROLES_ALLOWED_BY_LOCAL_CALL_METHOD.contains(roleName)){
// // TODO inconsistent value can be returned
// users = userManager.listUsersByGlobalRole(roleId);
// }
// }catch(Exception globalExp){
// logger.warn("Failed while checking for global role... trying with local one", globalExp);
// }
//
// if(users == null || users.isEmpty()){
// logger.debug("User list is still null/empty, checking for local information");
// users = userManager.listUsersByGroupAndRole(groupId, roleId);
// }
//
// if(users != null){
// for (GCubeUser gCubeUser : users) {
// usernames.add(gCubeUser.getUsername());
// }
// }
// responseBean.setResult(usernames);
// responseBean.setSuccess(true);
// }else{
// responseBean.setMessage("No role exists whit such a name");
// status = Status.BAD_REQUEST;
// }
// }catch(Exception e){
// logger.error("Unable to retrieve user's usernames", e);
// responseBean.setMessage(e.getMessage());
// status = Status.INTERNAL_SERVER_ERROR;
// }
return Response.status(status).entity(responseBean).build();
}
private static List<UserRepresentation> searchByRole(Keycloak keycloak, String context, String roleName) {
logger.info("Searching by role: {}", roleName);
String clientIdContext = context.replace("/", "%2F") ;
List<ClientRepresentation> clients = keycloak.realm(REALM_NAME)
.clients().findByClientId(clientIdContext);
String id = "";
for (ClientRepresentation client : clients) {
logger.info("found client ="+client.getClientId());
logger.info("found client id="+client.getId());
id =client.getId();
}
List<UserRepresentation> users = keycloak.realm(REALM_NAME)
.clients()
.get(id).roles().get(roleName)
.getUserMembers(0, 100000);
return users;
}
@GET
@Path("user-exists")
@Produces(MediaType.APPLICATION_JSON)