turbineusermanagement.java

来自「jetspeed源代码」· Java 代码 · 共 620 行 · 第 1/2 页

JAVA
620
字号
/*
 * Copyright 2000-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.jetspeed.services.security.turbine;

import java.util.List;
import java.util.Iterator;
import java.util.Date;
import javax.servlet.ServletConfig;
import java.security.Principal;
import java.util.Vector;

// Torque
import org.apache.torque.util.Criteria;
import org.apache.torque.om.NumberKey;

// Turbine
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;

// Jetspeed Database OM
import org.apache.jetspeed.om.security.turbine.TurbineUser;
import org.apache.jetspeed.om.security.turbine.TurbineUserPeer;

import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.om.profile.Profile;

// Jetspeed Security
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.BaseJetspeedUser;
import org.apache.jetspeed.om.security.UserNamePrincipal;
import org.apache.jetspeed.om.security.UserIdPrincipal;

import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.Profiler;
import org.apache.jetspeed.services.PsmlManager;
import org.apache.jetspeed.services.security.UserManagement;
import org.apache.jetspeed.services.security.JetspeedSecurityService;

import org.apache.jetspeed.services.security.CredentialsManagement;
import org.apache.jetspeed.services.security.UserException;
import org.apache.jetspeed.services.security.UnknownUserException;
import org.apache.jetspeed.services.security.NotUniqueUserException;
import org.apache.jetspeed.services.security.JetspeedSecurityException;
import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.turbine.services.localization.Localization;
import org.apache.turbine.services.rundata.RunDataService;

// Password encryption
import javax.mail.internet.MimeUtility;
import java.security.MessageDigest;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;


/**
 * Default Jetspeed-Turbine User Management implementation
 *
 *
 * @author <a href="mailto:david@bluesunrise.com">David Sean Taylor</a>
 * @author <a href="mailto:morciuch@apache.org">Mark Orciuch</a>
 * @version $Id: TurbineUserManagement.java,v 1.13 2004/02/23 03:54:49 jford Exp $
 */

