Search in sources :

Example 6 with Attribute

use of org.apache.directory.api.ldap.model.entry.Attribute in project mxisd by kamax-io.

the class LdapAuthProvider method authenticate.

@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    log.info("Performing auth for {}", mxid);
    try (LdapConnection conn = getConn()) {
        bind(conn);
        String uidType = getAt().getUid().getType();
        String userFilterValue = StringUtils.equals(LdapBackend.UID, uidType) ? mxid.getLocalPart() : mxid.getId();
        if (StringUtils.isBlank(userFilterValue)) {
            log.warn("Username is empty, failing auth");
            return BackendAuthResult.failure();
        }
        String userFilter = "(" + getUidAtt() + "=" + userFilterValue + ")";
        userFilter = buildWithFilter(userFilter, getCfg().getAuth().getFilter());
        Set<String> attributes = new HashSet<>();
        attributes.add(getUidAtt());
        attributes.add(getAt().getName());
        getAt().getThreepid().forEach((k, v) -> attributes.addAll(v));
        String[] attArray = new String[attributes.size()];
        attributes.toArray(attArray);
        log.debug("Base DN: {}", getBaseDn());
        log.debug("Query: {}", userFilter);
        log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
        try (EntryCursor cursor = conn.search(getBaseDn(), userFilter, SearchScope.SUBTREE, attArray)) {
            while (cursor.next()) {
                Entry entry = cursor.get();
                String dn = entry.getDn().getName();
                log.info("Checking possible match, DN: {}", dn);
                if (!getAttribute(entry, getUidAtt()).isPresent()) {
                    continue;
                }
                log.info("Attempting authentication on LDAP for {}", dn);
                try {
                    conn.bind(entry.getDn(), password);
                } catch (LdapException e) {
                    log.info("Unable to bind using {} because {}", entry.getDn().getName(), e.getMessage());
                    return BackendAuthResult.failure();
                }
                Attribute nameAttribute = entry.get(getAt().getName());
                String name = nameAttribute != null ? nameAttribute.get().toString() : null;
                log.info("Authentication successful for {}", entry.getDn().getName());
                log.info("DN {} is a valid match", dn);
                // TODO should we canonicalize the MXID?
                BackendAuthResult result = BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, name);
                log.info("Processing 3PIDs for profile");
                getAt().getThreepid().forEach((k, v) -> {
                    log.info("Processing 3PID type {}", k);
                    v.forEach(attId -> {
                        List<String> values = getAttributes(entry, attId);
                        log.info("\tAttribute {} has {} value(s)", attId, values.size());
                        getAttributes(entry, attId).forEach(tpidValue -> {
                            if (ThreePidMedium.PhoneNumber.is(k)) {
                                tpidValue = getMsisdn(tpidValue).orElse(tpidValue);
                            }
                            result.withThreePid(new ThreePid(k, tpidValue));
                        });
                    });
                });
                log.info("Found {} 3PIDs", result.getProfile().getThreePids().size());
                return result;
            }
        } catch (CursorLdapReferralException e) {
            log.warn("Entity for {} is only available via referral, skipping", mxid);
        }
        log.info("No match were found for {}", mxid);
        return BackendAuthResult.failure();
    } catch (LdapException | IOException | CursorException e) {
        throw new RuntimeException(e);
    }
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) IOException(java.io.IOException) BackendAuthResult(io.kamax.mxisd.auth.provider.BackendAuthResult) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) ThreePid(io.kamax.matrix.ThreePid) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection) HashSet(java.util.HashSet)

Example 7 with Attribute

use of org.apache.directory.api.ldap.model.entry.Attribute in project ldapchai by ldapchai.

the class ApacheLdapProviderImpl method searchImpl.

