Search in sources :

Example 1 with LinkedAttribute

use of org.forgerock.opendj.ldap.LinkedAttribute 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 2 with LinkedAttribute

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

the class DJLDAPv3Repo method getAttributes.

/**
     * Returns all the requested attributes either in binary or in String format. Only the attributes defined in the
     * configuration will be returned for this given identity. In case the default "inetUserStatus" attribute has been
     * requested, it will be converted to the actual status attribute during query, and while processing it will be
     * mapped back to standard "inetUserStatus" values as well (rather than returning the configuration/directory
     * specific values). If there is an attempt to read a realm identity type's objectclass attribute, this method will
     * return an empty map right away (legacy handling). If the dn attribute has been requested, and it's also defined
     * in the configuration, then the attributemap will also contain the dn in the result.
     *
     * @param <T>
     * @param type The type of the identity.
     * @param name The name of the identity.
     * @param attrNames The names of the requested attributes or <code>null</code> to retrieve all the attributes.
     * @param function A function that can extract String or byte array values from an LDAP attribute.
     * @return The requested attributes in string or binary format.
     * @throws IdRepoException If there is an error while retrieving the identity attributes.
     */
private <T> Map<String, T> getAttributes(IdType type, String name, Set<String> attrNames, Function<Attribute, T, IdRepoException> function) throws IdRepoException {
    Set<String> attrs = attrNames == null ? new CaseInsensitiveHashSet(0) : new CaseInsensitiveHashSet(attrNames);
    if (type.equals(IdType.REALM)) {
        if (attrs.contains(OBJECT_CLASS_ATTR)) {
            return new HashMap(0);
        }
    }
    Map<String, T> result = new HashMap<String, T>();
    String dn = getDN(type, name);
    if (type.equals(IdType.USER)) {
        if (attrs.contains(DEFAULT_USER_STATUS_ATTR)) {
            attrs.add(userStatusAttr);
        }
    }
    Connection conn = null;
    Set<String> definedAttributes = getDefinedAttributes(type);
    if (attrs.isEmpty() || attrs.contains("*")) {
        attrs.clear();
        if (definedAttributes.isEmpty()) {
            attrs.add("*");
        } else {
            attrs.addAll(definedAttributes);
        }
    } else {
        if (!definedAttributes.isEmpty()) {
            attrs.retainAll(definedAttributes);
        }
        if (attrs.isEmpty()) {
            //there were only non-defined attributes requested, so we shouldn't return anything here.
            return new HashMap<String, T>(0);
        }
    }
    try {
        conn = connectionFactory.getConnection();
        SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, attrs.toArray(new String[attrs.size()])));
        for (Attribute attribute : entry.getAllAttributes()) {
            String attrName = attribute.getAttributeDescriptionAsString();
            if (!definedAttributes.isEmpty() && !definedAttributes.contains(attrName)) {
                continue;
            }
            result.put(attribute.getAttributeDescriptionAsString(), function.apply(attribute));
            if (attrName.equalsIgnoreCase(userStatusAttr) && attrs.contains(DEFAULT_USER_STATUS_ATTR)) {
                String converted = helper.convertToInetUserStatus(attribute.firstValueAsString(), inactiveValue);
                result.put(DEFAULT_USER_STATUS_ATTR, function.apply(new LinkedAttribute(DEFAULT_USER_STATUS_ATTR, converted)));
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while getting user attributes", ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    if (attrs.contains(DN_ATTR)) {
        result.put(DN_ATTR, function.apply(new LinkedAttribute(DN_ATTR, dn)));
    }
    if (DEBUG.messageEnabled()) {
        DEBUG.message("getAttributes returning attrMap: " + IdRepoUtils.getAttrMapWithoutPasswordAttrs(result, null));
    }
    return result;
}
Also used : CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute)

Example 3 with LinkedAttribute

use of org.forgerock.opendj.ldap.LinkedAttribute 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 4 with LinkedAttribute

use of org.forgerock.opendj.ldap.LinkedAttribute 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)

Example 5 with LinkedAttribute

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

the class SMSLdapObject method copyModItemsToModifyRequest.

// Method to covert JNDI ModificationItems to LDAPModificationSet
private static ModifyRequest copyModItemsToModifyRequest(DN dn, ModificationItem[] mods) throws SMSException {
    ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(dn);
    try {
        for (ModificationItem mod : mods) {
            Attribute attribute = mod.getAttribute();
            LinkedAttribute attr = new LinkedAttribute(attribute.getID());
            for (NamingEnumeration ne = attribute.getAll(); ne.hasMore(); ) {
                attr.add(ne.next());
            }
            switch(mod.getModificationOp()) {
                case DirContext.ADD_ATTRIBUTE:
                    modifyRequest.addModification(new Modification(ModificationType.ADD, attr));
                    break;
                case DirContext.REPLACE_ATTRIBUTE:
                    modifyRequest.addModification(new Modification(ModificationType.REPLACE, attr));
                    break;
                case DirContext.REMOVE_ATTRIBUTE:
                    modifyRequest.addModification(new Modification(ModificationType.DELETE, attr));
                    break;
            }
        }
    } catch (NamingException nne) {
        throw new SMSException(nne, "sms-cannot-copy-fromModItemToModSet");
    }
    return modifyRequest;
}
Also used : ModificationItem(javax.naming.directory.ModificationItem) Modification(org.forgerock.opendj.ldap.Modification) Attribute(javax.naming.directory.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) SMSException(com.sun.identity.sm.SMSException) NamingEnumeration(javax.naming.NamingEnumeration) NamingException(javax.naming.NamingException) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute)

Aggregations

LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)10 Connection (org.forgerock.opendj.ldap.Connection)8 HashMap (java.util.HashMap)6 Attribute (org.forgerock.opendj.ldap.Attribute)5 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)5 ClaimsParameters (ddf.security.claims.ClaimsParameters)4 HashSet (java.util.HashSet)4 UserPrincipal (org.apache.karaf.jaas.boot.principal.UserPrincipal)4 ByteString (org.forgerock.opendj.ldap.ByteString)4 ConnectionFactory (org.forgerock.opendj.ldap.ConnectionFactory)4 LdapException (org.forgerock.opendj.ldap.LdapException)4 Modification (org.forgerock.opendj.ldap.Modification)4 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)4 BindResult (org.forgerock.opendj.ldap.responses.BindResult)4 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)4 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 Claim (ddf.security.claims.Claim)3 ClaimsCollection (ddf.security.claims.ClaimsCollection)3 ClaimsParametersImpl (ddf.security.claims.impl.ClaimsParametersImpl)3 SubjectUtils (ddf.security.service.impl.SubjectUtils)3