head	1.12;
access;
symbols
	dlr:1.1.1
	HELM_PEER_PORT_BRANCH:1.1.1.1;
locks; strict;
comment	@# @;


1.12
date	2001.03.07.01.14.51;	author lucas;	state dead;
branches;
next	1.11;

1.11
date	2001.03.02.01.30.54;	author dlr;	state Exp;
branches;
next	1.10;

1.10
date	2001.03.02.01.24.00;	author dlr;	state Exp;
branches;
next	1.9;

1.9
date	2001.02.26.20.21.18;	author dlr;	state Exp;
branches;
next	1.8;

1.8
date	2001.02.24.04.04.51;	author dlr;	state Exp;
branches;
next	1.7;

1.7
date	2001.02.24.01.17.24;	author leonardr;	state Exp;
branches;
next	1.6;

1.6
date	2001.02.24.00.43.13;	author leonardr;	state Exp;
branches;
next	1.5;

1.5
date	2001.02.23.19.09.51;	author leonardr;	state Exp;
branches;
next	1.4;

1.4
date	2001.02.22.21.37.21;	author leonardr;	state Exp;
branches;
next	1.3;

1.3
date	2001.02.22.19.45.34;	author leonardr;	state Exp;
branches;
next	1.2;

1.2
date	2001.02.21.03.02.28;	author edk;	state Exp;
branches;
next	1.1;

1.1
date	2001.01.28.01.18.25;	author dlr;	state dead;
branches
	1.1.1.1
	1.1.2.1;
next	;

1.1.1.1
date	2001.02.21.00.33.09;	author dlr;	state Exp;
branches;
next	;

1.1.2.1
date	2001.01.28.01.18.25;	author dlr;	state Exp;
branches;
next	1.1.2.2;

1.1.2.2
date	2001.01.29.04.44.28;	author dlr;	state Exp;
branches;
next	1.1.2.3;

1.1.2.3
date	2001.01.29.16.43.28;	author dlr;	state Exp;
branches;
next	1.1.2.4;

1.1.2.4
date	2001.01.29.18.59.59;	author dlr;	state Exp;
branches;
next	1.1.2.5;

1.1.2.5
date	2001.01.30.00.24.05;	author dlr;	state Exp;
branches;
next	1.1.2.6;

1.1.2.6
date	2001.01.30.00.53.37;	author dlr;	state Exp;
branches;
next	1.1.2.7;

1.1.2.7
date	2001.01.30.01.02.42;	author dlr;	state Exp;
branches;
next	1.1.2.8;

1.1.2.8
date	2001.01.30.01.13.28;	author dlr;	state Exp;
branches;
next	1.1.2.9;

1.1.2.9
date	2001.01.30.02.21.17;	author dlr;	state Exp;
branches;
next	1.1.2.10;

1.1.2.10
date	2001.01.30.02.36.20;	author dlr;	state Exp;
branches;
next	1.1.2.11;

1.1.2.11
date	2001.01.30.02.37.07;	author dlr;	state Exp;
branches;
next	1.1.2.12;

1.1.2.12
date	2001.01.30.02.49.31;	author dlr;	state Exp;
branches;
next	1.1.2.13;

1.1.2.13
date	2001.01.30.06.28.11;	author dlr;	state Exp;
branches;
next	1.1.2.14;

1.1.2.14
date	2001.01.30.07.06.49;	author dlr;	state Exp;
branches;
next	1.1.2.15;

1.1.2.15
date	2001.01.30.19.48.04;	author leonardr;	state Exp;
branches;
next	1.1.2.16;

1.1.2.16
date	2001.01.31.01.03.42;	author dlr;	state Exp;
branches;
next	1.1.2.17;

1.1.2.17
date	2001.01.31.02.07.34;	author dlr;	state Exp;
branches;
next	1.1.2.18;

1.1.2.18
date	2001.01.31.02.23.36;	author dlr;	state Exp;
branches;
next	1.1.2.19;

1.1.2.19
date	2001.02.06.18.55.06;	author leonardr;	state Exp;
branches;
next	1.1.2.20;

1.1.2.20
date	2001.02.07.16.18.44;	author leonardr;	state Exp;
branches;
next	1.1.2.21;

1.1.2.21
date	2001.02.07.19.50.12;	author leonardr;	state Exp;
branches;
next	1.1.2.22;

1.1.2.22
date	2001.02.08.00.29.33;	author dlr;	state Exp;
branches;
next	1.1.2.23;

1.1.2.23
date	2001.02.08.00.35.36;	author dlr;	state Exp;
branches;
next	1.1.2.24;

1.1.2.24
date	2001.02.08.00.55.42;	author dlr;	state Exp;
branches;
next	1.1.2.25;

1.1.2.25
date	2001.02.08.01.04.34;	author dlr;	state Exp;
branches;
next	1.1.2.26;

1.1.2.26
date	2001.02.08.01.06.41;	author dlr;	state Exp;
branches;
next	1.1.2.27;

1.1.2.27
date	2001.02.08.02.29.10;	author dlr;	state Exp;
branches;
next	1.1.2.28;

1.1.2.28
date	2001.02.09.03.02.48;	author dlr;	state Exp;
branches;
next	1.1.2.29;

1.1.2.29
date	2001.02.09.03.08.14;	author dlr;	state Exp;
branches;
next	1.1.2.30;

1.1.2.30
date	2001.02.12.15.07.17;	author leonardr;	state Exp;
branches;
next	1.1.2.31;

1.1.2.31
date	2001.02.13.03.35.34;	author leonardr;	state Exp;
branches;
next	1.1.2.32;

1.1.2.32
date	2001.02.14.00.20.28;	author leonardr;	state Exp;
branches;
next	1.1.2.33;

1.1.2.33
date	2001.02.15.14.40.42;	author leonardr;	state Exp;
branches;
next	1.1.2.34;

1.1.2.34
date	2001.02.15.20.50.39;	author leonardr;	state Exp;
branches;
next	1.1.2.35;

1.1.2.35
date	2001.02.16.03.01.33;	author dlr;	state Exp;
branches;
next	1.1.2.36;

1.1.2.36
date	2001.02.16.07.32.42;	author dlr;	state Exp;
branches;
next	1.1.2.37;

1.1.2.37
date	2001.02.16.07.55.28;	author dlr;	state Exp;
branches;
next	1.1.2.38;

1.1.2.38
date	2001.02.17.00.06.00;	author leonardr;	state Exp;
branches;
next	;


desc
@@


1.12
log
@Deprecated by Torque changes. -dlr
@
text
@/* ================================================================
 * Copyright (c) 2000-2001 CollabNet.  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 acknowlegement: "This product includes
 * software developed by CollabNet (http://www.collab.net/)."
 * Alternately, this acknowlegement may appear in the software itself, if
 * and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The hosted project names must not be used to endorse or promote
 * products derived from this software without prior written
 * permission. For written permission, please contact info@@collab.net.
 * 
 * 5. Products derived from this software may not use the "Tigris" name
 * nor may "Tigris" appear in their names without prior written
 * permission of CollabNet.
 * 
 * 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 COLLABNET 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 consists of voluntary contributions made by many
 * individuals on behalf of CollabNet.
 */

package org.tigris.helm.om.peer;

import java.util.*;

import java.sql.*;

import org.apache.turbine.om.*;
import org.apache.turbine.util.db.Criteria;
import org.apache.turbine.util.db.pool.DBConnection;
import org.apache.turbine.util.TurbineException;
import org.apache.turbine.services.db.TurbineDB;

import org.tigris.helm.om.map.UserMapBuilder;

import org.tigris.helm.om.base.*;
import org.tigris.helm.om.*;
import org.tigris.helm.*;
import org.tigris.helm.tool.PeerTool;

/**
 * Extension of generated Peer BaseUserPeer.
 *
 * @@author <a href="mailto:leonardr@@collab.net">Leonard Richardson</a>
 * @@author <a href="mailto:dlr@@collab.net">Daniel Rall</a>
 */