private Map<String, Map<String, List<String>>> searchImpl(final String baseDN, final SearchHelper searchHelper, final boolean multivalued) throws ChaiUnavailableException, ChaiOperationException {
    try {
        final SearchRequest searchRequest = new SearchRequestImpl();
        searchRequest.setBase(new Dn(baseDN));
        searchRequest.setFilter(searchHelper.getFilter());
        searchRequest.setScope(figureSearchScope(searchHelper.getSearchScope()));
        searchRequest.setSizeLimit(searchHelper.getMaxResults());
        searchRequest.setTimeLimit(searchHelper.getTimeLimit());
        final SearchCursor searchCursor = connection.search(searchRequest);
        final Map<String, Map<String, List<String>>> returnObj = new LinkedHashMap<String, Map<String, List<String>>>();
        while (searchCursor.next()) {
            final Entry entry = searchCursor.getEntry();
            final String dnValue = entry.getDn().getName();
            final Map<String, List<String>> entryMap = new HashMap<String, List<String>>();
            for (Attribute returnAttr : entry) {
                final String attrName = returnAttr.getId();
                final List<String> valueList = new ArrayList<String>();
                if (multivalued) {
                    for (Value value : returnAttr) {
                        valueList.add(value.getString());
                    }
                } else {
                    final String value = returnAttr.iterator().next().getString();
                    valueList.add(value);
                }
                entryMap.put(attrName, Collections.unmodifiableList(valueList));
            }
            returnObj.put(dnValue, Collections.unmodifiableMap(entryMap));
        }
        return Collections.unmodifiableMap(returnObj);
    } catch (CursorException e) {
        throw ChaiOperationException.forErrorMessage(e.getMessage());
    } catch (LdapException e) {
        throw ChaiOperationException.forErrorMessage(e.getMessage());
    }
}
Also used : SearchRequest(org.apache.directory.api.ldap.model.message.SearchRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) ArrayList(java.util.ArrayList) SearchRequestImpl(org.apache.directory.api.ldap.model.message.SearchRequestImpl) SearchCursor(org.apache.directory.api.ldap.model.cursor.SearchCursor) Dn(org.apache.directory.api.ldap.model.name.Dn) LinkedHashMap(java.util.LinkedHashMap) DefaultEntry(org.apache.directory.api.ldap.model.entry.DefaultEntry) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) BinaryValue(org.apache.directory.api.ldap.model.entry.BinaryValue) Value(org.apache.directory.api.ldap.model.entry.Value) StringValue(org.apache.directory.api.ldap.model.entry.StringValue) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 8 with Attribute

use of org.apache.directory.api.ldap.model.entry.Attribute in project ldapchai by ldapchai.

the class ApacheLdapProviderImpl method readStringAttribute.

public String readStringAttribute(final String entryDN, final String attribute) throws ChaiOperationException, ChaiUnavailableException, IllegalStateException {
    activityPreCheck();
    getInputValidator().readStringAttribute(entryDN, attribute);
    try {
        final EntryCursor entries = connection.search(entryDN, ChaiConstant.FILTER_OBJECTCLASS_ANY, org.apache.directory.api.ldap.model.message.SearchScope.OBJECT, attribute);
        final Entry entry = entries.iterator().next();
        final Attribute attr = entry.get(attribute);
        return attr == null ? null : attr.getString();
    } catch (LdapException e) {
        throw ChaiOperationException.forErrorMessage(e.getMessage());
    }
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) DefaultEntry(org.apache.directory.api.ldap.model.entry.DefaultEntry) Entry(org.apache.directory.api.ldap.model.entry.Entry) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 9 with Attribute

use of org.apache.directory.api.ldap.model.entry.Attribute in project jackrabbit-oak by apache.

the class LdapIdentityProvider method applyAttributes.

private void applyAttributes(Map<String, Object> props, Entry entry) throws LdapInvalidAttributeValueException {
    for (Attribute attr : entry.getAttributes()) {
        if (attr.isHumanReadable()) {
            final Object propValue;
            // for multivalue properties, store as collection
            if (attr.size() > 1) {
                List<String> values = new ArrayList();
                for (Value<?> value : attr) {
                    values.add(value.getString());
                }
                propValue = values;
            } else {
                propValue = attr.getString();
            }
            props.put(attr.getId(), propValue);
        }
    }
}
Also used : Attribute(org.apache.directory.api.ldap.model.entry.Attribute) ArrayList(java.util.ArrayList)

Example 10 with Attribute

use of org.apache.directory.api.ldap.model.entry.Attribute in project directory-ldap-api by apache.

the class SearchResultEntryTest method testDecodeSearchResultEntryEmptyAttributeValueWithControls.

/**
 * Test the decoding of a SearchResultEntry with an empty attribute value
 * with controls
 */
