wms-winstone-1.0.5

ppConfiguration.getTextFromNode(loginElm);
        }
      }
    }
    constraints = new SecurityConstraint[constraintNodes.size()];
    for (int n = 0; n < constraints.length; n++) {
      constraints[n] = new SecurityConstraint((Node)constraintNodes.get(n), rolesAllowed, n);
    }
  }
  
  public boolean processAuthentication(ServletRequest inRequest, ServletResponse inResponse, String pathRequested)
    throws IOException, ServletException
  {
    logger.debug("Starting authentication check");
    
    HttpServletRequest request = (HttpServletRequest)inRequest;
    HttpServletResponse response = (HttpServletResponse)inResponse;
    if (!validatePossibleAuthenticationResponse(request, response, pathRequested)) {
      return Boolean.FALSE.booleanValue();
    }
    return doRoleCheck(request, response, pathRequested);
  }
  
  protected boolean doRoleCheck(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException, ServletException
  {
    boolean foundApplicable = Boolean.FALSE.booleanValue();
    for (int n = 0; (n < constraints.length) && (!foundApplicable); n++)
    {
      logger.debug("Evaluating security constraint: {}", constraints[n].getName());
      if (constraints[n].isApplicable(pathRequested, request.getMethod()))
      {
        logger.debug("Found applicable security constraint: {}", constraints[n].getName());
        foundApplicable = Boolean.TRUE.booleanValue();
        if ((constraints[n].needsSSL()) && (!request.isSecure()))
        {
          String msg = "Security constraint requires SSL (failed): " + constraints[n].getName();
          logger.debug(msg);
          response.sendError(403, msg);
          return Boolean.FALSE.booleanValue();
        }
        if (!constraints[n].isAllowed(request))
        {
          requestAuthentication(request, response, pathRequested);
          return Boolean.FALSE.booleanValue();
        }
        setNoCache(response);
      }
    }
    logger.debug("Passed authentication check");
    return Boolean.TRUE.booleanValue();
  }
  
  protected void setNoCache(HttpServletResponse response)
  {
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "No-cache");
    response.setDateHeader("Expires", 1L);
  }
  
  protected abstract void requestAuthentication(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString)
    throws IOException, ServletException;
  
  protected abstract boolean validatePossibleAuthenticationResponse(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString)
    throws ServletException, IOException;
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.BaseAuthenticationHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import net.winstone.core.WinstoneRequest;
import net.winstone.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;