public class UserPeer extends BaseUserPeer
{

    //
    // Special data structures and methods for paginating lists of users.
    //     

    public static Map filterableFields = new HashMap();
    
    /**
     * How objects of this type should be ordered in lists.
     */
    public static final String DEFAULT_ORDER_BY = LOGIN_NAME;

    //
    // Special users.
    // 
    public static final String NOBODY_USER_LOGIN_NAME = "**Nobody";
    public static final String DOMAIN_USERS_LOGIN_NAME = "*All users in domain";

    /**
     * The login name of the super user.
     */
    protected static final String ROOT_LOGIN_NAME = "root";

    /**
     * The login name of the anonymous user (previously the guest user).
     */
    protected static final String ANONYMOUS_LOGIN_NAME = "guest";

    /**
     * Static initializer; initializes the filterableFields data structure.
     */
    static
    { 
        filterableFields.put("Real Name", REAL_NAME);
        filterableFields.put("Login Name", LOGIN_NAME);
        filterableFields.put("Email", EMAIL);
        filterableFields.put("Organization", ORGANIZATION);
    };    

    /**
     * Asserts that the provided login/password token is valid in the given
     * domain.
     *
     * @@param domain    The domain to check the login name in.
     * @@param loginName The login name to check the password of.
     * @@param password  The password to check.
     *
     * @@exception TurbineException Invalid login.
     * @@exception Exception        Error condition, probably database related.
     */
    public static User assertValidLogin(Domain domain, String loginName,
                                        String password)
        throws TurbineException, Exception
    {
        String failString = "Invalid login";
        User user = null;
        try 
        {
            user = getInstanceByIdentifier(domain, loginName);
        } catch (DoesNotExist e) {
            throw new TurbineException(failString);
        }

        if (!user.validPassword(password))
        {
            throw new TurbineException(failString);
        }
        return user;
    }

    /**
     * Checks whether the specified user exists.
     */
    public static boolean exists(Domain domain, String loginName)
        throws Exception
    {
        try {
            getInstanceByLoginName(domain, loginName);
            return true;
        }
        catch (DoesNotExist e) {
            return false;
        }
    }

    /**
     * Gets the database key associated with the special user that represents 
     * the "all users in domain" user group for the specified domain.
     *
     * @@param domain The domain to retrieve the special user for.
     */
    public static UserGroup getDomainUser(Domain domain)
        throws Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.DOMAIN_ID, domain.getID())
            .add(UserPeer.TYPE, User.DOMAIN_TYPE);
        UserGroup g = null;
        try {
            g = ((User)UserPeer.doSelect(c).get(0)).asGroup();
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special domain user for " +
                            domain.getName());
        }
        return g;
    }

    /**
     * Gets the database key associated with the special user that
     * represents the group of all users in the host domain.
     */
    public static UserGroup getHostUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.TYPE, User.HOST_TYPE);
        UserGroup g = null;
        try {
            g = ((User)UserPeer.doSelect(c).get(0)).asGroup();
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special host user!");
        }
        return g;
    }
    
    //
    // Ways of retrieving User objects.
    //

    /**
     * Returns the user with the specified ID.
     *
     * @@param userID The primary key of the user to retrieve.
     * @@return       The requested user.
     */
    public static User getInstance(String userID)
        throws Exception
    {
        return UserPeer.retrieveByPK(new NumberKey(userID));
    }

    /**
     * Tries to get a user by login name, email address, and real name.
     * If all of these fail, throws an exception.
     *
     * @@param domain     The domain to look in.
     * @@param identifier The primary key of the user to retrieve.
     * @@return           The first matching user.
     *
     * @@exception DoesNotExist No matches for the provided identifier.
     */
    public static User getInstanceByIdentifier(Domain domain,
                                               String identifier)
        throws DoesNotExist, Exception
    {
        User u = null;
        try
        {
            u =  getInstanceByLoginName(domain, identifier);
        }
        catch (DoesNotExist loginNameEx)
        {
            try 
            {
                u = getInstanceByEmail(domain, identifier);
            }
            catch (DoesNotExist emailEx) 
            {
                try 
                {
                    u = getInstanceByRealName(domain, identifier);
                }
                catch (DoesNotExist realNameEx)
                {
                    throw new DoesNotExist("User identified by " + 
                                           identifier, "domain named " +
                                           domain.getName());
                }
            }
        }
        return u;
    }

    /**
     * Returns the user for a specified domain and login name.
     */
    public static User getInstanceByLoginName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.LOGIN_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with login name of " + name,
                                         domain);
    }

    /**
     * Returns the user for a specified domain and real name.
     */
    public static User getInstanceByRealName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.REAL_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User named " + name, domain);
    }

    /**
     * Returns the user for a specified domain and email address.
     */
    public static User getInstanceByEmail(Domain domain, String email)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.EMAIL, email);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with email " + email, domain);
    }
    
    public static Criteria checkThisAndHostDomain(Criteria c, Domain domain)
        throws Exception
    {
        String[] domainIDs = { domain.getID(),
                               DomainPeer.getHostDomain().getID() };
        c.addIn(UserPeer.DOMAIN_ID, domainIDs);
        return c;
    }

    //
    // Ways of retrieving UserGroup objects. These suck.
    //
    public static UserGroup getGroupInstance(String userID)
        throws Exception
    {
        int uid = Integer.parseInt(userID);
        Criteria criteria = new Criteria();
        if (uid > 0) {
            criteria.add(UserPeer.USER_ID, uid);
        }
        return getFirstUserGroup(criteria);
    }

    public static UserGroup getGroupInstanceByName(Domain domain, String name)
        throws Exception
    {
        int domainID = Integer.parseInt(domain.getDomainId().toString());
        Criteria criteria = new Criteria();
        criteria.add(UserPeer.LOGIN_NAME, name);
        if (domainID > 0)
            criteria.add( UserPeer.DOMAIN_ID, domainID );
        return getFirstUserGroup(criteria);
    }

    private static final UserGroup getFirstUserGroup(Criteria criteria)
        throws DoesNotExist, Exception
    {
        return (UserGroup)PeerTool.getFirstBO(doSelect(criteria),
                                              "User group");
    }

    /**
     * Gets the special user for a given domain.
     */
    public static User getNobodyUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(TYPE, User.NOBODY_TYPE);
        User u = null;
        try {
            u = (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Nobody user");
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special 'nobody' user!");
        }
        return u;
    }

    /**
     * Gets the special super user.
     * <p>
     * TODO: Remove db hit via caching.
     */
    public static User getSuperUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(LOGIN_NAME, UserPeer.ROOT_LOGIN_NAME)
            .add(DOMAIN_ID, DomainPeer.getHostDomain().getID());
        try {
            return (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Root user");
        }
        catch (DoesNotExist e) {
            throw new Error("Super user cannot be found!");
        }
    }

    /**
     * Gets the special guest user.
     * <p>
     * TODO: Remove db hit via caching.
     */
    public static User getAnonymousUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(LOGIN_NAME, UserPeer.ANONYMOUS_LOGIN_NAME)
            .add(DOMAIN_ID, DomainPeer.getHostDomain().getID());
        try {
            return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                             "Guest user");
        }
        catch (DoesNotExist e) {
            throw new Error("Guest user cannot be found!");
        }
    }


    ////////////////////////////////////////////////////////////////
    // Mutator methods.
    ////////////////////////////////////////////////////////////////

    /**
     * Uses the database to encrypt the provided clear text password.
     *
     * @@param passwd The clear text password to encrypt.
     * @@return       The encrypted password.
     *
     * @@exception Exception Database error occurred.
     */
    public static String encryptPassword(String passwd)
        throws Exception
    {
        String encrypted = null;
        DBConnection dbc = null;
        try 
        {
            dbc = TurbineDB.getConnection();
            PreparedStatement stmt =
                dbc.getConnection().prepareStatement("select password(?)");
            stmt.setString(1, passwd);
            try 
            {
                ResultSet rset = stmt.executeQuery();
                if (rset.next()) 
                {
                    encrypted = rset.getString(1);
                }
            }
            finally 
            {
                if (stmt != null) stmt.close();
            }
        }
        finally 
        {
            TurbineDB.releaseConnection(dbc);
        }
        return encrypted;
    }
}
@