@Test
public void testDecodeSearchResultEntryEmptyAttributeValueWithControls() throws NamingException {
    Asn1Decoder ldapDecoder = new Asn1Decoder();
    ByteBuffer stream = ByteBuffer.allocate(0x56);
    stream.put(new byte[] { 0x30, // LDAPMessage ::=SEQUENCE {
    0x54, 0x02, 0x01, // messageID MessageID
    0x01, 0x64, // CHOICE { ..., searchResEntry SearchResultEntry,
    0x32, // objectName LDAPDN,
    0x04, 0x1b, 'o', 'u', '=', 'c', 'o', 'n', 't', 'a', 'c', 't', 's', ',', 'd', 'c', '=', 'i', 'k', 't', 'e', 'k', ',', 'd', 'c', '=', 'c', 'o', 'm', // PartialAttributeList ::= SEQUENCE OF SEQUENCE {
    0x30, 0x13, 0x30, 0x11, // type AttributeDescription,
    0x04, 0x0b, 'o', 'b', 'j', 'e', 'c', 't', 'c', 'l', 'a', 's', 's', // vals SET OF AttributeValue }
    0x31, 0x02, // AttributeValue ::= OCTET STRING
    0x04, 0x00, (byte) 0xA0, // A control
    0x1B, 0x30, 0x19, 0x04, 0x17, 0x32, 0x2E, 0x31, 0x36, 0x2E, 0x38, 0x34, 0x30, 0x2E, 0x31, 0x2E, 0x31, 0x31, 0x33, 0x37, 0x33, 0x30, 0x2E, 0x33, 0x2E, 0x34, 0x2E, 0x32 });
    String decodedPdu = Strings.dumpBytes(stream.array());
    stream.flip();
    // Allocate a BindRequest Container
    LdapMessageContainer<SearchResultEntryDecorator> ldapMessageContainer = new LdapMessageContainer<SearchResultEntryDecorator>(codec);
    try {
        ldapDecoder.decode(stream, ldapMessageContainer);
    } catch (DecoderException de) {
        de.printStackTrace();
        fail(de.getMessage());
    }
    SearchResultEntry searchResultEntry = ldapMessageContainer.getMessage();
    assertEquals(1, searchResultEntry.getMessageId());
    assertEquals("ou=contacts,dc=iktek,dc=com", searchResultEntry.getObjectName().toString());
    Entry entry = searchResultEntry.getEntry();
    assertEquals(1, entry.size());
    for (int i = 0; i < entry.size(); i++) {
        Attribute attribute = entry.get("objectclass");
        assertEquals(Strings.toLowerCaseAscii("objectClass"), Strings.toLowerCaseAscii(attribute.getUpId()));
        assertTrue(attribute.contains(""));
    }
    // Check the Control
    Map<String, Control> controls = searchResultEntry.getControls();
    assertEquals(1, controls.size());
    @SuppressWarnings("unchecked") CodecControl<Control> control = (org.apache.directory.api.ldap.codec.api.CodecControl<Control>) controls.get("2.16.840.1.113730.3.4.2");
    assertEquals("2.16.840.1.113730.3.4.2", control.getOid());
    assertEquals("", Strings.dumpBytes((byte[]) control.getValue()));
    // Check the encoding
    try {
        ByteBuffer bb = encoder.encodeMessage(searchResultEntry);
        // Check the length
        assertEquals(0x56, bb.limit());
        String encodedPdu = Strings.dumpBytes(bb.array());
        assertEquals(encodedPdu, decodedPdu);
    } catch (EncoderException ee) {
        ee.printStackTrace();
        fail(ee.getMessage());
    }
}
Also used : LdapMessageContainer(org.apache.directory.api.ldap.codec.api.LdapMessageContainer) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) SearchResultEntryDecorator(org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator) ByteBuffer(java.nio.ByteBuffer) DecoderException(org.apache.directory.api.asn1.DecoderException) EncoderException(org.apache.directory.api.asn1.EncoderException) SearchResultEntry(org.apache.directory.api.ldap.model.message.SearchResultEntry) Entry(org.apache.directory.api.ldap.model.entry.Entry) Control(org.apache.directory.api.ldap.model.message.Control) CodecControl(org.apache.directory.api.ldap.codec.api.CodecControl) Asn1Decoder(org.apache.directory.api.asn1.ber.Asn1Decoder) CodecControl(org.apache.directory.api.ldap.codec.api.CodecControl) SearchResultEntry(org.apache.directory.api.ldap.model.message.SearchResultEntry) Test(org.junit.Test) AbstractCodecServiceTest(org.apache.directory.api.ldap.codec.osgi.AbstractCodecServiceTest)

Aggregations

Attribute (org.apache.directory.api.ldap.model.entry.Attribute)269 Test (org.junit.Test)180 DefaultAttribute (org.apache.directory.api.ldap.model.entry.DefaultAttribute)168 Entry (org.apache.directory.api.ldap.model.entry.Entry)94 Modification (org.apache.directory.api.ldap.model.entry.Modification)56 Value (org.apache.directory.api.ldap.model.entry.Value)52 DefaultEntry (org.apache.directory.api.ldap.model.entry.DefaultEntry)46 DefaultModification (org.apache.directory.api.ldap.model.entry.DefaultModification)35 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)23 EncoderException (org.apache.directory.api.asn1.EncoderException)20 ByteBuffer (java.nio.ByteBuffer)18 DecoderException (org.apache.directory.api.asn1.DecoderException)18 Asn1Decoder (org.apache.directory.api.asn1.ber.Asn1Decoder)18 LdapMessageContainer (org.apache.directory.api.ldap.codec.api.LdapMessageContainer)18 AbstractCodecServiceTest (org.apache.directory.api.ldap.codec.osgi.AbstractCodecServiceTest)18 SearchResultEntry (org.apache.directory.api.ldap.model.message.SearchResultEntry)18 LdapInvalidAttributeValueException (org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException)16 LdifEntry (org.apache.directory.api.ldap.model.ldif.LdifEntry)16 ModifyRequest (org.apache.directory.api.ldap.model.message.ModifyRequest)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13