public class TurbineUserManagement extends TurbineBaseService
                                   implements UserManagement,
                                              CredentialsManagement
{
    /**
     * Static initialization of the logger for this class
     */    
    private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(TurbineUserManagement.class.getName());
    
    private final static String CONFIG_SECURE_PASSWORDS_KEY = "secure.passwords";
    private final static String CONFIG_SECURE_PASSWORDS_ALGORITHM = "secure.passwords.algorithm";
    private final static String CONFIG_SYSTEM_USERS = "system.users";

    boolean securePasswords = false;
    String passwordsAlgorithm = "SHA";
    Vector systemUsers = null;

    private final static String CONFIG_NEWUSER_ROLES     = "newuser.roles";
    private final static String [] DEFAULT_CONFIG_NEWUSER_ROLES =
    { "user" };

    String roles[] = null;

    /** The JetspeedRunData Service. */
    private JetspeedRunDataService runDataService = null;

    ///////////////////////////////////////////////////////////////////////////
    // User Management Interfaces
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Retrieves a <code>JetspeedUser</code> given the primary principle.
     * The principal can be any valid Jetspeed Security Principal:
     *   <code>org.apache.jetspeed.om.security.UserNamePrincipal</code>
     *   <code>org.apache.jetspeed.om.security.UserIdPrincipal</code>
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param principal a principal identity to be retrieved.
     * @return a <code>JetspeedUser</code> associated to the principal identity.
     * @exception UserException when the security provider has a general failure retrieving a user.
     * @exception UnknownUserException when the security provider cannot match
     *            the principal identity to a user.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public JetspeedUser getUser(Principal principal)
        throws JetspeedSecurityException
    {
        // TODO: check requestor for permission

        Criteria criteria = new Criteria();
        if (principal instanceof UserNamePrincipal)
        {
            criteria.add(TurbineUserPeer.LOGIN_NAME, principal.getName());
        }
        else if (principal instanceof UserIdPrincipal)
        {
            criteria.add(TurbineUserPeer.USER_ID, principal.getName());
        }
        else
        {
            throw new UserException("Invalid Principal Type in getUser: " + principal.getClass().getName());
        }
        List users;
        try
        {
            users = TurbineUserPeer.doSelectUsers(criteria);
        }
        catch(Exception e)
        {
            String message = "Failed to retrieve user '" + principal.getName() + "'";
            logger.error( message, e );
            throw new UserException( message, e );
        }
        if ( users.size() > 1 )
        {
            throw new UserException(
                "Multiple Users with same username '" + principal.getName() + "'");
        }
        if ( users.size() == 1 )
        {
            return (JetspeedUser)users.get(0);
        }
        throw new UnknownUserException("Unknown user '" + principal.getName() + "'");

    }

  /**
     * Retrieves a collection of all <code>JetspeedUser</code>s.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @return a collection of <code>JetspeedUser</code> entities.
     * @exception UserException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Iterator getUsers()
        throws JetspeedSecurityException
    {
        Criteria criteria = new Criteria();
        List users;
        try
        {
            users = TurbineUserPeer.doSelectUsers(criteria);
        }
        catch(Exception e)
        {
            logger.error( "Failed to retrieve users ", e );
            throw new UserException("Failed to retrieve users ", e);
        }
        return users.iterator();
    }

    /**
     * Retrieves a collection of <code>JetspeedUser</code>s filtered by a security
     * provider-specific query string. For example SQL, OQL, JDOQL.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @return a collection of <code>JetspeedUser</code> entities.
     * @exception UserException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Iterator getUsers(String filter)
        throws JetspeedSecurityException
    {
        // TODO: implement this with a SQL string

        Criteria criteria = new Criteria();
        List users;
        try
        {
            users = TurbineUserPeer.doSelectUsers(criteria);
        }
        catch(Exception e)
        {
            logger.error( "Failed to retrieve users ", e );
            throw new UserException("Failed to retrieve users ", e);
        }
        return users.iterator();
    }

    /**
     * Saves a <code>JetspeedUser</code>'s attributes into permanent storage.
     * The user's account is required to exist in the storage.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception UserException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void saveUser(JetspeedUser user)
        throws JetspeedSecurityException
    {
        if(!accountExists(user, true))
        {
            throw new UnknownUserException("Cannot save user '" + user.getUserName() +
                                           "', User doesn't exist");
        }
        Criteria criteria = TurbineUserPeer.buildCriteria(user);
        try
        {
            TurbineUserPeer.doUpdate(criteria);
        }
        catch(Exception e)
        {
            logger.error( "Failed to save user object ", e );
            throw new UserException("Failed to save user object ", e);
        }

    }


    /**
     * Adds a <code>JetspeedUser</code> into permanent storage.
     * The security service can throw a <code>NotUniqueUserException</code> when the public
     * credentials fail to meet the security provider-specific unique constraints.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception UserException when the security provider has a general failure retrieving users.
     * @exception NotUniqueUserException when the public credentials fail to meet
     *                                   the security provider-specific unique constraints.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void addUser(JetspeedUser user)
        throws JetspeedSecurityException
    {
        if(accountExists(user))
        {
            throw new NotUniqueUserException("The account '" +
                user.getUserName() + "' already exists");
        }
        String initialPassword = user.getPassword();
        String encrypted = JetspeedSecurity.encryptPassword(initialPassword);
        user.setPassword(encrypted);
        Criteria criteria = TurbineUserPeer.buildCriteria(user);
        try
        {

            NumberKey key = (NumberKey)TurbineUserPeer.doInsert(criteria);

            ((BaseJetspeedUser)user).setUserId(key.toString());

        }
        catch(Exception e)
        {
            String message = "Failed to create account '" + user.getUserName() + "'";
            logger.error( message, e );
            throw new UserException( message, e );
        }

        addDefaultPSML(user);
    }

    /*
     * A default PSML page is added for the user, and the Jetspeed default roles
     * are assigned to the new user.
     *
     * @param user The new user.
     * @throws
     */
    protected void addDefaultPSML(JetspeedUser user)
        throws JetspeedSecurityException
    {
        for (int ix = 0; ix < roles.length; ix++)
        {
            try

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?