package com.dexels.oauth.web; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dexels.oauth.api.Client; import com.dexels.oauth.api.ClientStoreFactory; import com.dexels.oauth.api.Scope; import com.dexels.oauth.api.ScopeStoreFactory; import com.dexels.oauth.web.exceptions.OAuthClientException; import com.dexels.oauth.web.exceptions.OAuthServerException; public abstract class OAuthCommandBase { private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern .compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); protected HttpServletRequest request; protected HttpServletResponse response; protected Client client; protected String tenant; protected Set scopes = new HashSet<>(); public OAuthCommandBase(HttpServletRequest request, HttpServletResponse response) throws OAuthClientException { this.request = request; this.response = response; tenant = request.getParameter("tenant"); if (tenant == null) { throw new OAuthClientException("Missing tenant parameter"); } String clientId = request.getParameter("client_id"); if (clientId == null) { throw new OAuthClientException("Missing client_id parameter"); } client = ClientStoreFactory.getInstance().find(tenant, clientId); if (client == null) { throw new OAuthClientException("Invalid client_id"); } String scopesString = request.getParameter("scope"); if (scopesString != null && !scopesString.trim().equals("")) { String splitter = " "; if (scopesString.contains(",")) { splitter = ","; } for (String scopeString : scopesString.split(splitter)) { // check if the requested scope exists in the scopestore Scope scope = ScopeStoreFactory.getInstance().getScope(tenant, scopeString); if (scope != null) { // check if we don't have this scope already and if it's part of this client // optional scopes if (!scopes.contains(scope) && client.getOptionalScopes().contains(scope)) { scopes.add(scope); } } else { throw new OAuthClientException("The requested scope is invalid, unknown, or malformed."); } } } } public abstract void execute() throws OAuthServerException; protected String createAbsolute(String relative) { String forwardedProto = request.getHeader("X-Forwarded-Proto"); String host = request.getHeader("Host"); if (forwardedProto == null) { forwardedProto = "http"; } return String.format("%s://%s%s", forwardedProto, host, relative); } protected boolean isValidPassword(String password) { return password != null && password.length() >= 8; } protected boolean isValidUsername(String username) { return username != null && VALID_EMAIL_ADDRESS_REGEX.matcher(username).find() && username.length() < 64; } }