1.11
log
@oops
@
text
@@


1.10
log
@Patch by Leonard to actually get the named user group from
getGroupInstanceByName().
@
text
@d327 1
a327 1
        criteria.add(UserPeer.NAME, name);
@


1.9
log
@Changes to keep in step with the latest Torque-generated code.
@
text
@d327 2
a328 1
        if( domainID > 0 )
@


1.8
log
@Sync'd with latest Turbine changes.  Mostly this consists of the use of the new SimpleKey class to handle primary database keys.
@
text
@d214 1
a214 1
        return UserPeer.retrieveByPK(new SimpleKey(userID));
@


1.7
log
@Failure message on invalid username should be the same as failure message on invalid password.
@
text
@d53 1
d214 1
a214 1
        return UserPeer.retrieveByPK(Integer.parseInt(userID));
d325 1
a325 1
        int domainID = domain.getDomainId();        
@


1.6
log
@There's no real reason to try getting a user by ID here, and it causes problems.
@
text
@d127 9
a135 1
        User user = (getInstanceByIdentifier(domain, loginName));
d138 1
a138 1
            throw new TurbineException("Invalid login");
@


1.5
log
@Get users using all avaliable methods.
@
text
@d209 2
a210 2
     * Tries to get a user by login name, real name, email address, and
     * ID.  If all of these fail, throws an exception.
d241 3
a243 10

                    try {
                        u = getInstance(identifier);
                    } 
                    catch (DoesNotExist idEx)
                    {
                        throw new DoesNotExist("User identified by " + 
                                               identifier, "domain named " +
                                               domain.getName());
                    }
@


