120 lines
2.5 KiB
Java
120 lines
2.5 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.instance.get();
|
|
|
|
return new Callable<V>() {
|
|
@Override
|
|
public V call() throws Exception {
|
|
|
|
SecretManagerProvider.instance.set(secret);
|
|
|
|
try {
|
|
logger.info("setting on authorized task context {} ", secret.getContext());
|
|
return task.call();
|
|
}
|
|
finally {
|
|
SecretManagerProvider.instance.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.instance.get();
|
|
|
|
return new Runnable() {
|
|
@Override
|
|
public void run() {
|
|
|
|
SecretManagerProvider.instance.set(secret);
|
|
|
|
try {
|
|
logger.info("setting on authorized task context {} ", secret.getContext());
|
|
task.run();
|
|
}
|
|
finally {
|
|
SecretManagerProvider.instance.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 void executeSafely(final Runnable task, final Secret secret) throws Throwable {
|
|
|
|
SafelyExecution se = new SafelyExecution(new Runnable() {
|
|
|
|
@Override
|
|
public void run() {
|
|
SecretManagerProvider.instance.set(secret);
|
|
|
|
try {
|
|
logger.info("setting on authorized task context {} ", secret.getContext());
|
|
task.run();
|
|
}finally {
|
|
SecretManagerProvider.instance.reset();
|
|
}
|
|
|
|
}
|
|
});
|
|
|
|
se.run();
|
|
|
|
if (se.e != null) throw se.e;
|
|
|
|
}
|
|
|
|
static private class SafelyExecution extends Thread{
|
|
|
|
protected Throwable e;
|
|
|
|
public SafelyExecution(Runnable target) {
|
|
super(target);
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
try {
|
|
super.run();
|
|
}catch (Throwable t) {
|
|
e = t;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
}
|