Search in sources :

Example 1 with ModifyRequest

use of org.forgerock.opendj.ldap.requests.ModifyRequest in project OpenAM by OpenRock.

the class LdapAdapter method update.

/**
     * Update the Token based on whether there were any changes between the two.
     *
     * @param connection The non null connection to perform this call against.
     * @param previous The non null previous Token to check against.
     * @param updated The non null Token to update with.
     * @return True if the token was updated, or false if there were no changes detected.
     * @throws org.forgerock.openam.sm.datalayer.api.LdapOperationFailedException If the operation failed for a known reason.
     */
public boolean update(Connection connection, Token previous, Token updated) throws LdapOperationFailedException {
    Entry currentEntry = conversion.getEntry(updated);
    LdapTokenAttributeConversion.stripObjectClass(currentEntry);
    Entry previousEntry = conversion.getEntry(previous);
    LdapTokenAttributeConversion.stripObjectClass(previousEntry);
    ModifyRequest request = Entries.diffEntries(previousEntry, currentEntry);
    request.addControl(TransactionIdControl.newControl(AuditRequestContext.createSubTransactionIdValue()));
    // Test to see if there are any modifications
    if (request.getModifications().isEmpty()) {
        return false;
    }
    try {
        processResult(connection.modify(request));
    } catch (LdapException e) {
        throw new LdapOperationFailedException(e.getResult());
    }
    return true;
}
Also used : Entry(org.forgerock.opendj.ldap.Entry) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) LdapOperationFailedException(org.forgerock.openam.sm.datalayer.api.LdapOperationFailedException) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 2 with ModifyRequest

use of org.forgerock.opendj.ldap.requests.ModifyRequest in project OpenAM by OpenRock.

the class LDAPAuthUtils method changePassword.

/**
     * Updates to new password by using the parameters passed by the user.
     *
     * @param oldPwd Current password entered.
     * @param password New password entered.
     * @param confirmPassword Confirm password.
     * @throws LDAPUtilException
     */
public void changePassword(String oldPwd, String password, String confirmPassword) throws LDAPUtilException {
    if (password.equals(oldPwd)) {
        setState(ModuleState.WRONG_PASSWORD_ENTERED);
        return;
    }
    if (!(password.equals(confirmPassword))) {
        setState(ModuleState.PASSWORD_MISMATCH);
        return;
    }
    if (password.equals(userId)) {
        setState(ModuleState.USER_PASSWORD_SAME);
        return;
    }
    Connection modConn = null;
    List<Control> controls;
    try {
        ModifyRequest mods = LDAPRequests.newModifyRequest(userDN);
        if (beheraEnabled) {
            mods.addControl(PasswordPolicyRequestControl.newControl(false));
        }
        if (!isAd) {
            mods.addModification(ModificationType.DELETE, LDAP_PASSWD_ATTR, oldPwd);
            mods.addModification(ModificationType.ADD, LDAP_PASSWD_ATTR, password);
            modConn = getConnection();
            modConn.bind(LDAPRequests.newSimpleBindRequest(userDN, oldPwd.toCharArray()));
        } else {
            mods.addModification(ModificationType.DELETE, AD_PASSWD_ATTR, updateADPassword(oldPwd));
            mods.addModification(ModificationType.ADD, AD_PASSWD_ATTR, updateADPassword(password));
            modConn = getAdminConnection();
        }
        Result modResult = modConn.modify(mods);
        controls = processControls(modResult);
        // Were there any password policy controls returned?
        PasswordPolicyResult result = checkControls(controls);
        if (result == null) {
            if (debug.messageEnabled()) {
                debug.message("No controls returned");
            }
            setState(ModuleState.PASSWORD_UPDATED_SUCCESSFULLY);
        } else {
            processPasswordPolicyControls(result);
        }
    } catch (LdapException ere) {
        if (ere.getResult().getResultCode().equals(ResultCode.CONSTRAINT_VIOLATION)) {
            PasswordPolicyResult result = checkControls(processControls(ere.getResult()));
            if (result != null) {
                processPasswordPolicyControls(result);
            } else {
                if (isAd) {
                    setState(ModuleState.PASSWORD_NOT_UPDATE);
                } else {
                    setState(ModuleState.INSUFFICIENT_PASSWORD_QUALITY);
                }
            }
        } else if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) || ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            if (debug.messageEnabled()) {
                debug.message("changepassword:Cannot connect to " + servers + ": ", ere);
            }
            setState(ModuleState.SERVER_DOWN);
            return;
        } else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
            // Were there any password policy controls returned?
            PasswordPolicyResult result = checkControls(processControls(ere.getResult()));
            if (result != null) {
                processPasswordPolicyControls(result);
            } else {
                setState(ModuleState.INSUFFICIENT_PASSWORD_QUALITY);
            }
        } else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
            Result r = ere.getResult();
            if (r != null) {
                // Were there any password policy controls returned?
                PasswordPolicyResult result = checkControls(processControls(r));
                if (result != null) {
                    processPasswordPolicyControls(result);
                }
            }
            setState(ModuleState.PASSWORD_NOT_UPDATE);
        } else {
            setState(ModuleState.PASSWORD_NOT_UPDATE);
        }
        if (debug.warningEnabled()) {
            debug.warning("Cannot update : ", ere);
        }
    } finally {
        if (modConn != null) {
            modConn.close();
        }
    }
}
Also used : PasswordExpiringResponseControl(org.forgerock.opendj.ldap.controls.PasswordExpiringResponseControl) PasswordExpiredResponseControl(org.forgerock.opendj.ldap.controls.PasswordExpiredResponseControl) PasswordPolicyRequestControl(org.forgerock.opendj.ldap.controls.PasswordPolicyRequestControl) Control(org.forgerock.opendj.ldap.controls.Control) PasswordPolicyResponseControl(org.forgerock.opendj.ldap.controls.PasswordPolicyResponseControl) Connection(org.forgerock.opendj.ldap.Connection) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LdapException(org.forgerock.opendj.ldap.LdapException) BindResult(org.forgerock.opendj.ldap.responses.BindResult) Result(org.forgerock.opendj.ldap.responses.Result)