1.4
log
@Fixed password setting.
@
text
@d123 1
a123 1
    public static void assertValidLogin(Domain domain, String loginName,
d127 4
a130 21
        boolean isValid = false;
        DBConnection dbc = null;
        try {
            dbc = TurbineDB.getConnection();
            PreparedStatement stmt = dbc.getConnection().prepareStatement
                ("select " + USER_ID + " from " + TABLE_NAME + " where " +
                 LOGIN_NAME + "=? and " + PASSWORD + "=password(?)");
            stmt.setString(1, loginName);
            stmt.setString(2, password);
            try {
                ResultSet rset = stmt.executeQuery();
                if (!rset.next()) {
                    throw new TurbineException("Invalid login");
                }
            }
            finally {
                if (stmt != null) stmt.close();
            }
        }
        finally {
            TurbineDB.releaseConnection(dbc);
d132 1
@


1.3
log
@Removed unused commented out method and made encryptPassword public.
@
text
@d423 1
a423 1
    public String encryptPassword(String passwd)
d428 2
a429 1
        try {
d434 2
a435 1
            try {
d437 2
a438 1
                if (rset.next()) {
d442 2
a443 1
            finally {
d447 2
a448 1
        finally {
@


1.2
log
@adding files from the branch to the head
@
text
@a414 50
//     /**
//      * Updates an existing user or adds a new user to the database 
//      * (depending on whether given a <code>userID</code> or not).
//      *
//      * Note: This method only changes the database. It does not run
//      * scripts.
//      *
//      * @@param userID        ID of the user to edit (leave null to add new)
//      * @@param domain        Domain in which the user resides.
//      * @@param loginName     Login name of the user.
//      * @@param email         Email Address of the user.
//      * @@param realName      Real name of the user.
//      * @@param organization  Organization with which the user is associated.
//      * @@param password      Unencrypted password for the user.
//      * @@param type          Type of the user.
//      *
//      * @@exception DBException
//      */
//     private void save(Domain domain, String loginName, String email, 
//                       String realName, String organization, String passwd, 
//                       String type)
//         throws DoesNotExist, Exception
//     {
//             String oldPassword = null;
//             String encryptedPassword = null;

//             if (userID != null)
//             {
//                 user = getUser(userID);
//                 oldPassword = user.getValue(PASSWORD).asString();
//             } else {
//                 users = new TableDataSet (connection, TABLE_NAME, keydef);
//                 user = users.addRecord();                
//             }
            
//             if (password != null)
//             {
//                 encryptedPassword = encryptPassword(connection, password);
//             }

//             // Do update.
//             if (domainID != null) user.setValue(DOMAIN_ID, domainID);
//             if (loginName != null) user.setValue(LOGIN_ID, loginName);
//             if (email != null) user.setValue(EMAIL, email);
//             if (realName != null) user.setValue(NAME, realName);
//             if (organization != null) user.setValue(ORGANIZATION, organization);
//             if (encryptedPassword != null) user.setValue(PASSWORD, encryptedPassword);
//             user.save();
//     }

d423 1
a423 1
    protected String encryptPassword(String passwd)
@


1.1
log
@file UserPeer.java was initially added on branch HELM_PEER_PORT_BRANCH.
@
text
@d1 498
@


1.1.1.1
log
@Replacing the HEAD with the HELM_PEER_PORT_BRANCH.
@
text
@a0 498
/* ================================================================
 * Copyright (c) 2000-2001 CollabNet.  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 acknowlegement: "This product includes
 * software developed by CollabNet (http://www.collab.net/)."
 * Alternately, this acknowlegement may appear in the software itself, if
 * and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The hosted project names must not be used to endorse or promote
 * products derived from this software without prior written
 * permission. For written permission, please contact info@@collab.net.
 * 
 * 5. Products derived from this software may not use the "Tigris" name
 * nor may "Tigris" appear in their names without prior written
 * permission of CollabNet.
 * 
 * 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 COLLABNET 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 consists of voluntary contributions made by many
 * individuals on behalf of CollabNet.
 */

package org.tigris.helm.om.peer;

import java.util.*;

import java.sql.*;

import org.apache.turbine.util.db.Criteria;
import org.apache.turbine.util.db.pool.DBConnection;
import org.apache.turbine.util.TurbineException;
import org.apache.turbine.services.db.TurbineDB;

import org.tigris.helm.om.map.UserMapBuilder;

import org.tigris.helm.om.base.*;
import org.tigris.helm.om.*;
import org.tigris.helm.*;
import org.tigris.helm.tool.PeerTool;

/**
 * Extension of generated Peer BaseUserPeer.
 *
 * @@author <a href="mailto:leonardr@@collab.net">Leonard Richardson</a>
 * @@author <a href="mailto:dlr@@collab.net">Daniel Rall</a>
 */
public class UserPeer extends BaseUserPeer
{

    //
    // Special data structures and methods for paginating lists of users.
    //     

    public static Map filterableFields = new HashMap();
    
    /**
     * How objects of this type should be ordered in lists.
     */
    public static final String DEFAULT_ORDER_BY = LOGIN_NAME;

    //
    // Special users.
    // 
    public static final String NOBODY_USER_LOGIN_NAME = "**Nobody";
    public static final String DOMAIN_USERS_LOGIN_NAME = "*All users in domain";

    /**
     * The login name of the super user.
     */
    protected static final String ROOT_LOGIN_NAME = "root";

    /**
     * The login name of the anonymous user (previously the guest user).
     */
    protected static final String ANONYMOUS_LOGIN_NAME = "guest";

    /**
     * Static initializer; initializes the filterableFields data structure.
     */
    static
    { 
        filterableFields.put("Real Name", REAL_NAME);
        filterableFields.put("Login Name", LOGIN_NAME);
        filterableFields.put("Email", EMAIL);
        filterableFields.put("Organization", ORGANIZATION);
    };    

    /**
     * Asserts that the provided login/password token is valid in the given
     * domain.
     *
     * @@param domain    The domain to check the login name in.
     * @@param loginName The login name to check the password of.
     * @@param password  The password to check.
     *
     * @@exception TurbineException Invalid login.
     * @@exception Exception        Error condition, probably database related.
     */
    public static void assertValidLogin(Domain domain, String loginName,
                                        String password)
        throws TurbineException, Exception
    {
        boolean isValid = false;
        DBConnection dbc = null;
        try {
            dbc = TurbineDB.getConnection();
            PreparedStatement stmt = dbc.getConnection().prepareStatement
                ("select " + USER_ID + " from " + TABLE_NAME + " where " +
                 LOGIN_NAME + "=? and " + PASSWORD + "=password(?)");
            stmt.setString(1, loginName);
            stmt.setString(2, password);
            try {
                ResultSet rset = stmt.executeQuery();
                if (!rset.next()) {
                    throw new TurbineException("Invalid login");
                }
            }
            finally {
                if (stmt != null) stmt.close();
            }
        }
        finally {
            TurbineDB.releaseConnection(dbc);
        }
    }

    /**
     * Checks whether the specified user exists.
     */
    public static boolean exists(Domain domain, String loginName)
        throws Exception
    {
        try {
            getInstanceByLoginName(domain, loginName);
            return true;
        }
        catch (DoesNotExist e) {
            return false;
        }
    }

    /**
     * Gets the database key associated with the special user that represents 
     * the "all users in domain" user group for the specified domain.
     *
     * @@param domain The domain to retrieve the special user for.
     */
    public static UserGroup getDomainUser(Domain domain)
        throws Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.DOMAIN_ID, domain.getID())
            .add(UserPeer.TYPE, User.DOMAIN_TYPE);
        UserGroup g = null;
        try {
            g = ((User)UserPeer.doSelect(c).get(0)).asGroup();
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special domain user for " +
                            domain.getName());
        }
        return g;
    }

    /**
     * Gets the database key associated with the special user that
     * represents the group of all users in the host domain.
     */
    public static UserGroup getHostUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.TYPE, User.HOST_TYPE);
        UserGroup g = null;
        try {
            g = ((User)UserPeer.doSelect(c).get(0)).asGroup();
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special host user!");
        }
        return g;
    }
    
    //
    // Ways of retrieving User objects.
    //

    /**
     * Returns the user with the specified ID.
     *
     * @@param userID The primary key of the user to retrieve.
     * @@return       The requested user.
     */
    public static User getInstance(String userID)
        throws Exception
    {
        return UserPeer.retrieveByPK(Integer.parseInt(userID));
    }

    /**
     * Tries to get a user by login name, real name, email address, and
     * ID.  If all of these fail, throws an exception.
     *
     * @@param domain     The domain to look in.
     * @@param identifier The primary key of the user to retrieve.
     * @@return           The first matching user.
     *
     * @@exception DoesNotExist No matches for the provided identifier.
     */
    public static User getInstanceByIdentifier(Domain domain,
                                               String identifier)
        throws DoesNotExist, Exception
    {
        User u = null;
        try
        {
            u =  getInstanceByLoginName(domain, identifier);
        }
        catch (DoesNotExist loginNameEx)
        {
            try 
            {
                u = getInstanceByEmail(domain, identifier);
            }
            catch (DoesNotExist emailEx) 
            {
                try 
                {
                    u = getInstanceByRealName(domain, identifier);
                }
                catch (DoesNotExist realNameEx)
                {

                    try {
                        u = getInstance(identifier);
                    } 
                    catch (DoesNotExist idEx)
                    {
                        throw new DoesNotExist("User identified by " + 
                                               identifier, "domain named " +
                                               domain.getName());
                    }
                }
            }
        }
        return u;
    }

    /**
     * Returns the user for a specified domain and login name.
     */
    public static User getInstanceByLoginName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.LOGIN_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with login name of " + name,
                                         domain);
    }

    /**
     * Returns the user for a specified domain and real name.
     */
    public static User getInstanceByRealName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.REAL_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User named " + name, domain);
    }

    /**
     * Returns the user for a specified domain and email address.
     */
    public static User getInstanceByEmail(Domain domain, String email)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.EMAIL, email);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with email " + email, domain);
    }
    
    public static Criteria checkThisAndHostDomain(Criteria c, Domain domain)
        throws Exception
    {
        String[] domainIDs = { domain.getID(),
                               DomainPeer.getHostDomain().getID() };
        c.addIn(UserPeer.DOMAIN_ID, domainIDs);
        return c;
    }

    //
    // Ways of retrieving UserGroup objects. These suck.
    //
    public static UserGroup getGroupInstance(String userID)
        throws Exception
    {
        int uid = Integer.parseInt(userID);
        Criteria criteria = new Criteria();
        if (uid > 0) {
            criteria.add(UserPeer.USER_ID, uid);
        }
        return getFirstUserGroup(criteria);
    }

    public static UserGroup getGroupInstanceByName(Domain domain, String name)
        throws Exception
    {
        int domainID = domain.getDomainId();        
        Criteria criteria = new Criteria();
        if( domainID > 0 )
            criteria.add( UserPeer.DOMAIN_ID, domainID );
        return getFirstUserGroup(criteria);
    }

    private static final UserGroup getFirstUserGroup(Criteria criteria)
        throws DoesNotExist, Exception
    {
        return (UserGroup)PeerTool.getFirstBO(doSelect(criteria),
                                              "User group");
    }

    /**
     * Gets the special user for a given domain.
     */
    public static User getNobodyUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(TYPE, User.NOBODY_TYPE);
        User u = null;
        try {
            u = (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Nobody user");
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special 'nobody' user!");
        }
        return u;
    }

    /**
     * Gets the special super user.
     * <p>
     * TODO: Remove db hit via caching.
     */
    public static User getSuperUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(LOGIN_NAME, UserPeer.ROOT_LOGIN_NAME)
            .add(DOMAIN_ID, DomainPeer.getHostDomain().getID());
        try {
            return (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Root user");
        }
        catch (DoesNotExist e) {
            throw new Error("Super user cannot be found!");
        }
    }

    /**
     * Gets the special guest user.
     * <p>
     * TODO: Remove db hit via caching.
     */
    public static User getAnonymousUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(LOGIN_NAME, UserPeer.ANONYMOUS_LOGIN_NAME)
            .add(DOMAIN_ID, DomainPeer.getHostDomain().getID());
        try {
            return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                             "Guest user");
        }
        catch (DoesNotExist e) {
            throw new Error("Guest user cannot be found!");
        }
    }


    ////////////////////////////////////////////////////////////////
    // Mutator methods.
    ////////////////////////////////////////////////////////////////

//     /**
//      * Updates an existing user or adds a new user to the database 
//      * (depending on whether given a <code>userID</code> or not).
//      *
//      * Note: This method only changes the database. It does not run
//      * scripts.
//      *
//      * @@param userID        ID of the user to edit (leave null to add new)
//      * @@param domain        Domain in which the user resides.
//      * @@param loginName     Login name of the user.
//      * @@param email         Email Address of the user.
//      * @@param realName      Real name of the user.
//      * @@param organization  Organization with which the user is associated.
//      * @@param password      Unencrypted password for the user.
//      * @@param type          Type of the user.
//      *
//      * @@exception DBException
//      */
//     private void save(Domain domain, String loginName, String email, 
//                       String realName, String organization, String passwd, 
//                       String type)
//         throws DoesNotExist, Exception
//     {
//             String oldPassword = null;
//             String encryptedPassword = null;

//             if (userID != null)
//             {
//                 user = getUser(userID);
//                 oldPassword = user.getValue(PASSWORD).asString();
//             } else {
//                 users = new TableDataSet (connection, TABLE_NAME, keydef);
//                 user = users.addRecord();                
//             }
            
//             if (password != null)
//             {
//                 encryptedPassword = encryptPassword(connection, password);
//             }

