/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  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 acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS 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.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

====================================================================== */

package org.bodington.server.realm;

import java.security.*;

import org.bodington.server.BuildingServerException;
import org.bodington.database.PrimaryKey;
import org.bodington.database.IndexKey;
import org.bodington.sqldatabase.SqlPersistentObject;
import org.bodington.util.Base64Encoder;
import java.util.Enumeration;

/**
 * Subclass of PersistentObject represents the user name and pass phrase
 * associated with a User.  This is separated from the User object to allow
 * for the possibility that users may have multiple methods of authentication.
 * There are static "find" methods and property get/set methods.
 * By default all passwords are now encrypted.
 * 
 * @author Jon Maber
 * @author buckett
 * @version 1
 */

public class PassPhrase extends SqlPersistentObject
	{

	/**
	 * The primary key of the object.
	 */
	private PrimaryKey pass_phrase_id;

	/**
	 * The user id of the user that owns this pass phrase.
	 */
	private PrimaryKey user_id;

	/**
	 * The log in user name of the user.
	 */
	private String user_name;

	/**
	 * The passphrase of the user.  (Currently stored unencrypted but
	 * in future likely to be a digest of the passphrase.)
	 */
	private String pass_phrase;
	
	
	private PassPhraseIndexKey[] ikeys;
	

	public static PassPhrase findPassPhrase( PrimaryKey key )
	    throws BuildingServerException
	    {
	    return (PassPhrase)findPersistentObject( key, "org.bodington.server.realm.PassPhrase" );
	    }
	
	public static PassPhrase findPassPhrase( String where )
	    throws BuildingServerException
	    {
	    return (PassPhrase)findPersistentObject( where, "org.bodington.server.realm.PassPhrase" );
	    }
	
	public static PassPhrase findPassPhraseByUserName( String user_name )
	    throws BuildingServerException
	    {
	    PassPhraseIndexKey ikey = new PassPhraseIndexKey();
	    ikey.setUserName( user_name );
	    return (PassPhrase)findPersistentObject( ikey, "org.bodington.server.realm.PassPhrase" );
	    }
	
	public static Enumeration findPassPhrases( String where )
	    throws BuildingServerException
	    {
	    return findPersistentObjects( where, "org.bodington.server.realm.PassPhrase" );
	    }
	
	public static PassPhrase findPassPhrase( User user )
		throws BuildingServerException
	{
	    return findPassPhrase( "user_id = "+ user.getPrimaryKey());
	}
	


	/**
	 * The Constructor does nothing at the moment.
	 */
	
	public PassPhrase()
		{
		ikeys = new PassPhraseIndexKey[1];
		ikeys[0] = new PassPhraseIndexKey();
		}

	/**
	 * This is a required method for implementation of PersistentObject.
	 * 
	 * @return The primary key of this object.
	 */
		
	public PrimaryKey getPrimaryKey()
		{
		return getPassPhraseId();
		}

	/**
	 * This is a required method for implementation of PersistentObject.
	 * 
	 * @param key The new primary key for this object.
	 */
	public void setPrimaryKey( PrimaryKey  key )
		{
		setPassPhraseId( key );
		}
		
	public PrimaryKey getPassPhraseId()
		{
		return pass_phrase_id;
		}
	public void setPassPhraseId( PrimaryKey x )
		{
		pass_phrase_id=x;
    	setUnsaved();
		}
		
	public PrimaryKey getUserId()
		{
		return user_id;
		}
	public void setUserId( PrimaryKey x )
		{
		user_id=x;
    	setUnsaved();
		}
		
	public String getUserName()
		{
		return user_name;
		}
	public void setUserName( String x )
		{
		user_name=x;
    	setUnsaved();
    	ikeys[0].setUserName( x );
		}
		
	public String getPassPhrase()
		{
		return pass_phrase;
		}
	
	/**
	 * PassPhrase setter. Doesn't do any encryption or checking of the value.
	 * For most cases you should probably use {@link #changePassPhrase(String)} 
	 * instead.
	 * @param x The new passphrase.
	 */
	public void setPassPhrase( String x )
		{
		pass_phrase = x;
		setUnsaved();
		}
	
	/**
	 * Set the passphrase to an encrypted string.
	 * @throws IllegalStateException If you try to set the password when the user is null.
	 * @param x The new passphrase.
	 */
	void setPassPhraseEncrypted( String x)
		{	    
	    /*
	    [ERROR] org.bodington.servlet.facilities.UserCreationFacility java.lang.NullPointerException
                       for sqlserver
	    */
	    if (user_id == null)
	        throw new IllegalStateException("Should never set password on object with NULL user.");
	    setPassPhrase(encrypt(user_id.toString() + x));
        //setPassPhrase(encrypt(user_id + x));
		}
	
	/**
	 * Set the password to be unencrypted. 
	 * We truncate the passphrase to 27 characters so it isn't
	 * confused with a encrypted passphrase.
	 * @param x The new passphrase.
	 */
	void setPassPhraseUnencrypted( String x)
		{
	    if (x.length() > 27)
	    	{
	        setPassPhrase(x.substring(0,26));
	    	}
	    else
	    	{
	        setPassPhrase(x);
	    	}
		}
	
	/**
	 * Change a users passphrase.
	 * This currently encrypts the users passphrase.
	 * @param x The new passphrase.
	 */
	public void changePassPhrase(String x)
		{
	    setPassPhraseEncrypted(x);
		}
	
	/**
	 * Check that the users passphrase matches.
	 * It supports encrypted and unencrypted passphrases.
	 * @param x The passphrase to test against.
	 * @return True is we accept this as a match.
	 * @throws BuildingServerException
	 */
	public boolean isPassPhrase( String x )
        throws BuildingServerException
		{
                if ( pass_phrase == null )
                    return false;
              
        if ( isEncryptedPassPhrase() )
        {
    		if ( checkEncrypted(x) )
    			return true;
        }
        else
        {
            if ( checkUnencrypted(x) )
                return true;
        }
		
		User user = getUser();
		if ( user == null ) return false;
		Alias alias = Alias.findAlias( "zone_id = " + user.getZoneId() + " AND alias_name = 'old_nbb_id'" );
		if ( alias == null ) return false;
		AliasEntry entry = AliasEntry.findAliasEntry( "alias_id = "     + alias.getAliasId() + 
													  " AND user_id = " + user.getUserId() );
		if ( entry == null ) return false;
		
		return pass_phrase.equals( encrypt( entry.getUserAlias() + x ) );
		}
		

	/**
	 * Check if an unencrypted passphrase matches.
	 * We only check the first 27 characters.
	 * @param x The passphrase to test against.
	 * @return True if they match.
	 */
    private boolean checkUnencrypted(String x)
    {
        return pass_phrase.equals( (x.length() > 27)?x.substring(0,26):x );
    }
    
    /**
     * Check if an encrypted passphrase matches.
     * @param x The passphrase to test against.
     * @return True if they match.
     */
    private boolean checkEncrypted(String x)
    {
        return pass_phrase.equals(encrypt(user_id + x));
    }
    
    /**
     * Check if this Passphrase is encrypted.
     * @return True if it is encrypted.
     */
    private boolean isEncryptedPassPhrase()
    {
        return pass_phrase.length() == 28;
    }

    public void setUser( User u )
    	{
    	setUserId( u.getUserId() );
    	}

    public User getUser()
        throws BuildingServerException
    	{
		return User.findUser( user_id );
	    }
	    
	    
	public int lifetime()
		{
		return 60;
		}
	
	
	/**
	 * Encrypts an password using a digest (SHA).
	 * There have been comment that this may be buggy?
	 * @param in The string to encrypt.
	 * @return The encrypted version.
	 */
	public static String encrypt( String in )
		{
		MessageDigest md;
		byte buf[];
		byte out[];
		String sout;
		
		buf = in.getBytes();
		try
			{
			md = MessageDigest.getInstance("SHA");
			}
		catch ( NoSuchAlgorithmException ex )
			{
			return null;
			}
		if ( md==null )
			return null;
			
	    out=md.digest( buf );
	    if ( out==null )
	    	return null;
	    
	    Base64Encoder enc=new Base64Encoder();
	    sout=enc.encode( out );
	    return sout;
	    }

	
	
	public IndexKey[] getIndexKeys()
	    {
	    
	    if ( ikeys[0].getUserName() == null )
	        return null;

	    return ikeys;
	    }
	    
	public boolean matchesKey( IndexKey testikey )
	    {
	    return testikey.equals( ikeys[0] );
	    }
	}
 