Example 3 with ModifyRequest

use of org.forgerock.opendj.ldap.requests.ModifyRequest in project OpenAM by OpenRock.

the class DJLDAPv3Repo method modifyGroupMembership.

/**
     * Modifies group membership data in the directory. In case the memberOf attribute is configured, this will also
     * iterate through all the user entries and modify those as well. Otherwise this will only modify the uniquemember
     * attribute on the group entry based on the operation.
     *
     * @param groupDN The DN of the group.
     * @param memberDNs The DNs of the group members.
     * @param operation Whether the members needs to be added or removed from the group. Use {@link IdRepo#ADDMEMBER}
     * or {@link IdRepo#REMOVEMEMBER}.
     * @throws IdRepoException If there was an error while modifying the membership data.
     */
private void modifyGroupMembership(String groupDN, Set<String> memberDNs, int operation) throws IdRepoException {
    ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(groupDN);
    Attribute attr = new LinkedAttribute(uniqueMemberAttr, memberDNs);
    ModificationType modType;
    if (ADDMEMBER == operation) {
        modType = ModificationType.ADD;
    } else {
        modType = ModificationType.DELETE;
    }
    modifyRequest.addModification(new Modification(modType, attr));
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        conn.modify(modifyRequest);
        if (memberOfAttr != null) {
            for (String member : memberDNs) {
                ModifyRequest userMod = LDAPRequests.newModifyRequest(member);
                userMod.addModification(modType, memberOfAttr, groupDN);
                conn.modify(userMod);
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to modify group membership. Name: " + groupDN + " memberDNs: " + memberDNs + " Operation: " + modType, ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : Modification(org.forgerock.opendj.ldap.Modification) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) ModificationType(org.forgerock.opendj.ldap.ModificationType) Connection(org.forgerock.opendj.ldap.Connection) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute)

Example 4 with ModifyRequest

use of org.forgerock.opendj.ldap.requests.ModifyRequest in project OpenAM by OpenRock.

the class DJLDAPv3Repo method modifyRoleMembership.

/**
     * Modifies role membership data in the directory. This will add/remove the corresponding nsRoleDN attribute from
     * the user entry.
     *
     * @param roleDN The DN of the role.
     * @param memberDNs The DNs of the role members.
     * @param operation Whether the members needs to be added or removed from the group. Use {@link IdRepo#ADDMEMBER}
     * or {@link IdRepo#REMOVEMEMBER}.
     * @throws IdRepoException If there was an error while modifying the membership data.
     */
private void modifyRoleMembership(String roleDN, Set<String> memberDNs, int operation) throws IdRepoException {
    Attribute attr = new LinkedAttribute(roleDNAttr, roleDN);
    Modification mod;
    if (ADDMEMBER == operation) {
        mod = new Modification(ModificationType.ADD, attr);
    } else {
        mod = new Modification(ModificationType.DELETE, attr);
    }
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        for (String memberDN : memberDNs) {
            ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(memberDN);
            modifyRequest.addModification(mod);
            conn.modify(modifyRequest);
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to modify role membership. Name: " + roleDN + " memberDNs: " + memberDNs, ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : Modification(org.forgerock.opendj.ldap.Modification) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LdapException(org.forgerock.opendj.ldap.LdapException) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute)

Example 5 with ModifyRequest

use of org.forgerock.opendj.ldap.requests.ModifyRequest in project OpenAM by OpenRock.

the class DJLDAPv3Repo method setAttributes.

/**
     * Sets the provided attributes (string or binary) for the given identity. The following steps will be performed
     * prior to modification:
     * <ul>
     *  <li>The password will be encoded in case we are dealing with AD.</li>
     *  <li>Anything related to undefined attributes will be ignored.</li>
     *  <li>If the attribute map contains the default status attribute, then it will be converted to the status value
     *      specified in the configuration.</li>
     *  <li>In case changeOCs is set to <code>true</code>, the method will traverse through all the defined
     *      objectclasses to see if there is any attribute in the attributes map that is defined by that objectclass.
     *      These objectclasses will be collected and will be part of the modificationset with the other changes.</li>
     * </ul>
     * The attributes will be translated to modifications based on the followings:
     * <ul>
     *  <li>If the attribute has no values in the map, it will be considered as an attribute DELETE.</li>
     *  <li>In any other case based on the value of isAdd parameter, it will be either ADD, or REPLACE.</li>
     * </ul>
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param name The name of the identity.
     * @param attributes The attributes that needs to be set for the entry.
     * @param isAdd <code>true</code> if the attributes should be ADDed, <code>false</code> if the attributes should be
     * REPLACEd instead.
     * @param isString Whether the provided attributes are in string or binary format.
     * @param changeOCs Whether the module should adjust the objectclasses for the entry or not.
     * @throws IdRepoException Can be thrown in the following cases:
     * <ul>
     *  <li>the identity cannot be found,</li>
     *  <li>there was a problem while retrieving the current user status from the directory (AD),</li>
     *  <li>there are no modifications to actually perform,</li>
     *  <li>there was an error while retrieving the objectClass attribute,</li>
     *  <li>there was an error while trying to read the directory schema,</li>
     *  <li>there was an error while trying to perform the modifications.</li>
     * </ul>
     */
private void setAttributes(SSOToken token, IdType type, String name, Map attributes, boolean isAdd, boolean isString, boolean changeOCs) throws IdRepoException {
    ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(getDN(type, name));
    attributes = removeUndefinedAttributes(type, attributes);
    if (type.equals(IdType.USER)) {
        Object status = attributes.get(DEFAULT_USER_STATUS_ATTR);
        if (status != null && !attributes.containsKey(userStatusAttr)) {
            String value = null;
            if (status instanceof Set) {
                value = ((Set<String>) status).iterator().next();
            } else if (status instanceof byte[][]) {
                value = new String(((byte[][]) status)[0], Charset.forName("UTF-8"));
            }
            value = helper.getStatus(this, name, !STATUS_INACTIVE.equals(value), userStatusAttr, activeValue, inactiveValue);
            attributes.remove(DEFAULT_USER_STATUS_ATTR);
            if (isString) {
                attributes.put(userStatusAttr, asSet(value));
            } else {
                byte[][] binValue = new byte[1][];
                binValue[0] = value.getBytes(Charset.forName("UTF-8"));
                attributes.put(userStatusAttr, binValue);
            }
        }
    }
    for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) attributes.entrySet()) {
        Object values = entry.getValue();
        String attrName = entry.getKey();
        Attribute attr = new LinkedAttribute(attrName);
        if (AD_UNICODE_PWD_ATTR.equalsIgnoreCase(attrName)) {
            if (values instanceof byte[][]) {
                attr.add(ByteString.valueOfBytes(helper.encodePassword(IdType.USER, (byte[][]) values)));
            } else {
                attr.add(ByteString.valueOfBytes(helper.encodePassword(IdType.USER, (Set) values)));
            }
        } else if (values instanceof byte[][]) {
            for (byte[] bytes : (byte[][]) values) {
                attr.add(ByteString.valueOfBytes(bytes));
            }
        } else if (values instanceof Set) {
            for (String value : (Set<String>) values) {
                attr.add(value);
            }
        }
        if (attr.isEmpty()) {
            modifyRequest.addModification(new Modification(ModificationType.REPLACE, attr));
        } else {
            modifyRequest.addModification(new Modification(isAdd ? ModificationType.ADD : ModificationType.REPLACE, attr));
        }
    }
    if (modifyRequest.getModifications().isEmpty()) {
        if (DEBUG.messageEnabled()) {
            DEBUG.message("setAttributes: there are no modifications to perform");
        }
        throw newIdRepoException(IdRepoErrorCode.ILLEGAL_ARGUMENTS);
    }
    if (type.equals(IdType.USER) && changeOCs) {
        Set<String> missingOCs = new CaseInsensitiveHashSet();
        Map<String, Set<String>> attrs = getAttributes(token, type, name, asSet(OBJECT_CLASS_ATTR));
        Set<String> ocs = attrs.get(OBJECT_CLASS_ATTR);
        //to missingOCs
        if (ocs != null) {
            missingOCs.addAll(getObjectClasses(type));
            missingOCs.removeAll(ocs);
        }
        //if the missingOCs is not empty (i.e. there are objectclasses that are not present in the entry yet)
        if (!missingOCs.isEmpty()) {
            Object obj = attributes.get(OBJECT_CLASS_ATTR);
            //if the API user has also added some of his objectclasses, then let's remove those from missingOCs
            if (obj != null && obj instanceof Set) {
                missingOCs.removeAll((Set<String>) obj);
            }
            //for every single objectclass that needs to be added, let's check if they contain an attribute that we
            //wanted to add to the entry.
            Set<String> newOCs = new HashSet<String>(2);
            Schema dirSchema = getSchema();
            for (String objectClass : missingOCs) {
                try {
                    ObjectClass oc = dirSchema.getObjectClass(objectClass);
                    //we should never add new structural objectclasses, see RFC 4512
                    if (!oc.getObjectClassType().equals(ObjectClassType.STRUCTURAL)) {
                        for (String attrName : (Set<String>) attributes.keySet()) {
                            //before we start to add too many objectclasses here...
                            if (!attrName.equalsIgnoreCase(OBJECT_CLASS_ATTR) && oc.isRequiredOrOptional(dirSchema.getAttributeType(attrName))) {
                                newOCs.add(objectClass);
                                break;
                            }
                        }
                    }
                } catch (UnknownSchemaElementException usee) {
                    if (DEBUG.warningEnabled()) {
                        DEBUG.warning("Unable to find a schema element: " + usee.getMessage());
                    }
                }
            }
            missingOCs = newOCs;
            //it is possible that none of the missing objectclasses are actually covering any new attributes
            if (!missingOCs.isEmpty()) {
                //based on these let's add the extra objectclasses to the modificationset
                modifyRequest.addModification(new Modification(ModificationType.ADD, new LinkedAttribute(OBJECT_CLASS_ATTR, missingOCs)));
            }
        }
    }
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        conn.modify(modifyRequest);
    } catch (LdapException ere) {
        DEBUG.error("An error occured while setting attributes for identity: " + name, ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : Modification(org.forgerock.opendj.ldap.Modification) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CollectionUtils.asSet(org.forgerock.openam.utils.CollectionUtils.asSet) ObjectClass(org.forgerock.opendj.ldap.schema.ObjectClass) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) UnknownSchemaElementException(org.forgerock.opendj.ldap.schema.UnknownSchemaElementException) Schema(org.forgerock.opendj.ldap.schema.Schema) Connection(org.forgerock.opendj.ldap.Connection) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) ByteString(org.forgerock.opendj.ldap.ByteString) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)15 LdapException (org.forgerock.opendj.ldap.LdapException)13 Connection (org.forgerock.opendj.ldap.Connection)10 ByteString (org.forgerock.opendj.ldap.ByteString)8 Modification (org.forgerock.opendj.ldap.Modification)7 Attribute (org.forgerock.opendj.ldap.Attribute)5 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)4 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)4 SMSException (com.sun.identity.sm.SMSException)3 CaseInsensitiveHashMap (com.sun.identity.common.CaseInsensitiveHashMap)2 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 LinkedHashSet (java.util.LinkedHashSet)2 Map (java.util.Map)2 Set (java.util.Set)2 CollectionUtils.asSet (org.forgerock.openam.utils.CollectionUtils.asSet)2 Entry (org.forgerock.opendj.ldap.Entry)2 ResultCode (org.forgerock.opendj.ldap.ResultCode)2 SSOException (com.iplanet.sso.SSOException)1