//             // Do update.
//             if (domainID != null) user.setValue(DOMAIN_ID, domainID);
//             if (loginName != null) user.setValue(LOGIN_ID, loginName);
//             if (email != null) user.setValue(EMAIL, email);
//             if (realName != null) user.setValue(NAME, realName);
//             if (organization != null) user.setValue(ORGANIZATION, organization);
//             if (encryptedPassword != null) user.setValue(PASSWORD, encryptedPassword);
//             user.save();
//     }

    /**
     * Uses the database to encrypt the provided clear text password.
     *
     * @@param passwd The clear text password to encrypt.
     * @@return       The encrypted password.
     *
     * @@exception Exception Database error occurred.
     */
    protected String encryptPassword(String passwd)
        throws Exception
    {
        String encrypted = null;
        DBConnection dbc = null;
        try {
            dbc = TurbineDB.getConnection();
            PreparedStatement stmt =
                dbc.getConnection().prepareStatement("select password(?)");
            stmt.setString(1, passwd);
            try {
                ResultSet rset = stmt.executeQuery();
                if (rset.next()) {
                    encrypted = rset.getString(1);
                }
            }
            finally {
                if (stmt != null) stmt.close();
            }
        }
        finally {
            TurbineDB.releaseConnection(dbc);
        }
        return encrypted;
    }
}
@


1.1.2.1
log
@Classes ported to the Turbine Peer system. -dlr and leonardr
@
text
@a0 400
/* ================================================================
 * Copyright (c) 2001 CollabNet.  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 acknowlegement: "This product includes
 * software developed by CollabNet (http://www.collab.net/)."
 * Alternately, this acknowlegement may appear in the software itself, if
 * and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The hosted project names must not be used to endorse or promote
 * products derived from this software without prior written
 * permission. For written permission, please contact info@@collab.net.
 * 
 * 5. Products derived from this software may not use the "Tigris" name
 * nor may "Tigris" appear in their names without prior written
 * permission of CollabNet.
 * 
 * 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 COLLABNET 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 consists of voluntary contributions made by many
 * individuals on behalf of CollabNet.
 */

package org.tigris.helm.om.peer;

import org.apache.turbine.util.db.Criteria;
import org.tigris.helm.om.*;
import org.tigris.helm.DoesNotExist;
import org.tigris.helm.tool.PeerTool;

/**
 * Extension of generated Peer BaseUserPeer.
 *
 * @@author <a href="mailto:leonardr@@collab.net">Leonard Richardson</a>
 */
public class UserPeer extends BaseUserPeer
{
    //
    // Special users.
    // 
    public static final String NOBODY_USER_LOGIN_NAME = "**Nobody";
    public static final String DOMAIN_USERS_LOGIN_NAME = "*All users in domain";

    public static final String GUEST_LOGIN_NAME = "guest";

    //
    // Special users.
    //

    /**
     * Gets the database key associated with the special user that represents 
     * the "all users in domain" user group for the specified domain.
     *
     * @@param domainID      The database key of the domain to retrieve the 
     *                      special user for.
     */
    public static User getDomainUser(Domain domain)
        throws Exception
    {
        Criteria c = new Criteria().add(UserPeer.DOMAIN_ID, domain.getID())
            .add(UserPeer.TYPE, UserType.DOMAIN);
        User u = null;
        try {
            u = (User)UserPeer.doSelect(c).get(0);
        } catch (DoesNotExist e) {
            throw new Exception("ERROR: Could not locate special domain user for " + domain.getName());
        }
        return u;
    }
    
    /**
     * Gets the database key associated with the special user that
     * represents the group of all users in the host domain.
     */
    public static User getHostUser()
        throws Exception
    {
        return getDomainUser(DomainPeer.getHostDomain());
    }
    
    /**
     * Gets the special user for a given domain.
     */
    public static User getNobodyUser()
        throws Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.TYPE, UserType.NOBODY);
        User u = null;
        try {
            u = (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Nobody user");
        } catch (DoesNotExist e) {
            throw new Exception("ERROR: Could not locate special 'nobody' user!");
        }
        return u;
    }

    /**
     * Gets the special guest user.
     */
    public static User getGuestUser()
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.LOGIN_NAME, UserPeer.GUEST_LOGIN_NAME)
            .add(UserPeer.DOMAIN_ID, DomainPeer.getHostDomain().getID());
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Guest user");
    }
    
    //
    // Ways of retrieving User objects.
    //

    /**
     * Returns the user with the specified ID.
     */
    public static User getInstance(String userID)
        throws Exception
    {
        return UserPeer.retrieveByPK(Integer.parseInt(userID));
    }

    /**
     * Returns the user for a specified domain and login name.
     */
    public static User getInstanceByLoginName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.LOGIN_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with login name of " + name
                                         + " in " + domain.getID());
    }

    /**
     * Returns the user for a specified domain and real name.
     */
    public static User getInstanceByRealName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.REAL_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User named " + name,
                                         "in " + domain.getName());
    }

    /**
     * Returns the user for a specified domain and email address.
     */
    public static User getInstanceByEmail(Domain domain, String email)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.EMAIL, email);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with email " + email +
                                         " in " + domain.getName());
    }
    
    private static Criteria checkThisAndHostDomain(Criteria c, Domain domain)
        throws Exception
    {
        String[] domains = { domain.getID(), DomainPeer.getHostDomain().getID() };
        c.addIn(DOMAIN_ID, domains);
        return c;
    }

    /**
     * Throws an exception if the specified information corresponds to an
     * existing user.
     *  
     * @@param domainID ID of the domain to check
     * @@param loginName  Login name of the user to search for.
     * @@param
     */
//     public void assertUserNonexistance(String domainID, String loginName)
//         throws DBException, AlreadyExists
//     {
//         // TODO: Check the host domain as well.
//         Criterion c = new Criterion(LOGIN_NAME, loginName);
//         c.and(new Criterion(DOMAIN_ID, domainID));
//         Record user = getFirstMatchingUser(c);
//         if (user != null)
//         {
//             throw new AlreadyExists
//                 ("User in domain " + domainID + " with loginName " + loginName);
//         }
//     }


//     ////////////////////////////////////////////////////////////////
//     // Mutator methods.
//     ////////////////////////////////////////////////////////////////

//     /**
//      * Updates an existing user or adds a new user to the database 
//      * (depending on whether given a <code>userID</code> or not).
//      *
//      * Note: This method only changes the database. It does not run
//      * scripts.
//      *
//      * @@param domainID      Domain in which the new user resides.
//      * @@param loginName       Login ID of the new user.
//      * @@param email         Email Address of the new user.
//      * @@param realName      Real name of the new user.
//      * @@param organization  Organization with which the new user is associated.
//      * @@param password      Unencrypted password for the new user.
//      * @@param type          Type of the user.
//      * @@return  The record for the updated user.
//      *
//      * @@exception DBException
//      */
//     public synchronized Record addUser 
//         (String domainID, String loginName, String email, 
//          String realName, String organization, 
//          String password, String type)
//         throws DBException, AlreadyExists
//     {
//         assertUserNonexistance(domainID, loginName);
//         Record user = null;
//         try {
//             user = updateUser(null, domainID, loginName, email, realName, 
//                               organization, password, type);
//         } catch (DoesNotExist ignore) {
//             //Can't happen on new user creation
//         }
//         return user;
//     }

//     /**
//      * Updates an existing user or adds a new user to the database 
//      * (depending on whether given a <code>userID</code> or not).
//      *
//      * Note: This method only changes the database. It does not run
//      * scripts.
//      *
//      * @@param userID        ID of the user to edit (leave null to add new)
//      * @@param domainID      Domain in which the user resides.
//      * @@param loginName       Login ID of the user.
//      * @@param email         Email Address of the user.
//      * @@param realName      Real name of the user.
//      * @@param organization  Organization with which the user is associated.
//      * @@param password      Unencrypted password for the user.
//      * @@param type          Type of the user.
//      *
//      * @@return  The record for the updated user.
//      *
//      * @@exception DBException
//      */
//     private Record updateUser (String userID, String domainID,
//                                String loginName, String email, 
//                                String realName, String organization, 
//                                String password, String type)
//         throws DBException, DoesNotExist
//     {
//         DBConnection dbConn = null;
//         Record user = null;
//         TableDataSet users = null;