public final class BasicAuthenticationHandler
  extends BaseAuthenticationHandler
{
  protected static Logger logger = LoggerFactory.getLogger(BasicAuthenticationHandler.class);
  
  public BasicAuthenticationHandler(Node loginConfigNode, List constraintNodes, Set rolesAllowed, AuthenticationRealm realm)
  {
    super(loginConfigNode, constraintNodes, rolesAllowed, realm);
    logger.debug("BasicAuthenticationHandler initialised for realm: {}", realmName);
  }
  
  protected void requestAuthentication(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException
  {
    response.setHeader("WWW-Authenticate", "Basic Realm=\"" + realmName + "\"");
    response.sendError(401, "This content can only be viewed by authorized users.");
  }
  
  protected boolean validatePossibleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException
  {
    String authorization = request.getHeader("Authorization");
    if ((authorization != null) && (authorization.toLowerCase().startsWith("basic")))
    {
      char[] inBytes = authorization.substring(5).trim().toCharArray();
      byte[] outBytes = new byte[(int)(inBytes.length * 0.75F)];
      
      int length = Base64.decode(inBytes, outBytes, 0, inBytes.length, 0);
      
      String decoded = new String(outBytes, 0, length);
      int delimPos = decoded.indexOf(':');
      if (delimPos != -1)
      {
        AuthenticationPrincipal principal = realm.authenticateByUsernamePassword(decoded.substring(0, delimPos).trim(), decoded.substring(delimPos + 1).trim());
        if (principal != null)
        {
          principal.setAuthType("BASIC");
          if ((request instanceof WinstoneRequest))
          {
            ((WinstoneRequest)request).setRemoteUser(principal);
          }
          else if ((request instanceof HttpServletRequestWrapper))
          {
            HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper)request;
            if ((wrapper.getRequest() instanceof WinstoneRequest)) {
              ((WinstoneRequest)wrapper.getRequest()).setRemoteUser(principal);
            } else {
              logger.warn("Request type invalid - can't set authenticated user in request class: {}", wrapper.getRequest().getClass().getName());
            }
          }
          else
          {
            logger.warn("Request type invalid - can't set authenticated user in request class: {}", request.getClass().getName());
          }
        }
      }
    }
    return Boolean.TRUE.booleanValue();
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.BasicAuthenticationHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication;

import java.io.IOException;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import net.winstone.core.WinstoneRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;

public final class ClientcertAuthenticationHandler
  extends BaseAuthenticationHandler
{
  protected static Logger logger = LoggerFactory.getLogger(ClientcertAuthenticationHandler.class);
  
  public ClientcertAuthenticationHandler(Node loginConfigNode, List constraintNodes, Set rolesAllowed, AuthenticationRealm realm)
  {
    super(loginConfigNode, constraintNodes, rolesAllowed, realm);
    logger.debug("ClientcertAuthenticationHandler initialised for realm: {}", realmName);
  }
  
  protected void requestAuthentication(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException
  {
    response.sendError(401, "This content can only be viewed by authorized users.");
  }
  
  protected boolean validatePossibleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException
  {
    X509Certificate[] certificateArray = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
    if ((certificateArray != null) && (certificateArray.length > 0))
    {
      boolean failed = Boolean.FALSE.booleanValue();
      for (int n = 0; n < certificateArray.length; n++) {
        try
        {
          certificateArray[n].checkValidity();
        }
        catch (Throwable err)
        {
          failed = Boolean.TRUE.booleanValue();
        }
      }
      if (!failed)
      {
        AuthenticationPrincipal principal = realm.retrieveUser(certificateArray[0].getSubjectDN().getName());
        if (principal != null)
        {
          principal.setAuthType("CLIENT_CERT");
          if ((request instanceof WinstoneRequest))
          {
            ((WinstoneRequest)request).setRemoteUser(principal);
          }
          else if ((request instanceof HttpServletRequestWrapper))
          {
            HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper)request;
            if ((wrapper.getRequest() instanceof WinstoneRequest)) {
              ((WinstoneRequest)wrapper.getRequest()).setRemoteUser(principal);
            } else {
              logger.warn("Request type invalid - can't set authenticated user in request class: {}", wrapper.getRequest().getClass().getName());
            }
          }
          else
          {
            logger.warn("Request type invalid - can't set authenticated user in request class: {}", request.getClass().getName());
          }
        }
      }
    }
    return Boolean.TRUE.booleanValue();
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.ClientcertAuthenticationHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import net.winstone.core.WinstoneRequest;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;

public final class DigestAuthenticationHandler
  extends BaseAuthenticationHandler
{
  protected static Logger logger = LoggerFactory.getLogger(DigestAuthenticationHandler.class);
  private final MessageDigest md5Digester;
  
  public DigestAuthenticationHandler(Node loginConfigNode, List constraintNodes, Set rolesAllowed, AuthenticationRealm realm)
    throws NoSuchAlgorithmException
  {
    super(loginConfigNode, constraintNodes, rolesAllowed, realm);
    md5Digester = MessageDigest.getInstance("MD5");
    logger.debug("DigestAuthenticationHandler initialised for realm: {}", realmName);
  }
  
  protected void requestAuthentication(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException
  {
    String oneTimeToken = "WinstoneToken:" + new Random().nextDouble() * System.currentTimeMillis();
    
    String authHeader = "Digest realm=\"" + realmName + "\", qop=\"auth\", " + "nonce=\"" + oneTimeToken + "\", opaque=\"" + md5Encode(oneTimeToken) + "\"";
    response.setHeader("WWW-Authenticate", authHeader);
    
    response.sendError(401, "This content can only be viewed by authorized users.");
  }
  
  protected boolean validatePossibleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws IOException
  {
    String authorization = request.getHeader("Authorization");
    if (authorization == null) {
      return Boolean.TRUE.booleanValue();
    }
    if (!authorization.startsWith("Digest")) {
      return Boolean.TRUE.booleanValue();
    }
    String userName = null;
    String realm = null;
    String qop = null;
    String algorithm = null;
    String uri = null;
    String nOnce = null;
    String nc = null;
    String cnOnce = null;
    String clientResponseDigest = null;
    
    StringTokenizer st = new StringTokenizer(authorization.substring(6).trim(), ",");
    while (st.hasMoreTokens())
    {
      String token = st.nextToken().trim();
      int equalPos = token.indexOf('=');
      String paramName = token.substring(0, equalPos);
      if (paramName.equals("username")) {
        userName = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("realm")) {
        realm = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("qop")) {
        qop = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("algorithm")) {
        algorithm = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("uri")) {
        uri = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("nonce")) {
        nOnce = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("nc")) {
        nc = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("cnonce")) {
        cnOnce = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      } else if (paramName.equals("response")) {
        clientResponseDigest = StringUtils.replace(token.substring(equalPos + 1).trim(), "\"", "");
      }
    }
    if ((userName == null) || (realm == null) || (qop == null) || (uri == null) || (nOnce == null) || (nc == null) || (cnOnce == null) || (clientResponseDigest == null)) {
      return Boolean.TRUE.booleanValue();
    }
    if ((algorithm != null) && (!algorithm.equals("MD5"))) {
      return Boolean.TRUE.booleanValue();
    }
    AuthenticationPrincipal principal = this.realm.retrieveUser(userName);
    if (principal == null) {
      return Boolean.TRUE.booleanValue();
    }
    String userRealmPasswordDigest = md5Encode(userName + ":" + realm + ":" + principal.getPassword());
    String methodURIDigest = md5Encode(request.getMethod() + ":" + uri);
    String serverResponseDigest = md5Encode(userRealmPasswordDigest + ":" + nOnce + ":" + nc + ":" + cnOnce + ":" + qop + ":" + methodURIDigest);
    if (serverResponseDigest.equals(clientResponseDigest))
    {
      principal.setAuthType("DIGEST");
      if ((request instanceof WinstoneRequest))
      {
        ((WinstoneRequest)request).setRemoteUser(principal);
      }
      else if ((request instanceof HttpServletRequestWrapper))
      {
        HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper)request;
        if ((wrapper.getRequest() instanceof WinstoneRequest)) {
          ((WinstoneRequest)wrapper.getRequest()).setRemoteUser(principal);
        } else {
          logger.warn("Request type invalid - can't set authenticated user in request class: {}", wrapper.getRequest().getClass().getName());
        }
      }
      else
      {
        logger.warn("Request type invalid - can't set authenticated user in request class: {}", request.getClass().getName());
      }
    }
    return Boolean.TRUE.booleanValue();
  }
  
  public String md5Encode(String input)
    throws UnsupportedEncodingException
  {
    byte[] digestBytes = md5Digester.digest(input.getBytes("8859_1"));
    
    char[] outArray = new char[32];
    for (int n = 0; n < digestBytes.length; n++)
    {
      int hiNibble = (digestBytes[n] & 0xFF) >> 4;
      int loNibble = digestBytes[n] & 0xF;
      outArray[(2 * n)] = (hiNibble > 9 ? (char)(hiNibble + 87) : (char)(hiNibble + 48));
      outArray[(2 * n + 1)] = (loNibble > 9 ? (char)(loNibble + 87) : (char)(loNibble + 48));
    }
    return new String(outArray);
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.DigestAuthenticationHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.winstone.core.WebAppConfiguration;
import net.winstone.core.WinstoneRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FormAuthenticationHandler
  extends BaseAuthenticationHandler
{
  protected static Logger logger = LoggerFactory.getLogger(FormAuthenticationHandler.class);
  private static final transient String ELEM_FORM_LOGIN_CONFIG = "form-login-config";
  private static final transient String ELEM_FORM_LOGIN_PAGE = "form-login-page";
  private static final transient String ELEM_FORM_ERROR_PAGE = "form-error-page";
  private static final transient String FORM_ACTION = "j_security_check";
  private static final transient String FORM_USER = "j_username";
  private static final transient String FORM_PASS = "j_password";
  private static final transient String AUTHENTICATED_USER = "winstone.auth.FormAuthenticationHandler.AUTHENTICATED_USER";
  private static final transient String CACHED_REQUEST = "winstone.auth.FormAuthenticationHandler.CACHED_REQUEST";
  private String loginPage;
  private String errorPage;
  
  public FormAuthenticationHandler(Node loginConfigNode, List constraintNodes, Set rolesAllowed, AuthenticationRealm realm)
  {
    super(loginConfigNode, constraintNodes, rolesAllowed, realm);
    for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++)
    {
      Node loginElm = loginConfigNode.getChildNodes().item(n);
      if (loginElm.getNodeName().equals("form-login-config")) {
        for (int k = 0; k < loginElm.getChildNodes().getLength(); k++)
        {
          Node formElm = loginElm.getChildNodes().item(k);
          if (formElm.getNodeType() == 1) {
            if (formElm.getNodeName().equals("form-login-page")) {
              loginPage = WebAppConfiguration.getTextFromNode(formElm);
            } else if (formElm.getNodeName().equals("form-error-page")) {
              errorPage = WebAppConfiguration.getTextFromNode(formElm);
            }
          }
        }
      }
    }
    logger.debug("FormAuthenticationHandler initialised for realm: {}", realmName);
  }
  
  public boolean processAuthentication(ServletRequest request, ServletResponse response, String pathRequested)
    throws IOException, ServletException
  {
    if ((pathRequested.equals(loginPage)) || (pathRequested.equals(errorPage))) {
      return Boolean.TRUE.booleanValue();
    }
    return super.processAuthentication(request, response, pathRequested);
  }
  
  protected void requestAuthentication(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws ServletException, IOException
  {
    ServletRequest unwrapped = request;
    while ((unwrapped instanceof HttpServletRequestWrapper)) {
      unwrapped = ((HttpServletRequestWrapper)unwrapped).getRequest();
    }
    HttpSession session = request.getSession(Boolean.TRUE.booleanValue());
    session.setAttribute("winstone.auth.FormAuthenticationHandler.CACHED_REQUEST", new RetryRequestParams(unwrapped));
    
    logger.debug("Forwarding to the login page");
    RequestDispatcher rdLogin = request.getRequestDispatcher(loginPage);
    setNoCache(response);
    rdLogin.forward(request, response);
  }
  
  protected boolean validatePossibleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, String pathRequested)
    throws ServletException, IOException
  {
    if (pathRequested.endsWith("j_security_check"))
    {
      String username = request.getParameter("j_username");
      String password = request.getParameter("j_password");
      
      AuthenticationPrincipal principal = realm.authenticateByUsernamePassword(username, password);
      if (principal == null)
      {
        RequestDispatcher rdError = request.getRequestDispatcher(errorPage);
        rdError.forward(request, response);
      }
      else
      {
        ServletRequest wrapperCheck = request;
        while ((wrapperCheck instanceof HttpServletRequestWrapper)) {
          wrapperCheck = ((HttpServletRequestWrapper)wrapperCheck).getRequest();
        }
        WinstoneRequest actualRequest = null;
        if ((wrapperCheck instanceof WinstoneRequest))
        {
          actualRequest = (WinstoneRequest)wrapperCheck;
          actualRequest.setRemoteUser(principal);
        }
        else
        {
          logger.warn("Request type invalid - can't set authenticated user in request class: {}", wrapperCheck.getClass().getName());
        }
        HttpSession session = request.getSession(Boolean.TRUE.booleanValue());
        String previousLocation = loginPage;
        RetryRequestParams cachedRequest = (RetryRequestParams)session.getAttribute("winstone.auth.FormAuthenticationHandler.CACHED_REQUEST");
        if ((cachedRequest != null) && (actualRequest != null))
        {
          request = new RetryRequestWrapper(request, cachedRequest);
          previousLocation = (request.getServletPath() == null ? "" : request.getServletPath()) + (request.getPathInfo() == null ? "" : request.getPathInfo());
        }
        else
        {
          logger.debug("No cached request - redirecting to the login page.");
        }
        if (doRoleCheck(request, response, previousLocation))
        {
          principal.setAuthType("FORM");
          session.setAttribute("winstone.auth.FormAuthenticationHandler.AUTHENTICATED_USER", principal);
          RequestDispatcher rdPrevious = request.getRequestDispatcher(previousLocation);
          rdPrevious.forward(request, response);
        }
        else
        {
          RequestDispatcher rdError = request.getRequestDispatcher(errorPage);
          rdError.forward(request, response);
        }
      }
      return Boolean.FALSE.booleanValue();
    }
    WinstoneRequest actualRequest = null;
    if ((request instanceof WinstoneRequest))
    {
      actualRequest = (WinstoneRequest)request;
    }
    else if ((request instanceof HttpServletRequestWrapper))
    {
      HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper)request;
      if ((wrapper.getRequest() instanceof WinstoneRequest)) {
        actualRequest = (WinstoneRequest)wrapper.getRequest();
      } else {
        logger.warn("Request type invalid - can't set authenticated user in request class: {}", wrapper.getRequest().getClass().getName());
      }
    }
    else
    {
      logger.warn("Request type invalid - can't set authenticated user in request class: {}", request.getClass().getName());
    }
    HttpSession session = actualRequest.getSession(Boolean.FALSE.booleanValue());
    if (session != null)
    {
      AuthenticationPrincipal authenticatedUser = (AuthenticationPrincipal)session.getAttribute("winstone.auth.FormAuthenticationHandler.AUTHENTICATED_USER");
      if (authenticatedUser != null)
      {
        actualRequest.setRemoteUser(authenticatedUser);
        logger.debug("Got authenticated user from session");
      }
    }
    return Boolean.TRUE.booleanValue();
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.FormAuthenticationHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication.realm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import net.winstone.core.authentication.AuthenticationPrincipal;
import net.winstone.core.authentication.AuthenticationRealm;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ArgumentsRealm
  implements AuthenticationRealm
{
  protected static Logger logger = LoggerFactory.getLogger(ArgumentsRealm.class);
  private static final transient String PASSWORD_PREFIX = "argumentsRealm.passwd.";
  private static final transient String ROLES_PREFIX = "argumentsRealm.roles.";
  private final Map<String, String> passwords;
  private final Map<String, List<String>> roles;
  
  public ArgumentsRealm(Set<String> rolesAllowed, Map<String, String> args)
  {
    passwords = new HashMap();
    roles = new HashMap();
    for (Iterator<String> i = args.keySet().iterator(); i.hasNext();)
    {
      String key = (String)i.next();
      if (key.startsWith("argumentsRealm.passwd."))
      {
        String userName = key.substring("argumentsRealm.passwd.".length());
        String password = (String)args.get(key);
        
        String roleList = StringUtils.stringArg(args, "argumentsRealm.roles." + userName, "");
        if (roleList.equals(""))
        {
          logger.warn("WARNING: No roles detected in configuration for user {}", userName);
        }
        else
        {
          StringTokenizer st = new StringTokenizer(roleList, ",");
          List<String> rl = new ArrayList();
          while (st.hasMoreTokens())
          {
            String currentRole = st.nextToken();
            if (rolesAllowed.contains(currentRole)) {
              rl.add(currentRole);
            }
          }
          String[] roleArray = (String[])rl.toArray();
          Arrays.sort(roleArray);
          roles.put(userName, Arrays.asList(roleArray));
        }
        passwords.put(userName, password);
      }
    }
    logger.debug("ArgumentsRealm initialised: users: " + passwords.size());
  }
  
  public AuthenticationPrincipal authenticateByUsernamePassword(String userName, String password)
  {
    if ((userName == null) || (password == null)) {
      return null;
    }
    String realPassword = (String)passwords.get(userName);
    if (realPassword == null) {
      return null;
    }
    if (!realPassword.equals(password)) {
      return null;
    }
    return new AuthenticationPrincipal(userName, password, (List)roles.get(userName));
  }
  
  public AuthenticationPrincipal retrieveUser(String userName)
  {
    if (userName == null) {
      return null;
    }
    return new AuthenticationPrincipal(userName, (String)passwords.get(userName), (List)roles.get(userName));
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.realm.ArgumentsRealm
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication.realm;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import net.winstone.WinstoneException;
import net.winstone.core.authentication.AuthenticationPrincipal;
import net.winstone.core.authentication.AuthenticationRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FileRealm
  implements AuthenticationRealm
{
  protected static Logger logger = LoggerFactory.getLogger(FileRealm.class);
  private static final transient String FILE_NAME_ARGUMENT = "fileRealm.configFile";
  private static final transient String DEFAULT_FILE_NAME = "users.xml";
  private static final transient String ELEM_USER = "user";
  private static final transient String ATT_USERNAME = "username";
  private static final transient String ATT_PASSWORD = "password";
  private static final transient String ATT_ROLELIST = "roles";
  private final Map<String, String> passwords;
  private final Map<String, List<String>> roles;
  
  public FileRealm(Set<String> rolesAllowed, Map<String, String> args)
  {
    passwords = new HashMap();
    roles = new HashMap();
    
    String realmFileName = args.get("fileRealm.configFile") == null ? "users.xml" : (String)args.get("fileRealm.configFile");
    File realmFile = new File(realmFileName);
    if (!realmFile.exists()) {
      throw new WinstoneException("FileRealm could not locate the user file " + realmFile.getPath() + " - disabling security");
    }
    try
    {
      InputStream inFile = new FileInputStream(realmFile);
      Document doc = parseStreamToXML(inFile);
      inFile.close();
      Node rootElm = doc.getDocumentElement();
      for (int n = 0; n < rootElm.getChildNodes().getLength(); n++)
      {
        Node child = rootElm.getChildNodes().item(n);
        if ((child.getNodeType() == 1) && (child.getNodeName().equals("user")))
        {
          String userName = null;
          String password = null;
          String roleList = null;
          for (int j = 0; j < child.getAttributes().getLength(); j++)
          {
            Node thisAtt = child.getAttributes().item(j);
            if (thisAtt.getNodeName().equals("username")) {
              userName = thisAtt.getNodeValue();
            } else if (thisAtt.getNodeName().equals("password")) {
              password = thisAtt.getNodeValue();
            } else if (thisAtt.getNodeName().equals("roles")) {
              roleList = thisAtt.getNodeValue();
            }
          }
          if ((userName == null) || (password == null) || (roleList == null))
          {
            logger.debug("Skipping user {} - details were incomplete", userName);
          }
          else
          {
            StringTokenizer st = new StringTokenizer(roleList, ",");
            List<String> rl = new ArrayList();
            while (st.hasMoreTokens())
            {
              String currentRole = st.nextToken();
              if (rolesAllowed.contains(currentRole)) {
                rl.add(currentRole);
              }
            }
            String[] roleArray = (String[])rl.toArray();
            Arrays.sort(roleArray);
            passwords.put(userName, password);
            roles.put(userName, Arrays.asList(roleArray));
          }
        }
      }
      logger.debug("FileRealm initialised: users:" + passwords.size());
    }
    catch (IOException err)
    {
      throw new WinstoneException("Error loading FileRealm", err);
    }
  }
  
  private Document parseStreamToXML(InputStream in)
  {
    try
    {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setExpandEntityReferences(Boolean.FALSE.booleanValue());
      factory.setValidating(Boolean.FALSE.booleanValue());
      factory.setNamespaceAware(Boolean.FALSE.booleanValue());
      factory.setIgnoringComments(Boolean.TRUE.booleanValue());
      factory.setCoalescing(Boolean.TRUE.booleanValue());
      factory.setIgnoringElementContentWhitespace(Boolean.TRUE.booleanValue());
      DocumentBuilder builder = factory.newDocumentBuilder();
      return builder.parse(in);
    }
    catch (Throwable errParser)
    {
      throw new WinstoneException("Error parsing the users XML document", errParser);
    }
  }
  
  public AuthenticationPrincipal authenticateByUsernamePassword(String userName, String password)
  {
    if ((userName == null) || (password == null)) {
      return null;
    }
    String realPassword = (String)passwords.get(userName);
    if (realPassword == null) {
      return null;
    }
    if (!realPassword.equals(password)) {
      return null;
    }
    return new AuthenticationPrincipal(userName, password, (List)roles.get(userName));
  }
  
  public AuthenticationPrincipal retrieveUser(String userName)
  {
    return new AuthenticationPrincipal(userName, (String)passwords.get(userName), (List)roles.get(userName));
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.realm.FileRealm
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication.realm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.winstone.core.authentication.AuthenticationPrincipal;
import net.winstone.core.authentication.AuthenticationRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JDBCRealm
  implements AuthenticationRealm
{
  protected static Logger logger = LoggerFactory.getLogger(JDBCRealm.class);
  private static final transient String ARGS_DRIVER = "JDBCRealm.driver";
  private static final transient String ARGS_URL = "JDBCRealm.url";
  private static final transient String ARGS_USER = "JDBCRealm.user";
  private static final transient String ARGS_PASSWORD = "JDBCRealm.password";
  public static final transient String ARGS_USER_REL = "JDBCRealm.userRel";
  private static final transient String ARGS_USER_NAME_COL = "JDBCRealm.userNameCol";
  private static final transient String ARGS_USER_CRED_COL = "JDBCRealm.userCredCol";
  private static final transient String ARGS_USER_ROLE_REL = "JDBCRealm.userRoleRel";
  private static final transient String ARGS_ROLE_NAME_COL = "JDBCRealm.roleNameCol";
  public static final transient String DEFAULT_USER_REL = "web_users";
  private static final transient String DEFAULT_USER_NAME_COL = "username";
  private static final transient String DEFAULT_USER_CRED_COL = "credential";
  private static final transient String DEFAULT_USER_ROLE_REL = "web_user_roles";
  private static final transient String DEFAULT_ROLE_NAME_COL = "rolename";
  private Connection connection;
  private final String url;
  private final String user;
  private final String password;
  private final String retriveUserQuery;
  private final String authenticationQueryPostfix;
  private final String userRolesQuery;
  
  public JDBCRealm(Set<String> rolesAllowed, Map<String, String> args)
  {
    String driver = (String)args.get("JDBCRealm.driver");
    url = ((String)args.get("JDBCRealm.url"));
    user = ((String)args.get("JDBCRealm.user"));
    password = ((String)args.get("JDBCRealm.password"));
    
    String userRel = (String)args.get("JDBCRealm.userRel");String userNameCol = (String)args.get("JDBCRealm.userNameCol");String userCredCol = (String)args.get("JDBCRealm.userCredCol");String userRoleRel = (String)args.get("JDBCRealm.userRoleRel");String roleNameCol = (String)args.get("JDBCRealm.roleNameCol");
    if (userRel == null) {
      userRel = "web_users";
    }
    if (userNameCol == null) {
      userNameCol = "username";
    }
    if (userCredCol == null) {
      userCredCol = "credential";
    }
    if (userRoleRel == null) {
      userRoleRel = "web_user_roles";
    }
    if (roleNameCol == null) {
      roleNameCol = "rolename";
    }
    retriveUserQuery = ("SELECT 1\n  FROM \"" + userRel + "\"\n" + "  WHERE \"" + userNameCol + "\" = ?");
    
    authenticationQueryPostfix = ("\n    AND \"" + userCredCol + "\" = ?");
    
    userRolesQuery = ("SELECT \"" + roleNameCol + "\"\n" + "  FROM \"" + userRoleRel + "\"\n" + "  WHERE \"" + userNameCol + "\" = ?");
    if (driver != null) {
      try
      {
        Class.forName(driver);
        
        logger.info("JDBCRealm loaded jdbc driver: " + driver);
      }
      catch (ClassNotFoundException cnfe)
      {
        logger.error("JDBCRealm failed to load jdbc driver: " + driver);
      }
    }
  }
  
  public AuthenticationPrincipal getPrincipal(String userName, String password, boolean usePassword)
  {
    try
    {
      if ((connection == null) || (connection.isClosed())) {
        connection = DriverManager.getConnection(url, user, this.password);
      }
      String query = retriveUserQuery;
      if (usePassword) {
        query = query + authenticationQueryPostfix;
      }
      PreparedStatement ps = connection.prepareStatement(query);
      ps.setString(1, userName);
      if (usePassword) {
        ps.setString(2, password);
      }
      ResultSet resultSet = ps.executeQuery();
      if (resultSet.next())
      {
        query = userRolesQuery;
        ps = connection.prepareStatement(query);
        ps.setString(1, userName);
        resultSet = ps.executeQuery();
        
        List<String> roles = new ArrayList();
        while (resultSet.next()) {
          roles.add(resultSet.getString(1));
        }
        return new AuthenticationPrincipal(userName, password, roles);
      }
    }
    catch (SQLException sqle)
    {
      logger.error("getPrincipal Error:", sqle);
    }
    return null;
  }
  
  public AuthenticationPrincipal authenticateByUsernamePassword(String userName, String password)
  {
    return getPrincipal(userName, password, Boolean.TRUE.booleanValue());
  }
  
  public AuthenticationPrincipal retrieveUser(String userName)
  {
    return getPrincipal(userName, null, Boolean.FALSE.booleanValue());
  }
}

/* Location:
 * Qualified Name:     net.winstone.core.authentication.realm.JDBCRealm
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.core.authentication;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

public final class RetryRequestParams
  implements Serializable
{
  private static final long serialVersionUID = 7900915469307853808L;
  private final String method;
  private final String scheme;
  private final String contextPath;
  private final String servletPath;
  private final String pathInfo;
  private final String queryString;
  private final String protocol;
  private final int contentLength;
  private final String contentType;
  private final String encoding;
  private final Map<String, Enumeration> headers;
  private final List<Locale> locales;
  private final Locale locale;
  private final byte[] bodyContent;
  
  public RetryRequestParams(ServletRequest request)
    throws IOException
  {
    protocol = request.getProtocol();
    locales = new ArrayList(Collections.list(request.getLocales()));
    locale = request.getLocale();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    encoding = request.getCharacterEncoding();
    headers = new HashMap();
    scheme = request.getScheme();
    HttpServletRequest httpRequest;
    Enumeration names;
    if ((request instanceof HttpServletRequest))
    {
      httpRequest = (HttpServletRequest)request;
      method = httpRequest.getMethod();
      contextPath = httpRequest.getContextPath();
      servletPath = httpRequest.getServletPath();
      pathInfo = httpRequest.getPathInfo();
      queryString = httpRequest.getQueryString();
      for (names = httpRequest.getHeaderNames(); names.hasMoreElements();)
      {
        String name = (String)names.nextElement();
        headers.put(name.toLowerCase(), httpRequest.getHeaders(name));
      }
    }
    else
    {
      method = null;
      contextPath = null;
      servletPath = null;
      pathInfo = null;
      queryString = null;
    }
    if (((method == null) || (method.equalsIgnoreCase("POST"))) && (contentLength != -1))
    {
      InputStream inData = request.getInputStream();
      bodyContent = new byte[contentLength];
      int readCount = 0;
      int read = 0;
      while ((read = inData.read(bodyContent, readCount, contentLength - readCount)) >= 0) {
        readCount += read;
      }
      inData.close();
    }
    else
    {
      bodyContent = null;
    }
  }
  
  public byte[] getBodyContent()
  {
    return bodyContent;
  }
  
  public int getContentLength()
  {
    return contentLength;
  }
  
  public String getContentType()
  {
    return contentType;
  }
  
  public String getEncoding()
  {
    return encoding;
  }
  
  public Map<String, Enumeration> getHeaders()
  {
    return headers;
  }
  
  public Locale getLocale()
  {
    return locale;
  }
  
  public List<Locale> getLocales()
  {
    return locales;
  }
  
  public String getMethod()
  {
    return method;
  }
  
  publ
1 2 3 4 5 6 7 8 9 10 11 12 13 14

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2019. Infinite Loop Ltd