package org.dbxml.core.security;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: PasswordCredentials.java,v 1.17 2001/08/03 06:34:05 tom Exp $
 */

import org.dbxml.core.*;
import org.dbxml.core.Collection;
import org.dbxml.core.*;
import org.dbxml.core.data.*;

import org.dbxml.server.*;
import org.dbxml.server.util.*;

import java.util.*;

import org.w3c.dom.*;
/**
 * PasswordCredentials provides a Credentials implementation that uses usernames
 * and passwords stored in the Systemdatabase.
 */
public class PasswordCredentials implements Credentials {
   private static final String COLLECTION = "system/SysGroups";
   protected boolean isValid = false;
   protected String username = null;
   protected String password = null;
   protected ArrayList groups = null;
   protected Database db = null;

   /**
    * Creates a new PasswordCredentials using the username and password provided.
    * The username will be looked up in system/SysUsers and the password will be
    * compared to that stored in the record.
    *
    * @param username The username to authenticate
    * @param password The password used to authenticate the user.
    * @param db The Database instance in effect
    * @exception InvalidPasswordException Thrown when the password provided does
    *            not match for the username.
    * @exception UnknownUserException Thrown when the username can not be found.
    */
   public PasswordCredentials(String username, String password,
         Database db)
         throws InvalidPasswordException, UnknownUserException {
      this.username = username;
      this.password = password;
      this.db = db;
      groups = new ArrayList();

      try {
         Collection users = db.getCollection("system/SysUsers");

         Document user = null;
         try {
org.dbxml.Debug.println("USER: " + username);
            user = users.getDocument(username);
            if (user == null) {
               throw new UnknownUserException();
            }
         }
         catch (DBException e) {
            org.dbxml.Debug.printStackTrace(e);
         }

         // Authenticate the user
         String hash = new MD5().md(password).toString();
         if (!user.getDocumentElement().getAttribute("password").equals(hash)) {
            throw new InvalidPasswordException();
         }

         // Retrieve a list of all groups that this user is a member of
         Collection groupsCol = db.getCollection(COLLECTION);
         NodeSet results = groupsCol.queryCollection("XPath", "/group/members/member/@name='" +
            username + "'", null);
         if (results != null) {
            while (results.hasMoreNodes()) {
               Node node = results.getNextNode();
               String groupName = ((Element)node).getAttribute("name");
               groups.add(groupName);
            }
         }
      }
      catch (dbXMLException e) {
         org.dbxml.Debug.printStackTrace(e);
         throw new UnknownUserException();
      }

      isValid = true;
   }

   /**
    * Verifies that the credentials are valid.
    *
    * @exception InvalidCredentialsException Thrown if the credentials
    *            are not valid.
    */
   public void verify() throws InvalidCredentialsException {
      if ((username == null) || (password == null) || (!isValid)) {
         throw new InvalidCredentialsException();
      }
   }

   /**
    * Determines if these credentials have an association with the specified
    * group.
    *
    * @param group The group to check membership of
    * @return true if the group exists false otherwise.
    * @exception AccessDeniedException Thrown when access to the resource is
    *            denied.
    * @exception InvalidCredentialsException Thrown if the provided credentials
    *            are not valid.
    */
   public boolean checkGroup(String group) throws AccessDeniedException,
         InvalidCredentialsException {
      return groups.contains(group);
   }

   /**
    * Returns the list of groups to which these credentials belong.
    *
    * @return the list of groups
    */
   public ArrayList getGroups() {
      return groups;
   }

   /**
    * Returns the username associated with these credentials
    *
    * @return the username
    */
   public String getUsername() {
      return username;
   }

   /**
    * Returns the password associated with these credentials
    *
    * @return the password
    */
   public String getPassword() {
      return password;
   }
}