//         try
//         {
//             dbConn = TurbineDB.getConnection();
//             Connection connection = dbConn.getConnection();           

//             String oldPassword = null;
//             String encryptedPassword = null;

//             if (userID != null)
//             {
//                 user = getUser(userID);
//                 oldPassword = user.getValue(PASSWORD).asString();
//             } else {
//                 users = new TableDataSet (connection, TABLE_NAME, keydef);
//                 user = users.addRecord();                
//             }
            
//             if (password != null)
//             {
//                 encryptedPassword = encryptPassword(connection, password);
//             }

//             // Do update.
//             if (domainID != null) user.setValue(DOMAIN_ID, domainID);
//             if (loginName != null) user.setValue(LOGIN_ID, loginName);
//             if (email != null) user.setValue(EMAIL, email);
//             if (realName != null) user.setValue(NAME, realName);
//             if (organization != null) user.setValue(ORGANIZATION, organization);
//             if (encryptedPassword != null) user.setValue(PASSWORD, encryptedPassword);
//             user.save();

//             if (userID == null)
//             {
//                 // NOTE: There is no way to refresh a Village Record which has
//                 // been created using TableDataSet.addRecord().
//                 userID = getLastInsertedID(connection).toString();
//                 user.setValue(USER_ID, userID);
//             }
//         } catch (Exception e) {
//             throw new DBException(e);
//         } finally {
//             registerToClose(users);
//             try {
//                 TurbineDB.releaseConnection(dbConn);
//             } catch (Exception e) {
//                 throw new DBException(e);
//             }
//         }
        
//         return user;
//     }

//     /**
//      *  Deletes an existing user record from the database
//      *
//      * @@param	userID    the ID of the user to delete
//      * @@exception	DBException if a database error occurs.
//      */
//     public void deleteUser (String userID)
// 	throws DBException
//     {
//         Record user = null;
//         try {
//             user = getUser(userID);
//         } catch (DoesNotExist ignore) {}

//         if (user != null)
//         {
//             try {
//                 user.markToBeDeleted();
//                 user.save();
//             } catch (DataSetException e) {
//                 throw new DBException(e);
//             } catch (SQLException e) {
//                 throw new DBException(e);
//             }
//         }
//     }

//     /**
//      * Uses the database to encrypt the provided clear text password.
//      *
//      * @@param conn   The JDBC connection to use.
//      * @@param passwd The clear text password to encrypt.
//      * @@return       The encrypted password.
//      */
//     protected String encryptPassword (Connection conn, String passwd)
//         throws SQLException
//     {
//         String encrypted = null;
//         Statement stmt = conn.createStatement();
//         try
//         {
//             StringBuffer buf = new StringBuffer("select PASSWORD(");
//             buf.append(QuotedString.from(passwd)).append(')');
//             ResultSet rset = stmt.executeQuery(buf.toString());

//             if (rset.next())
//             {
//                 encrypted = rset.getString(1);
//             }
//         }
//         finally
//         {
//             if (stmt != null) stmt.close();
//         }
//         return encrypted;
//     }



}

@


1.1.2.2
log
@Made use of getFirstBO() overload which takes a Domain as there
"where" parameter.
@
text
@d156 2
a157 2
                                         "User with login name of " + name,
                                         domain);
d170 2
a171 1
                                         "User named " + name, domain);
d184 2
a185 1
                                         "User with email " + email, domain);
@


1.1.2.3
log
@Added MapBuilder classes.
@
text
@a57 1
 * @@author <a href="mailto:dlr@@collab.net">Daniel Rall</a>
@


1.1.2.4
log
@Added getSuperUser() method to retreive the root user.
@
text
@a67 1
    public static final String ROOT_LOGIN_NAME = "root";
a122 14
     * Gets the special super user.
     * <p>
     * TODO: Remove db hit via caching.
     */
    public static User getSuperUser()
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.LOGIN_NAME, UserPeer.ROOT_LOGIN_NAME)
            .add(UserPeer.DOMAIN_ID, DomainPeer.getHostDomain().getID());
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Root user");
    }

    /**
a123 2
     * <p>
     * TODO: Remove db hit via caching.
d133 1
a133 1

@


1.1.2.5
log
@Ported assertUserNonexistance() method and migrated to UserType
interface.
@
text
@a48 2
import java.util.List;

d51 1
a51 1
import org.tigris.helm.*;
d79 2
a80 1
     * @@param domain The domain to retrieve the special user for.
d85 2
a86 3
        Criteria c = new Criteria()
            .add(UserPeer.DOMAIN_ID, domain.getID())
            .add(UserPeer.TYPE, User.DOMAIN_TYPE);
d90 2
a91 5
        }
        catch (DoesNotExist e) {
            throw new Exception
                ("ERROR: Could not locate special domain user for " +
                 domain.getName());
d113 1
a113 1
            .add(UserPeer.TYPE, User.NOBODY_TYPE);
d207 2
a208 3
        String[] domainIDs = { domain.getID(),
                               DomainPeer.getHostDomain().getID() };
        c.addIn(DOMAIN_ID, domainIDs);
d220 13
a232 13
    public void assertUserNonexistance(Domain domain, String loginName)
        throws AlreadyExists, Exception
    {
        // TODO: Check the host domain as well.
        Criteria c = new Criteria()
            .add(LOGIN_NAME, loginName);
        checkThisAndHostDomain(c, domain);
        List u = UserPeer.doSelect(c);
        if (u.isEmpty()) {
            throw new AlreadyExists("User with loginName of " + loginName,
                                    "domain named " + domain);
        }
    }
d412 3
d416 1
@


1.1.2.6
log
@Ported deleteUser() as delete().
@
text
@d362 26
a387 12
    /**
     * Deletes the corresponding user record from the database.
     *
     * @@exception Exception Likely a database error.
     */
    public void delete(User user)
	throws Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.USER_ID, user.getID());
        UserPeer.doDelete(c);
    }
@


1.1.2.7
log
@Checking host domain as well.
@
text
@d229 1
d245 34
a278 34
    /**
     * Updates an existing user or adds a new user to the database 
     * (depending on whether given a <code>userID</code> or not).
     *
     * Note: This method only changes the database. It does not run
     * scripts.
     *
     * @@param domainID      Domain in which the new user resides.
     * @@param loginName       Login ID of the new user.
     * @@param email         Email Address of the new user.
     * @@param realName      Real name of the new user.
     * @@param organization  Organization with which the new user is associated.
     * @@param password      Unencrypted password for the new user.
     * @@param type          Type of the user.
     * @@return  The record for the updated user.
     *
     * @@exception DBException
     */
    public synchronized Record add(Domain domain, String loginName,
                                   String email, String realName,
                                   String organization, String password,
                                   String type)
        throws AlreadyExists, Exception
    {
        assertUserNonexistance(domain, loginName);
        Record user = null;
        try {
            user = updateUser(null, domainID, loginName, email, realName, 
                              organization, password, type);
        } catch (DoesNotExist ignore) {
            //Can't happen on new user creation
        }
        return user;
    }
@


1.1.2.8
log
@The add() method is no longer necessary.  Use doInsert(User) instead.
@
text
@d240 38
a277 3
    ////////////////////////////////////////////////////////////////
    // Mutator methods.
    ////////////////////////////////////////////////////////////////
@


1.1.2.9
log
@doDelete(User) does the trick just as well.  Moving named method to
User business object.
@
text
@d326 13
@


1.1.2.10
log
@Ported encryptPassword() method.
@
text
@a49 2
import java.sql.PreparedStatement;
import java.sql.ResultSet;
a51 3
import org.apache.turbine.util.db.pool.DBConnection;
import org.apache.turbine.services.db.TurbineDB;

