gcat/src/main/java/org/gcube/gcat/utils/Constants.java

62 lines
2.2 KiB
Java

package org.gcube.gcat.utils;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.model.TokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class Constants {
private static final Logger logger = LoggerFactory.getLogger(Constants.class);
public static final String CATALOGUE_NAME = "gCat";
protected static final String CLIENT_SECRET_FILENAME = "config.properties";
protected static final String CLIENT_ID = "gcat";
protected static String clientSecret;
private static String getClientSecret(String context) {
try {
if(clientSecret==null) {
Properties properties = new Properties();
URL url = Constants.class.getClassLoader().getResource(CLIENT_SECRET_FILENAME);
logger.trace("Going to read {} at {}", CLIENT_SECRET_FILENAME, url.toString());
InputStream input = ClassLoader.getSystemClassLoader().getResourceAsStream(CLIENT_SECRET_FILENAME);
properties.load(input);
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
clientSecret = properties.getProperty(root);
}
return clientSecret;
} catch(Exception e) {
throw new InternalServerErrorException(
"Unable to retrieve Application Token for context " + SecretManagerProvider.instance.get().getContext(), e);
}
}
private static TokenResponse getJWTAccessToken() throws Exception {
String contextToAuthorise = SecretManagerProvider.instance.get().getContext();
TokenResponse tr = KeycloakClientFactory.newInstance().queryUMAToken(CLIENT_ID, getClientSecret(contextToAuthorise), contextToAuthorise, null);
return tr;
}
public static Secret getCatalogueSecret() throws Exception {
TokenResponse tr = getJWTAccessToken();
Secret secret = new JWTSecret(tr.getAccessToken());
return secret;
}
}