reorganized packages

This commit is contained in:
Alfredo Oliviero 2024-02-26 17:40:13 +01:00
parent 2fc47d8d21
commit d6257cf520
19 changed files with 539 additions and 110 deletions

View File

@ -1,28 +0,0 @@
package org.gcube.idm;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.gcube.idm.rest.TestRest;
/**
* @author Alfredo Oliviero (ISTI - CNR)
*/
// SMARTGEARS
// legge i parametri del service da application.yaml
@Path("idm")
public class IdentityManagerApplication extends Application {
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register resources and features
classes.add(TestRest.class);
return classes;
}
}

View File

@ -1,65 +0,0 @@
package org.gcube.idm;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.smartgears.ApplicationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Alfredo gOliviero (ISTI - CNR)
*/
public class IdentityManagerApplicationManager implements ApplicationManager {
/**
* Logger
*/
private static Logger logger = LoggerFactory.getLogger(IdentityManagerApplicationManager.class);
public static boolean initialised;
/**
* {@inheritDoc}
*/
@Override
public synchronized void onInit() {
String context = SecretManagerProvider.get().getContext();
logger.trace(
"\n-------------------------------------------------------\n"
+ "Identity Manager Service is Starting on context {}\n"
+ "-------------------------------------------------------",
context);
// ApplicationContext applicationContext = ContextProvider.get();
// String helloWorldEServiceID = applicationContext.id();
logger.trace(
"\n-------------------------------------------------------\n"
+ "Identity Manager Service Started Successfully on context {}\n"
+ "-------------------------------------------------------",
context);
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void onShutdown() {
String context = SecretManagerProvider.get().getContext();
logger.trace(
"\n-------------------------------------------------------\n"
+ "Identity Manager Service is Stopping on context {}\n"
+ "-------------------------------------------------------",
context);
logger.trace(
"\n-------------------------------------------------------\n"
+ "Identity Manager Service Stopped Successfully on context {}\n"
+ "-------------------------------------------------------",
context);
}
}

View File

@ -0,0 +1,28 @@
package org.gcube.service.idm;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.gcube.service.idm.test.services.AuthenticatedService;
import org.gcube.service.idm.test.services.ExcludeAuthorizationService;
import org.gcube.service.idm.test.services.HelloService;
/**
* @author Alfredo Oliviero (ISTI - CNR)
*/
@ApplicationPath("")
public class IdM extends Application {
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register resources and features
classes.add(HelloService.class);
classes.add(ExcludeAuthorizationService.class);
classes.add(AuthenticatedService.class);
return classes;
}
}

View File