d326 29
a354 32
    /**
     * Uses the database to encrypt the provided clear text password.
     *
     * @@param passwd The clear text password to encrypt.
     * @@return       The encrypted password.
     *
     * @@exception Exception Database error occurred.
     */
    protected String encryptPassword(String passwd)
        throws Exception
    {
        String encrypted = null;
        DBConnection dbc = null;
        try {
            PreparedStatement stmt =
                dbc.getConnection().prepareStatement("select password(?)");
            stmt.setString(1, passwd);
            try {
                ResultSet rset = stmt.executeQuery();
                if (rset.next()) {
                    encrypted = rset.getString(1);
                }
            }
            finally {
                if (stmt != null) stmt.close();
            }
        }
        finally {
            TurbineDB.releaseConnection(dbc);
        }
        return encrypted;
    }
@


1.1.2.11
log
@The assertUserNonexistance() is static.
@
text
@d231 1
a231 1
    public static void assertUserNonexistance(Domain domain, String loginName)
@


1.1.2.12
log
@Preparing save() (previously updateUser()) for transfer back to User.
@
text
@d257 2
a258 2
//      * @@param domain        Domain in which the user resides.
//      * @@param loginName     Login name of the user.
d265 2
d269 5
a273 4
//     private void save(Domain domain, String loginName, String email, 
//                       String realName, String organization, String passwd, 
//                       String type)
//         throws DoesNotExist, Exception
d275 9
d309 20
@


1.1.2.13
log
@Switched to throwing Errors intead of Exceptions for critical
problems.
@
text
@d99 3
a101 2
            throw new Error("Could not locate special domain user for " +
                            domain.getName());
d105 1
a105 1

d127 2
a128 3
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special 'nobody' user!");
@


1.1.2.14
log
@Moved factory methods back into User.
@
text
@d161 83
@


1.1.2.15
log
@More porting for projects and user groups.
@
text
@d50 2
a51 2

import java.sql.*;
d88 1
a88 1
    public static UserGroup getDomainUser(Domain domain)
d94 1
a94 1
        UserGroup g = null;
d96 1
a96 1
            g = ((User)UserPeer.doSelect(c).get(0)).asGroup();
d102 1
a102 1
        return g;
d109 1
a109 1
    public static UserGroup getHostUser()
a114 16
    //
    // Ways of retrieving ProjectGroup objects.
    //
    public static UserGroup getGroupInstance(String projectID)
        throws Exception
    {
        return UserPeer.retrieveByPK(Integer.parseInt(projectID)).asGroup();
    }

    public static UserGroup getGroupInstanceByName(Domain domain,
                                                      String name)
        throws Exception
    {
        return User.getInstanceByLoginName(domain, name).asGroup();
    }

@


1.1.2.16
log
@Moved User factory methods back into UserPeer.  Ping pong.
@
text
@a115 62
    // Ways of retrieving User objects.
    //

    /**
     * Returns the user with the specified ID.
     */
    public static User getInstance(String userID)
        throws Exception
    {
        return UserPeer.retrieveByPK(Integer.parseInt(userID));
    }

    /**
     * Returns the user for a specified domain and login name.
     */
    public static User getInstanceByLoginName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.LOGIN_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with login name of " + name,
                                         domain);
    }

    /**
     * Returns the user for a specified domain and real name.
     */
    public static User getInstanceByRealName(Domain domain, String name)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.REAL_NAME, name);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User named " + name, domain);
    }

    /**
     * Returns the user for a specified domain and email address.
     */
    public static User getInstanceByEmail(Domain domain, String email)
        throws DoesNotExist, Exception
    {
        Criteria c = new Criteria()
            .add(UserPeer.EMAIL, email);
        checkThisAndHostDomain(c, domain);
        return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                         "User with email " + email, domain);
    }
    
    public static Criteria checkThisAndHostDomain(Criteria c, Domain domain)
        throws Exception
    {
        String[] domainIDs = { domain.getID(),
                               DomainPeer.getHostDomain().getID() };
        c.addIn(UserPeer.DOMAIN_ID, domainIDs);
        return c;
    }

    //
d121 1
a121 1
        return retrieveByPK(Integer.parseInt(projectID)).asGroup();
d128 1
a128 1
        return getInstanceByLoginName(domain, name).asGroup();
d138 1
a138 1
            .add(TYPE, User.NOBODY_TYPE);
d158 2
a159 2
            .add(LOGIN_NAME, UserPeer.ROOT_LOGIN_NAME)
            .add(DOMAIN_ID, DomainPeer.getHostDomain().getID());
d172 2
a173 2
            .add(LOGIN_NAME, UserPeer.GUEST_LOGIN_NAME)
            .add(DOMAIN_ID, DomainPeer.getHostDomain().getID());
@


1.1.2.17
log
@Corrected param name.
@
text
@d180 1
a180 1
    public static UserGroup getGroupInstance(String userID)
d183 1
a183 1
        return retrieveByPK(Integer.parseInt(userID)).asGroup();
d186 2
a187 1
    public static UserGroup getGroupInstanceByName(Domain domain, String name)
@


1.1.2.18
log
@Missing guest or super user is very, very bad.
@
text
@d216 1
a216 1
        throws Exception
d221 1
a221 6
        try {
            return (User)PeerTool.getFirstBO(UserPeer.doSelect(c), "Root user");
        }
        catch (DoesNotExist e) {
            throw new Error("Super user cannot be found!");
        }
d230 1
a230 1
        throws Exception
d235 1
a235 7
        try {
            return (User)PeerTool.getFirstBO(UserPeer.doSelect(c),
                                             "Guest user");
        }
        catch (DoesNotExist e) {
            throw new Error("Guest user cannot be found!");
        }
@


1.1.2.19
log
@Added horrible hacky methods to replace previous hacky and nonfunctional methods of obtaining UserGroup objects.
@
text
@a49 1
import java.util.Vector;
a56 2
import org.tigris.helm.om.map.UserMapBuilder;

a68 5

    /** the mapbuilder for this class. stolen from the generated peer. */
    private static final UserMapBuilder mapBuilder = 
        (UserMapBuilder)getMapBuilder(UserMapBuilder.CLASS_NAME);

d78 4
d178 1
a178 1
    // Ways of retrieving UserGroup objects. These suck.
d183 1
a183 5
        int user_id = Integer.parseInt(userID);
        Criteria criteria = new Criteria();
        if( user_id > 0 )
            criteria.add( UserPeer.USER_ID, user_id );
        return getFirstUserGroup(criteria);
