package org.gcube.common.authorization.utils.secret; import java.util.Map; import java.util.Objects; import org.gcube.common.authorization.library.ClientType; import org.gcube.common.authorization.library.exception.AuthorizationException; import org.gcube.common.authorization.library.provider.AuthorizationProvider; import org.gcube.common.authorization.library.provider.ClientInfo; import org.gcube.common.authorization.library.utils.Caller; import org.gcube.common.authorization.utils.user.User; import org.gcube.common.scope.api.ScopeProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Luca Frosini (ISTI - CNR) */ public abstract class Secret implements Comparable { protected static final Logger logger = LoggerFactory.getLogger(Secret.class); protected int priority; protected String token; protected User user; protected void check(String token) throws AuthorizationException { if(token == null) { throw new AuthorizationException("token cannot be null"); } if(token.compareTo("")==0) { throw new AuthorizationException("token cannot be an empty string"); } } protected Secret(int priority, String token) { this.priority = priority; check(token); this.token = token; } public String getToken() { return token; } public void set() throws Exception { setToken(); setAuthorizationProvider(); ScopeProvider.instance.set(getContext()); } public abstract void setToken() throws Exception; public abstract void resetToken() throws Exception; public abstract ClientInfo getClientInfo() throws Exception; public abstract Caller getCaller() throws Exception; public void setAuthorizationProvider() throws Exception { Caller caller = getCaller(); AuthorizationProvider.instance.set(caller); } public abstract String getContext() throws Exception; public String getUsername() throws Exception { return getClientInfo().getId(); } public boolean isApplication() throws Exception { return getClientInfo().getType() == ClientType.EXTERNALSERVICE; } public abstract Map getHTTPAuthorizationHeaders(); @Override public int hashCode() { return Objects.hash(priority, token); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Secret other = (Secret) obj; return priority == other.priority && Objects.equals(token, other.token); } @Override public int compareTo(Secret obj) { if (this == obj) { return 0; } if (obj == null) { return priority; } if (getClass() != obj.getClass()) { return priority; } return token.compareTo(obj.token); } public void reset() throws Exception { resetToken(); AuthorizationProvider.instance.reset(); ScopeProvider.instance.reset(); } public abstract boolean isExpired(); public abstract boolean isRefreshable(); public abstract User getUser(); }