@ -0,0 +1,58 @@
package org.gcube.service.idm;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.ApplicationManager;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.configuration.Mode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* This class is use to Manage the application initialization and shutdown per
* context; The init and shutdown methods are called one per context in which
* the app is running respectively at init and a shutdown time. It is connected
* to the app declaring it via the @ManagedBy annotation. (@see HelloWorld
* class)
*
* @author Alfredo gOliviero (ISTI - CNR)
*/
public class IdMManager implements ApplicationManager {
Logger logger = LoggerFactory.getLogger(IdMManager.class);
/**
* {@inheritDoc}
*/
@Override
public void onInit() {
if (ContextProvider.get().container().configuration().mode() == Mode.offline) {
logger.debug("init called in offline mode");
} else {
Secret secret = SecretManagerProvider.get();
if (secret != null) {
logger.debug("init called in context {}", secret.getContext());
} else {
logger.debug("init called in null context");
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void onShutdown() {
if (ContextProvider.get().container().configuration().mode() == Mode.offline) {
logger.debug("shutDown called in offline mode");
} else {
Secret secret = SecretManagerProvider.get();
if (secret != null) {
logger.debug("shutDown called in context {}", secret.getContext());
} else {
logger.debug("shutDown called in null context");
}
}
}
}

View File

@ -0,0 +1,45 @@
package org.gcube.service.idm.health;
import java.io.File;
import java.io.IOException;
import org.gcube.common.health.api.HealthCheck;
import org.gcube.common.health.api.ReadinessChecker;
import org.gcube.common.health.api.response.HealthCheckResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* this class is used to add checks about components used by the service (DB,
* external FS, other services etc. )
* and automatically exposed using the REST method webapp/gcube/resources/health
*
*
* @author lucio
*
*/
@ReadinessChecker
public class CreateTempFileCheck implements HealthCheck {
private static Logger log = LoggerFactory.getLogger(CreateTempFileCheck.class);
@Override
public String getName() {
return "create temp file";
}
@Override
public HealthCheckResponse check() {
try {
File.createTempFile("exampleTest", "txt");
return HealthCheckResponse.builder(getName()).up().info("health check example").build();
} catch (IOException e) {
log.error("error checking defaultStorage", e);
return HealthCheckResponse.builder(getName()).down().error(e.getMessage()).build();
}
}
}

View File

@ -1,4 +1,4 @@
package org.gcube.idm.rest;
package org.gcube.service.idm.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@ -7,24 +7,24 @@ import javax.ws.rs.core.MediaType;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.idm.IdentityManagerApplicationManager;
import org.gcube.service.idm.IdMManager;
import org.gcube.smartgears.annotations.ManagedBy;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
// import com.webcohesion.enunciate.metadata.rs.RequestHeader;
// import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
// import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
// import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
@ManagedBy(IdentityManagerApplicationManager.class)
@ManagedBy(IdMManager.class)
@Path("/test")
@ResourceGroup("test")
@ResourceLabel("test")
@RequestHeaders({
@RequestHeader(name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
})
// @ResourceGroup("test")
// @ResourceLabel("test")
// @RequestHeaders({
// @RequestHeader(name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
// })
public class TestRest {
private final Logger logger = LoggerFactory.getLogger(TestRest.class);

View File

@ -1,4 +1,4 @@
package org.gcube.idm.rest;
package org.gcube.service.idm.rest;
import org.gcube.common.authorization.library.policies.Users;
import org.slf4j.LoggerFactory;

View File

@ -0,0 +1,45 @@
package org.gcube.service.idm.serializers;
import java.io.IOException;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for ContainerConfiguration
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class ContainerConfigurationSerializer extends StdSerializer<ContainerConfiguration> {
protected ContainerConfigurationSerializer(Class<ContainerConfiguration> t) {
super(t);
}
public ContainerConfigurationSerializer() {
super(ContainerConfiguration.class, true);
}
@Override
public void serialize(ContainerConfiguration configuration, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeObjectField("mode", configuration.mode());
jgen.writeObjectField("app", configuration.apps());
jgen.writeObjectField("site", configuration.site());
jgen.writeObjectField("infrastructure", configuration.infrastructure());
jgen.writeObjectField("hostname", configuration.hostname());
jgen.writeObjectField("port", configuration.port());
jgen.writeObjectField("protocol", configuration.protocol());
jgen.writeObjectField("authorizeChildrenContext", configuration.authorizeChildrenContext());
jgen.writeObjectField("proxy", configuration.proxy());
jgen.writeObjectField("desc", configuration.toString());
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,42 @@
package org.gcube.service.idm.serializers;
import java.io.IOException;
import org.gcube.smartgears.context.container.ContainerContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for ContainerContext
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class ContainerContextSerializer extends StdSerializer<ContainerContext> {
protected ContainerContextSerializer(Class<ContainerContext> t) {
super(t);
}
public ContainerContextSerializer() {
super(ContainerContext.class, true);
}
@Override
public void serialize(ContainerContext ccontext, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeStringField("id", ccontext.id());
// jgen.writeObjectField("configuration.site", ccontext.configuration().site());
// jgen.writeObjectField("configuration", ccontext.configuration());
jgen.writeObjectField("properties", ccontext.properties());
jgen.writeObjectField("authorizationProvider", ccontext.authorizationProvider());
jgen.writeObjectField("configuration", ccontext.configuration());
jgen.writeObjectField("desc", ccontext.toString());
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,36 @@
package org.gcube.service.idm.serializers;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.security.SimpleCredentials;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
/**
* Jackson Serialization utils for Smartgear Context classes
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class ContextSerializator {
private static ObjectMapper serializer = null;
public static ObjectMapper getSerializer() {
if (serializer == null) {
ObjectMapper om = new ObjectMapper();
SimpleModule module = new SimpleModule();
// module.addSerializer(Owner.class, new OwnerSerializer());
module.addSerializer(ContainerConfiguration.class, new ContainerConfigurationSerializer());
module.addSerializer(ContainerContext.class, new ContainerContextSerializer());
module.addSerializer(SimpleCredentials.class, new SimpleCredentialsSerializer());
om.registerModule(module);
serializer = om;
}
return serializer;
}
}

View File

@ -0,0 +1,47 @@
package org.gcube.service.idm.serializers;
import java.io.IOException;
import org.gcube.common.security.Owner;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for Owner
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class OwnerSerializer extends StdSerializer<Owner> {
protected OwnerSerializer(Class<Owner> t) {
super(t);
}
public OwnerSerializer() {
super(Owner.class, true);
}
@Override
public void serialize(Owner owner, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField("ownerId", owner.getId());
jgen.writeStringField("clientName", owner.getClientName());
jgen.writeArrayFieldStart("roles");
for (String role : owner.getRoles()) {
jgen.writeString(role);
}
jgen.writeEndArray();
jgen.writeStringField("email", owner.getEmail());
jgen.writeStringField("firstName", owner.getFirstName());
jgen.writeStringField("lastName", owner.getLastName());
jgen.writeBooleanField("externalClient", owner.isExternalClient());
jgen.writeStringField("contactPerson", owner.getClientName());
jgen.writeStringField("contactOrganisation", owner.getContactOrganisation());
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,36 @@
package org.gcube.service.idm.serializers;
import java.io.IOException;
import org.gcube.smartgears.security.SimpleCredentials;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for SimpleCredentials
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class SimpleCredentialsSerializer extends StdSerializer<SimpleCredentials> {
protected SimpleCredentialsSerializer(Class<SimpleCredentials> t) {
super(t);
}
public SimpleCredentialsSerializer() {
super(SimpleCredentials.class, true);
}
@Override
public void serialize(SimpleCredentials credentials, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeStringField("clientId", credentials.getClientID());
jgen.writeStringField("secret", "[*****]");
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,67 @@
package org.gcube.service.idm.test.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.utils.InnerMethodName;
/**
* @author Lucio Le (ISTI - CNR)
* @author Alfredo Oliviero (ISTI - CNR)
*/
@Path("auth")
public class AuthenticatedService {
private static final String ALLOWED_ROLE = "myRole";
private static final String ALLOWED_ROLE_ORG = "OrganizationMember";
private static final String ALLOWED_ROLE_MEMBER = "Member";
@AuthorizationControl(allowedRoles = { ALLOWED_ROLE_ORG })
@GET
@Path("org_member")
@Produces(MediaType.TEXT_PLAIN)
public String authorizedOrg() {
InnerMethodName.set("auth");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
return String.format(
"User %s in context %s is authorized to execute this method because he has the role %s", userId,
context, ALLOWED_ROLE_ORG);
}
@AuthorizationControl(allowedRoles = { ALLOWED_ROLE_MEMBER })
@GET
@Path("member")
@Produces(MediaType.TEXT_PLAIN)
public String authorizedMember() {
InnerMethodName.set("auth");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
return String.format(
"User %s in context %s is authorized to execute this method because he has the role %s", userId,
context, ALLOWED_ROLE_MEMBER);
}
@AuthorizationControl(allowedRoles = { ALLOWED_ROLE })
@GET
@Path("")
@Produces(MediaType.TEXT_PLAIN)
public String authorized() {
InnerMethodName.set("auth");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
return String.format(
"User %s in context %s is authorized to execute this method because he has the role %s", userId,
context, ALLOWED_ROLE);
}
}

View File

@ -0,0 +1,31 @@
package org.gcube.service.idm.test.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("guest")
public class ExcludeAuthorizationService {
private final Logger logger = LoggerFactory.getLogger(ExcludeAuthorizationService.class);
/**
* this method doesn't need authorization and the SecretManagerProvider is null
* see to implement this behavior add to excludes section in your
* application.yaml
*
* - path: /{path-to-your-method-path}
*
* example for this method
*
* - path: /excluded
*
*/
@GET
public String exludedMethod() {
logger.info("executed whithout any authorization");
return "executed whithout any authorization";
}
}

View File

@ -0,0 +1,87 @@
package org.gcube.service.idm.test.services;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gcube.common.security.Owner;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.service.idm.IdMManager;
import org.gcube.service.idm.serializers.ContextSerializator;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.annotations.ManagedBy;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @author Lucio Lelii (ISTI-CNR)
* @author Alfredo Oliviero (ISTI-CNR)
*/
@ManagedBy(IdMManager.class)
@Path("")
public class HelloService {
private final Logger logger = LoggerFactory.getLogger(HelloService.class);
@GET
@Path("hello")
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
InnerMethodName.set("hello");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
String infrastructureName = ContextProvider.get().container().configuration().infrastructure();
logger.info("caller id is {}", userId);
return String.format("Hello %s in context %s in infastructure %s -roles %s", userId, context,
infrastructureName, secret.getOwner().getRoles());
}
@GET
@Path("details")
@Produces({ MediaType.APPLICATION_JSON })
public Response details() {
InnerMethodName.set("details");
Map<String, Object> data = new HashMap<>();
Secret secret = SecretManagerProvider.get();
String context = secret.getContext();
data.put("context", context);
Owner owner = secret.getOwner();
data.put("owner", owner);
ContainerContext container = ContextProvider.get().container();
data.put("container", container);
ObjectMapper objectMapper = ContextSerializator.getSerializer();
try {
String jsonData = objectMapper.writeValueAsString(data);
return Response.ok(jsonData).build();
} catch (JsonProcessingException e) {
e.printStackTrace();
return Response.serverError().build();
}
}
}

View File

@ -1,4 +1,4 @@
package org.gcube.rest;
package org.gcube.service.rest;
import java.io.Serializable;

View File

@ -1,4 +1,4 @@
package org.gcube.rest.annotation;
package org.gcube.service.rest.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View File

@ -1,4 +1,4 @@
package org.gcube.rest.annotation;
package org.gcube.service.rest.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View File

@ -1,4 +1,4 @@
package org.gcube.rest.utils;
package org.gcube.service.rest.utils;
import java.io.BufferedReader;
import java.io.IOException;