Skip to content
LdapUserDAO.java 50.8 KiB
Newer Older
            //LDAPConnection conn = this.getUnboundReadConnection();
            //conn.bind(bindRequest);
            LDAPConnection conn = this.getReadWriteConnection();
            PasswordModifyExtendedRequest passwordModifyRequest;
                        new PasswordModifyExtendedRequest(userDN.toNormalizedString(),
                                null, new String(newPassword));
                        new PasswordModifyExtendedRequest(userDN.toNormalizedString(),
                                new String(oldPassword), new String(newPassword));
Jeff Burke's avatar
Jeff Burke committed
            PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult)
Brian Major's avatar
Brian Major committed
                    conn.processExtendedOperation(passwordModifyRequest);
Jeff Burke's avatar
Jeff Burke committed
            LdapDAO.checkLdapResult(passwordModifyResult.getResultCode());
            logger.debug("updatedPassword for " + userID.getName());
Jeff Burke's avatar
Jeff Burke committed
        }
        catch (LDAPException e)
        {
            logger.debug("setPassword Exception: " + e);
            LdapDAO.checkLdapResult(e.getResultCode());
        }
    /**
     * Update a user's password. The given user and authenticating user must match.
     *
     * @param userID
     * @param oldPassword   current password.
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void setPassword(HttpPrincipal userID, String oldPassword, String newPassword)
        throws UserNotFoundException, TransientException, AccessControlException
    {
        updatePassword(userID, oldPassword, newPassword);
    }

    /**
     * Reset a user's password. The given user and authenticating user must match.
     *
     * @param userID
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void resetPassword(HttpPrincipal userID, String newPassword)
        throws UserNotFoundException, TransientException, AccessControlException
    {
     * Delete the user specified by userID from the active user tree.
     *
     * @param userID The userID.
     * @throws UserNotFoundException  when the user is not found.
     * @throws TransientException     If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void deleteUser(final Principal userID, boolean markDelete)
            throws UserNotFoundException, TransientException,
                   AccessControlException
        deleteUser(userID, config.getUsersDN(), markDelete);
    }

    /**
     * Delete the user specified by userID from the pending user tree.
     *
     * @param userID The userID.
     * @throws UserNotFoundException  when the user is not found.
     * @throws TransientException     If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void deleteUserRequest(final Principal userID)
        throws UserNotFoundException, TransientException,
        AccessControlException
    {
        deleteUser(userID, config.getUserRequestsDN(), false);
    private void deleteUser(final Principal userID, final String usersDN, boolean markDelete)
        throws UserNotFoundException, AccessControlException, TransientException
    {
        User user2Delete = getUser(userID, usersDN);
            long uuid = uuid2long(user2Delete.getID().getUUID());
            DN userDN = getUserDN(uuid, usersDN);
            if (markDelete)
            {
                List<Modification> modifs = new ArrayList<Modification>();
                modifs.add(new Modification(ModificationType.ADD, LDAP_NSACCOUNTLOCK, "true"));
                ModifyRequest modifyRequest = new ModifyRequest(userDN, modifs);
Brian Major's avatar
Brian Major committed
                LDAPResult result = getReadWriteConnection().modify(modifyRequest);
                LdapDAO.checkLdapResult(result.getResultCode());
            }
            else // real delete
            {
                DeleteRequest delRequest = new DeleteRequest(userDN);
Brian Major's avatar
Brian Major committed
                LDAPResult result = getReadWriteConnection().delete(delRequest);
                logger.info("delete result:" + delRequest);
                LdapDAO.checkLdapResult(result.getResultCode());
            }
            logger.debug("deleted " + userID.getName() + " from " + usersDN);
        }
        catch (LDAPException e1)
        {
            logger.debug("Delete Exception: " + e1, e1);
            LdapDAO.checkLdapResult(e1.getResultCode());
        }

        // getUser does not yet support nsaccountlock
        if (!markDelete)
            try
            {
                getUser(userID, usersDN);
                throw new RuntimeException(
                    "BUG: " + userID.getName() + " not deleted in " + usersDN);
            }
            catch (UserNotFoundException ignore) {}
    private Principal getPreferredPrincipal(User user)
    {
        Principal ret = null;
        Principal next = null;
        Iterator<Principal> i = user.getIdentities().iterator();
        while (i.hasNext())
        {
            next = i.next();
            if (next instanceof NumericPrincipal)
            {
                return next;
            }
            ret = next;
        }
        return ret;
    }

    DN getUserDN(User user)
        throws UserNotFoundException, TransientException, LDAPException
        Principal p = getPreferredPrincipal(user);
        if (p == null)
        {
            throw new UserNotFoundException("No identities");
        }

        // DN can be formulated if it is the numeric id
        if (p instanceof NumericPrincipal)
            return this.getUserDN(uuid2long(UUID.fromString(p.getName())), config.getUsersDN());

        // Otherwise we need to search for the numeric id
        String searchField = userLdapAttrib.get(p.getClass());
        if (searchField == null)
        {
Jeff Burke's avatar
Jeff Burke committed
            throw new IllegalArgumentException(
                    "Unsupported principal type " + p.getClass());
//      change the DN to be in the 'java' format
//      if (userID instanceof X500Principal)
//      {
//          X500Principal orderedPrincipal = AuthenticationUtil.getOrderedForm(
//              (X500Principal) userID);
//          filter = Filter.createEqualityFilter(searchField, orderedPrincipal.toString());
//      }

        Filter filter = Filter.createEqualityFilter(searchField, p.getName());
        SearchResultEntry searchResult = null;
        try
        {
            SearchRequest searchRequest = new SearchRequest(
                config.getUsersDN(), SearchScope.ONE, filter, LDAP_ENTRYDN);
Brian Major's avatar
Brian Major committed
            searchResult = getReadOnlyConnection().searchForEntry(searchRequest);
            logger.debug("getUserDN: got " + p.getName() + " from " + config.getUsersDN());
Dustin Jenkins's avatar
Dustin Jenkins committed
        }
        catch (LDAPException e)
            LdapDAO.checkLdapResult(e.getResultCode());
        if (searchResult == null)
        {
            String msg = "User not found " + p.getName() + " in " + config.getUsersDN();
            logger.debug(msg);
            throw new UserNotFoundException(msg);
        }
        return searchResult.getAttributeValueAsDN(LDAP_ENTRYDN);
    }
    protected DN getUserDN(long numericID, String usersDN)
            throws LDAPException, TransientException
        return new DN(LDAP_UID + "=" + numericID + "," + usersDN);
    private void addAttribute(List<Attribute> attributes, final String name, final String value)
    {
        if (value != null && !value.isEmpty())
        {
            attributes.add(new Attribute(name, value));
        }
    private void addModification(List<Modification> mods, final String name, final String value)
    {
        if (value != null && !value.isEmpty())
        {
            mods.add(new Modification(ModificationType.REPLACE, name, value));
        }
        else
        {
            mods.add(new Modification(ModificationType.REPLACE, name));
        }
    }

    /**
     * Checks the Ldap result code, and if the result is not SUCCESS,
     * throws an appropriate exception. This is the place to decide on
     * mapping between ldap errors and exception types
     *
     * @param code The code returned from an LDAP request.
     * @throws TransientException
     * @throws UserAlreadyExistsException
     */
    protected static void checkUserLDAPResult(final ResultCode code)
            throws TransientException, UserAlreadyExistsException
    {
        if (code == ResultCode.ENTRY_ALREADY_EXISTS)
        {
            throw new UserAlreadyExistsException("User already exists.");
        }
        else
        {
            LdapDAO.checkLdapResult(code);
        }
    }
     * Method to return a randomly generated user numeric ID. The default
     * implementation returns a value between 10000 and Integer.MAX_VALUE.
     * Services that support a different mechanism for generating numeric
     * @return
     */
    protected int genNextNumericId()
    {
        Random rand = new Random();
        return rand.nextInt(Integer.MAX_VALUE - 10000) + 10000;
    }
    protected long uuid2long(UUID uuid)
        return uuid.getLeastSignificantBits();
    protected void setInternalIdUriPrefix(String internalIdUriPrefix)
    {
        this.internalIdUriPrefix = internalIdUriPrefix;
    }

    protected InternalID getInternalID(String numericID)
    {
Jeff Burke's avatar
Jeff Burke committed
        UUID uuid = new UUID(0L, Long.parseLong(numericID));
        String uriString = internalIdUriPrefix + "?" + uuid.toString();
Jeff Burke's avatar
Jeff Burke committed
            uri = new URI(uriString);
        }
        catch (URISyntaxException e)
        {
Jeff Burke's avatar
Jeff Burke committed
            throw new RuntimeException("Invalid InternalID URI " + uriString);
        }
        return new InternalID(uri);
    }