d189 1
a189 27
        int domainID = domain.getDomainId();        
        Criteria criteria = new Criteria();
        if( domainID > 0 )
            criteria.add( UserPeer.DOMAIN_ID, domainID );
        return getFirstUserGroup(criteria);
    }

    private static UserGroup getFirstUserGroup(Criteria criteria)
        throws Exception
    {
        Vector UserGroupVector = doGroupSelect(criteria);
        if (UserGroupVector.size() != 1)
        {
            throw new Exception("Failed to select one and only one row.");
        }
        else
        {
            return (UserGroup) UserGroupVector.firstElement();
        }

    }

    private static Vector doGroupSelect(Criteria criteria)
        throws Exception
    {
        criteria.setDbName(mapBuilder.getDatabaseMap().getName());
        return doSelect (criteria,"org.tigris.helm.om.UserGroup", null);
@


1.1.2.20
log
@Added methods and fields for the use of PeerBackedList.
@
text
@a77 16
    // Special data structures and methods for paginating lists of users.
    // 

    /**
     * Gets the first letter of the appropriate field.
     */
    public static String pageGuide(Object o)
    {
        User u = (User)o;
        String relevantString = u.getLoginName();
        return relevantString.substring(0,1).toUpperCase();
    }

    public static final String DEFAULT_ORDER_BY = LOGIN_NAME;

    //
@


1.1.2.21
log
@Additions to User to support the new face of pagination/filtering.
@
text
@d49 2
a50 1
import java.util.*;
d73 1
a73 2
    /** the mapbuilder for this class. stolen from the generated peer so
     that doGroupSelect will work.*/
d79 1
a79 3
    //     

    public static Map filterableFields = new HashMap();
d82 1
a82 3
     * Gets the first letter of the ordered-by field. With the new
     * thing which gets an object by its field name, this might be movable
     * out of the peer so long as DEFAULT_ORDER_BY is here.
d90 1
a90 4
    
    /**
     * How objects of this type should be ordered in lists.
     */
a100 11

    /**
     * Static initializer; initializes the filterableFields data structure.
     */
    static
    { 
        filterableFields.put("Real Name", REAL_NAME);
        filterableFields.put("Login Name", LOGIN_NAME);
        filterableFields.put("Email", EMAIL);
        filterableFields.put("Organization", ORGANIZATION);
    };    
@


1.1.2.22
log
@Skeleton to assert a valid login.
@
text
@a54 1
import org.apache.turbine.util.TurbineException;
a118 12

    public static void assertValidLogin(Domain domain, String loginName,
                                        String password)
        throws TurbineException
    {
        // TODO: FIXME
        if (true) {
        }
        else {
            throw new TurbineException("Invalid login");
        }
    }
@


1.1.2.23
log
@Added JavaDoc.
@
text
@a120 10
    /**
     * Asserts that the provided login/password token is valid in the given
     * domain.
     *
     * @@param domain    The domain to check the login name in.
     * @@param loginName The login name to check the password of.
     * @@param password  The password to check.
     *
     * @@exception TurbineException Invalid login.
     */
@


1.1.2.24
log
@Added implementation of assertValidLogin() method.
@
text
@a129 1
     * @@exception Exception        Error condition, probably database related.
d133 1
a133 1
        throws TurbineException, Exception
d135 2
a136 17
        boolean isValid = false;
        DBConnection dbc = null;
        try {
            PreparedStatement stmt = dbc.getConnection().prepareStatement
                ("select " + USER_ID + " from " + TABLE_NAME + " where " +
                 LOGIN_NAME + '=' + loginName + " and " + PASSWORD +
                 "=password(?)");
            stmt.setString(1, password);
            try {
                ResultSet rset = stmt.executeQuery();
                if (!rset.next()) {
                    throw new TurbineException("Invalid login");
                }
            }
            finally {
                if (stmt != null) stmt.close();
            }
d138 2
a139 2
        finally {
            TurbineDB.releaseConnection(dbc);
@


1.1.2.25
log
@Corrected a couple of NPEs.
@
text
@a138 1
            dbc = TurbineDB.getConnection();
a424 1
            dbc = TurbineDB.getConnection();
@


1.1.2.26
log
@Propertly quote login name.
@
text
@d142 3
a144 3
                 LOGIN_NAME + "=? and " + PASSWORD + "=password(?)");
            stmt.setString(1, loginName);
            stmt.setString(2, password);
@


1.1.2.27
log
@Ported exists() method.
@
text
@a160 15
     * Checks whether the specified user exists.
     */
    public static boolean exists(Domain domain, String loginName)
        throws Exception
    {
        try {
            getInstanceByLoginName(domain, loginName);
            return true;
        }
        catch (DoesNotExist e) {
            return false;
        }
    }

    /**
@


1.1.2.28
log
@* Renamed the concept of the "guest" user to "anonymous".
* JavaDoc'd and reduced the accessibility of login name constants.
@
text
@d107 2
a108 9
    /**
     * The login name of the super user.
     */
    protected static final String ROOT_LOGIN_NAME = "root";

    /**
     * The login name of the anonymous user (previously the guest user).
     */
    protected static final String ANONYMOUS_LOGIN_NAME = "guest";
a352 9
     * @@deprecated Use getAnonymousUser() instead.
     */
    public static final User getGuestUser()
        throws Exception
    {
        return getAnonymousUser();
    }

    /**
d357 1
a357 1
    public static User getAnonymousUser()
d361 1
a361 1
            .add(LOGIN_NAME, UserPeer.ANONYMOUS_LOGIN_NAME)
@


1.1.2.29
log
@Totally removed getGuestUser() (deprecated by getAnonymousUser()).
@
text
@d360 9
@


1.1.2.30
log
@Forgive me, father, for I have sinned. It has been six days since my last confession. I have made a hacky method public so that it might be accessed from another package.
@
text
@d315 1
a315 1
    public static Vector doGroupSelect(Criteria criteria)
@


1.1.2.31
log
@Fixing compile errors.
@
text
@d73 5
d303 1
a303 1
        Vector UserGroupVector = doSelect(criteria);
d313 7
@


1.1.2.32
log
@Oops, host user is really of a different type; fix this, as there's no need for another type.
@
text
@d207 1
a207 10
        Criteria c = new Criteria()
            .add(UserPeer.TYPE, User.HOST_TYPE);
        UserGroup g = null;
        try {
            g = ((User)UserPeer.doSelect(c).get(0)).asGroup();
        }
        catch (DoesNotExist e) {
            throw new Error("Could not locate special host user!");
        }
        return g;
@


1.1.2.33
log
@Added getInstanceByIdentifier, which tries everything it can think of to turn a string into a User object.
@
text
@a232 42
     * Tries to get a user by login name, real name, email address, and
     * ID. If all of these fail, throws an exception.
     */
    public static User getInstanceByIdentifier
        (Domain domain, String identifier)
        throws DoesNotExist, Exception
    {
        User u = null;
        try
        {
            u =  getInstanceByLoginName(domain, identifier);
        }
        catch (DoesNotExist loginNameEx)
        {
            try 
            {
                u = getInstanceByEmail(domain, identifier);
            }
            catch (DoesNotExist emailEx) 
            {
                try 
                {
                    u = getInstanceByRealName(domain, identifier);
                }
                catch (DoesNotExist nameEx)
                {

                    try {
                        u = getInstance(identifier);
                    } 
                    catch (DoesNotExist idEx)
                    {
                        throw new DoesNotExist("No such user on system: " + 
                                               identifier);
                    }
                }
            }
        }
        return u;
    }

    /**
@


1.1.2.34
log
@Normalized copyright dates.
@
text
@d2 1
a2 1
 * Copyright (c) 2000-2001 CollabNet.  All rights reserved.
@


1.1.2.35
log
@Added new imports necessitated by Torque.
@
text
@a59 1
import org.tigris.helm.om.base.*;
@


1.1.2.36
log
@Throw an exception using a more informative message, in the manner
that the exception was meant to be used.
@
text
@d266 2
a267 3
                        throw new DoesNotExist("User identified by " + 
                                               identifier, "domain named " +
                                               domain.getName());
@


1.1.2.37
log
@* Improved documentation and clarity of a few methods (mostly
  factory methods).
* Reimplemented getFirstUserGroup(Criteria) using PeerTool.getFirstBO().
@
text
@a225 3
     *
     * @@param userID The primary key of the user to retrieve.
     * @@return       The requested user.
d235 1
a235 7
     * ID.  If all of these fail, throws an exception.
     *
     * @@param domain     The domain to look in.
     * @@param identifier The primary key of the user to retrieve.
     * @@return           The first matching user.
     *
     * @@exception DoesNotExist No matches for the provided identifier.
d237 2
a238 2
    public static User getInstanceByIdentifier(Domain domain,
                                               String identifier)
d258 1
a258 1
                catch (DoesNotExist realNameEx)
d331 1
a331 1
        int uid = Integer.parseInt(userID);
d333 2
a334 3
        if (uid > 0) {
            criteria.add(UserPeer.USER_ID, uid);
        }
d348 2
a349 2
    private static final UserGroup getFirstUserGroup(Criteria criteria)
        throws DoesNotExist, Exception
d351 10
a360 2
        return (UserGroup)PeerTool.getFirstBO(doSelect(criteria),
                                              "User group");
@


1.1.2.38
log
@Got rid of now-superfluous pageGuide method.
@
text
@d79 12
@


