common-security/src/main/java/org/gcube/common/security/AuthorizedTasks.java

105 lines
2.6 KiB
Java

package org.gcube.common.security;
import java.util.concurrent.Callable;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AuthorizedTasks {
private static Logger logger= LoggerFactory.getLogger(AuthorizedTasks.class);
/**
* Binds a {@link Callable} task to the current scope and user.
* @param task the task
* @return an equivalent {@link Callable} task bound to the current scope and user
*/
static public <V> Callable<V> bind(final Callable<V> task) {
final Secret secret = SecretManagerProvider.get();
return new Callable<V>() {
@Override
public V call() throws Exception {
SecretManagerProvider.set(secret);
try {
logger.info("setting on authorized task context {} ", secret.getContext());
return task.call();
}
finally {
SecretManagerProvider.reset();
}
}
};
}
/**
* Binds a {@link Runnable} task to the current scope and user.
* @param task the task
* @return an equivalent {@link Runnable} task bound to the current scope and user
*/
static public <V> Runnable bind(final Runnable task) {
final Secret secret = SecretManagerProvider.get();
return new Runnable() {
@Override
public void run() {
SecretManagerProvider.set(secret);
try {
logger.info("setting on authorized task context {} ", secret.getContext());
task.run();
}
finally {
SecretManagerProvider.reset();
}
}
};
}
/**
* Execute a runnable inline with set and reset of the SecretManagerProvider
* @param task the task
* @param secret the secret that must be used in the function
* @return an equivalent {@link Runnable} task bound to the current scope and user
*/
static public void executeSafely(final Runnable task, final Secret secret){
Secret previousSecret = SecretManagerProvider.get();
try {
SecretManagerProvider.set(secret);
task.run();
} finally {
SecretManagerProvider.set(previousSecret);
}
}
/**
* Execute a callable inline with set and reset of the SecretManagerProvider
* @param task the task
* @param secret the secret that must be used in the function
* @return an equivalent {@link Runnable} task bound to the current scope and user
*/
static public <T> T executeSafely(final Callable<T> task, final Secret secret) throws Throwable {
Secret previousSecret = SecretManagerProvider.get();
try {
SecretManagerProvider.set(secret);
return task.call();
} finally {
SecretManagerProvider.set(previousSecret);
}
}
}