ldapusermanagement.java

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

JAVA
603 行
字号

                JetspeedSecurity.grantRole(user.getUserName(),
                      JetspeedSecurity.getRole(roles[ix]).getName());
            }
            catch(Exception e)
            {
                logger.error("Could not grant role: " + roles[ix] + " to user " + user.getUserName(), e);
            }
        }
        try
        {
            JetspeedRunData rundata = getRunData();
            if (rundata != null)
            {
                Profile profile = Profiler.createProfile();
                profile.setUser(user);
                profile.setMediaType("html");
                Profiler.createProfile(getRunData(), profile);
            }
        }
        catch (Exception e)
        {
            logger.error( "Failed to create profile for new user ", e );
            removeUser(new UserNamePrincipal(user.getUserName()));
            throw new UserException("Failed to create profile for new user ", e);
        }
    }

    /**
     * Removes a <code>JetspeedUser</code> from the permanent store.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param principal the principal identity to be retrieved.
     * @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 void removeUser(Principal principal)
        throws JetspeedSecurityException
    {
        BasicAttributes attr= new BasicAttributes();
        Vector userurls = new Vector();
        LDAPUser user = (LDAPUser)getUser(principal);

        try
        {
            JetspeedLDAP.deleteEntry(user.getldapurl());
            PsmlManager.removeUserDocuments(user);
        }
        catch(Exception e)
        {
            logger.error( "Failed to remove account '" + user.getUserName() + "'", e );
            throw new UserException("Failed to remove account '" +
                user.getUserName() + "'", e);
        }

    }

    ///////////////////////////////////////////////////////////////////////////
    // Credentials Management
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Allows for a user to change their own password.
     *
     * @param user the JetspeedUser to change password
     * @param oldPassword the current password supplied by the user.
     * @param newPassword the current password requested by the user.
     * @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 void changePassword( JetspeedUser user,
                                String oldPassword,
                                String newPassword )
        throws JetspeedSecurityException
    {
        oldPassword = JetspeedSecurity.convertPassword(oldPassword);
        newPassword = JetspeedSecurity.convertPassword(newPassword);

        if(!accountExists(user))
        {
            throw new UnknownUserException("The account '" +
                user.getUserName() + "' does not exist");
        }
        else if (!passwordsMatch(user, oldPassword))
        {
            throw new UserException(
               "The supplied old password for '" + user.getUserName() +
                "' was incorrect");
        }

        String encrypted = JetspeedSecurity.encryptPassword( newPassword );
        user.setPassword(encrypted);

        // save the changes in the database immediately, to prevent the password
        // being 'reverted' to the old value if the user data is lost somehow
        // before it is saved at session's expiry.
        saveUser(user);
    }

    /**
     * Forcibly sets new password for a User.
     *
     * Provides an administrator the ability to change the forgotten or
     * compromised passwords. Certain implementatations of this feature
     * would require administrative level access to the authenticating
     * server / program.
     *
     * @param user              the user to change the password for.
     * @param password          the new password.
     *
     * @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 void forcePassword( JetspeedUser user, String password )
        throws JetspeedSecurityException
    {
        if(!accountExists(user))
        {
            throw new UnknownUserException("The account '" +
                user.getUserName() + "' does not exist");
        }

        String encrypted = JetspeedSecurity.encryptPassword( password );
        user.setPassword(encrypted);


        // save the changes in the database immediately, to prevent the
        // password being 'reverted' to the old value if the user data
        // is lost somehow before it is saved at session's expiry.
        saveUser(user);
    }

    /**
     * This method provides client-side encryption of passwords.
     *
     * If <code>secure.passwords</code> are enabled in 
     * JetspeedSecurity.properties,
     * the password will be encrypted, if not, it will be returned unchanged.
     * The <code>secure.passwords.algorithm</code> property can be used
     * to chose which digest algorithm should be used for performing the
     * encryption. <code>SHA</code> is used by default.
     *
     * @param password the password to process
     * 
     * @return processed password
     *
     */
    public String encryptPassword( String password )
        throws JetspeedSecurityException
    {
        if (securePasswords == false)
        {
            return password;
        }
        else if(password == null)
        {
            return null;
        }
        else if(password.startsWith(passwordsSuffix))
        {
            // A kludge
            return password;
        }
 
        return passwordsSuffix + UnixCrypt.crypt(password);
    }

    /**
     * <p>Check's if user's current password matches with the
     * supplied password.</p>
     * 
     * @param user             User whose password will be checked
     * @param suppliedPassword Password to match
     *
     * @return                 True if passwords match.
     *
     */ 
    public static boolean passwordsMatch(JetspeedUser user, String suppliedPassword)
    {
        if (securePasswords == false)
        {
            return user.getPassword().equals(suppliedPassword);
        }
        else
        {
            return UnixCrypt.matches(user.getPassword().substring(passwordsSuffix.length()), suppliedPassword);
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // Service Init
    ///////////////////////////////////////////////////////////////////////////

    /**
     * This is the early initialization method called by the
     * Turbine <code>Service</code> framework
     * @param conf The <code>ServletConfig</code>
     * @exception throws a <code>InitializationException</code> if the service
     * fails to initialize
     */
    public synchronized void init(ServletConfig conf)
        throws InitializationException
    {
        if (getInit()) return;

        super.init(conf);

        // get configuration parameters from Jetspeed Resources
        ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
                                                     .getResources(JetspeedSecurityService.SERVICE_NAME);

        securePasswords = serviceConf.getBoolean(CONFIG_SECURE_PASSWORDS_KEY,
                                                  securePasswords);
        passwordsAlgorithm = serviceConf.getString(CONFIG_SECURE_PASSWORDS_ALGORITHM,
                                                   passwordsAlgorithm);
        passwordsSuffix = serviceConf.getString(CONFIG_SECURE_PASSWORDS_SUFFIX,
                                                   passwordsSuffix);

        try
        {
            roles = serviceConf.getStringArray(CONFIG_NEWUSER_ROLES);
        }
        catch (Exception e)
        {
        }

        if (null == roles || roles.length == 0)
        {
            roles = DEFAULT_CONFIG_NEWUSER_ROLES;
        }

        this.runDataService = (JetspeedRunDataService)TurbineServices.getInstance()
               .getService(RunDataService.SERVICE_NAME);

        setInit(true);
     }

    ///////////////////////////////////////////////////////////////////////////
    // Internal
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Check whether a specified user's account exists.
     *
     * The login name is used for looking up the account.
     *
     * @param user             The user to be checked.
     * @param checkUniqueId    Make sure that we aren't 
     *                         overwriting another user
     *                         with different id.
     *
     * @return true            If the specified account exists
     *
     * @throws UserException   If there was a general db access error
     *
     */
    protected boolean accountExists( JetspeedUser user )
        throws UserException
    {
        return accountExists(user, false);
    }

    protected boolean accountExists( JetspeedUser user, boolean checkUniqueId )
        throws UserException
    {
        UserNamePrincipal principal = new UserNamePrincipal(user.getUserName());

        try
        {
            getUser(principal);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    protected JetspeedRunData getRunData()
    {
        JetspeedRunData rundata = null;

        if (this.runDataService != null)
        {
            rundata = this.runDataService.getCurrentRunData();
        }

        return rundata;
    }

}

⌨️ 快捷键说明

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