Example usage for javax.naming.directory Attributes get

List of usage examples for javax.naming.directory Attributes get

Introduction

In this page you can find the example usage for javax.naming.directory Attributes get.

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * This method will perform multiple queries into Active Directory
 * in order to resolve what groups a user is a member of.  The
 * logic will identify nested groups and add them to the table.
 * <p>//from w  w w.j a va2  s .c  om
 * The LDAP_ACCOUNT_NAME field must be populated in the user bag
 * prior to invoking this method.  Any site specific fields can be
 * assigned to the user bag will be included in the attribute query.
 * </p>
 * <p>
 * Any site specific fields can be assigned to the group bag will
 * be included in the attribute query.
 * </p>
 *
 * @param aUserBag Active Directory user attributes.
 * @param aGroupBag Active Directory group attributes.
 *
 * @return Table of groups that the user is a member of.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    DataBag groupBag;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    // First, we will populate our user bag so that we can obtain the distinguished name.

    loadUserByAccountName(aUserBag);

    // Now we will use the DN to find all of the groups the user is a member of.

    String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME);
    if (StringUtils.isEmpty(distinguishedName))
        distinguishedName = getPropertyValue("user_searchbasedn", null);

    // Next, we will initialize our group membership table.

    DataTable memberTable = new DataTable(aUserBag);
    memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME)));

    // The next logic section will query AD for all of the groups the user is a member
    // of.  Because we are following tokenGroups, we will gain access to nested groups.

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);

    SearchControls userSearchControls = new SearchControls();
    userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE);

    StringBuffer groupsSearchFilter = null;
    String ldapAttrNames[] = { "tokenGroups" };
    userSearchControls.setReturningAttributes(ldapAttrNames);

    try {
        NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)",
                userSearchControls);
        if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) {
            groupsSearchFilter = new StringBuffer();
            groupsSearchFilter.append("(|");

            SearchResult userSearchResult = (SearchResult) userSearchResponse.next();
            Attributes userResultAttributes = userSearchResult.getAttributes();
            if (userResultAttributes != null) {
                try {
                    for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes
                            .getAll(); searchResultAttributesAll.hasMore();) {
                        Attribute attr = (Attribute) searchResultAttributesAll.next();
                        for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration
                                .hasMore();) {
                            objectSid = (byte[]) namingEnumeration.next();
                            groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")");
                        }
                        groupsSearchFilter.append(")");
                    }
                } catch (NamingException e) {
                    String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage());
                    appLogger.error(msgStr, e);
                    throw new NSException(msgStr);
                }
            }
            userSearchResponse.close();

            // Finally, we will query each group in the search filter and add it to the table.

            SearchControls groupSearchControls = new SearchControls();
            groupSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            int field = 0;
            int attrCount = aGroupBag.count();
            String[] groupsReturnedAtts = new String[attrCount];
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                groupsReturnedAtts[field++] = fieldName;
            }
            groupSearchControls.setReturningAttributes(groupsReturnedAtts);
            NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN,
                    groupsSearchFilter.toString(), groupSearchControls);
            while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) {
                SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next();
                Attributes groupResultAttributes = groupSearchResult.getAttributes();
                if (groupResultAttributes != null) {
                    groupBag = new DataBag(aGroupBag);
                    for (DataField complexField : groupBag.getFields()) {
                        fieldName = complexField.getName();
                        responseAttribute = groupResultAttributes.get(fieldName);
                        if (responseAttribute != null) {
                            if (fieldName.equals(LDAP_OBJECT_SID)) {
                                objectSid = (byte[]) responseAttribute.get();
                                fieldValue = objectSidToString2(objectSid);
                            } else
                                fieldValue = (String) responseAttribute.get();
                            if (StringUtils.isNotEmpty(fieldValue))
                                complexField.setValue(fieldValue);
                        }
                    }
                    memberTable.addRow(groupBag);
                }
            }
            if (groupSearchResponse != null)
                groupSearchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return memberTable;
}

From source file:org.nuxeo.wizard.RouterServlet.java

public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Context ctx = Context.instance(req);
    ParamCollector collector = ctx.getCollector();

    String refreshParam = req.getParameter("refresh");
    String directoryType = collector.getConfigurationParam("nuxeo.directory.type");

    if ("true".equals(refreshParam)) {
        currentPage.dispatchToJSP(req, resp);
        return;/*  www .  ja  va2  s  . c  o m*/
    }

    if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam)
            || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) {
        try {
            if ("checkNetwork".equals(refreshParam)) {
                bindLdapConnection(collector, false);
                ctx.trackInfo("nuxeo.ldap.url", "info.host.found");
            } else if ("checkAuth".equals(refreshParam)) {
                bindLdapConnection(collector, true);
                ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success");
            } else {
                DirContext dirContext = new InitialDirContext(getContextEnv(collector, true));
                String searchScope;
                String searchBaseDn;
                String searchClass;
                String searchFilter;
                if ("checkUserLdapParam".equals(refreshParam)) {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope");
                    searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter");
                } else {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter");
                    searchClass = "";
                }

                SearchControls scts = new SearchControls();
                if ("onelevel".equals(searchScope)) {
                    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
                } else {
                    scts.setSearchScope(SearchControls.SUBTREE_SCOPE);
                }
                String filter = String.format("(&(%s)(objectClass=%s))",
                        searchFilter.isEmpty() ? "objectClass=*" : searchFilter,
                        searchClass.isEmpty() ? "*" : searchClass);
                NamingEnumeration<SearchResult> results;
                try {
                    results = dirContext.search(searchBaseDn, filter, scts);
                    if (!results.hasMore()) {
                        ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult");
                    } else {
                        SearchResult result = results.next();
                        if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) {
                            // try not to display the root of the search
                            // base DN
                            result = results.next();
                        }
                        ctx.trackInfo("dn", result.getNameInNamespace());
                        Attributes attributes = result.getAttributes();
                        NamingEnumeration<String> ids = attributes.getIDs();
                        String id;
                        StringBuilder sb;
                        while (ids.hasMore()) {
                            id = ids.next();
                            NamingEnumeration<?> values = attributes.get(id).getAll();
                            sb = new StringBuilder();
                            while (values.hasMore()) {
                                sb.append(values.next()).append(" , ");
                            }
                            ctx.trackInfo(id, sb.substring(0, sb.length() - 3));
                        }
                    }
                } catch (NameNotFoundException e) {
                    ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn");
                    log.warn(e);
                }
                dirContext.close();
            }
        } catch (AuthenticationException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.auth.failed");
            log.warn(e);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.url", "error.host.not.found");
            log.warn(e);
        }
    }

    // Form submit
    if (!"default".equals(directoryType) && refreshParam.isEmpty()) {
        // first check bind to LDAP server
        try {
            bindLdapConnection(collector, true);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed");
            log.warn(e);
        }

        // then check mandatory fields
        if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required");
        }
        String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage");
        if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) {
            if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required");
            }
        }
        if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) {
            if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required");
            }
            if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required");
            }
        }
    }

    if (ctx.hasErrors() || ctx.hasInfos()) {
        currentPage.dispatchToJSP(req, resp);
    } else {
        currentPage.next().dispatchToJSP(req, resp, true);
    }
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

/***************************************************************************
 * Collect all the values from the table (Arguments), using this create the
 * Attributes, this will create the Attributes for the User
 * defined TestCase for Add Test//from   w  ww. j a v  a2  s .co  m
 *
 * @return The Attributes
 **************************************************************************/
private Attributes getUserAttributes() {
    Attributes attrs = new BasicAttributes(true);
    Attribute attr;

    for (JMeterProperty jMeterProperty : getArguments()) {
        Argument item = (Argument) jMeterProperty.getObjectValue();
        attr = attrs.get(item.getName());
        if (attr == null) {
            attr = getBasicAttribute(item.getName(), item.getValue());
        } else {
            attr.add(item.getValue());
        }
        attrs.put(attr);
    }
    return attrs;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * attempts to get the users credentials from the users context
 * <p/>//from w  ww .  jav  a 2s .  c  o  m
 * NOTE: this is not an user authenticated operation
 *
 * @param username
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
    String ldapCredential = null;

    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    try {
        Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
        NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments,
                ctls);

        debug("Found user?: " + results.hasMoreElements());

        if (!results.hasMoreElements()) {
            throw new LoginException("User not found.");
        }

        SearchResult result = findUser(username);

        Attributes attributes = result.getAttributes();

        setDemographicAttributes(attributes);
        Attribute attribute = attributes.get(_userPasswordAttribute);
        if (attribute != null) {
            try {
                byte[] value = (byte[]) attribute.get();

                ldapCredential = new String(value);
            } catch (NamingException e) {
                LOG.info("no password available under attribute: " + _userPasswordAttribute);
            }
        }
    } catch (NamingException e) {
        throw new LoginException("Root context binding failure.");
    }

    debug("user cred is present: " + (ldapCredential != null));

    return ldapCredential;
}

From source file:com.wfp.utils.LDAPUtils.java

@SuppressWarnings("unchecked")
public static Map<String, Map<String, String>> parseDataAsMap(NamingEnumeration searchResults,
        String optionalKey, String uniqueKey, String[] attrArray) {
    Logger.debug("Formatting the data as MAP", LDAPUtils.class);

    Map<String, Map<String, String>> resultMap = null;

    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }//ww w  . jav a 2  s  . c  o m

    // Loop through the search results
    while (searchResults.hasMoreElements()) {
        SearchResult sr = null;
        try {
            sr = (SearchResult) searchResults.next();
        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return null;
        }

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            if (resultMap == null) {
                resultMap = new HashMap<String, Map<String, String>>();
            }
            try {
                Map<String, String> resultAttrMap = new HashMap();
                for (String attr : attrArray) {
                    if (resultAttrMap.get(attr) == null) {
                        attrs.get(attr);
                        resultAttrMap.put(attr, "");
                    }
                }
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) {
                        String attrValue = (String) e.next();
                        //if it is external id
                        if (attr.getID().equals(EXTERNAL_ID)) {
                            if (attrValue.contains(COMPASS_ID)) {
                                resultAttrMap.put(attr.getID(), attrValue.replace(COMPASS_ID, ""));
                                break;
                            } else
                                resultAttrMap.put(attr.getID(), "inValidFormat");
                        }
                        resultAttrMap.put(attr.getID(), attrValue);
                    }
                }
                if (optionalKey != null && !StringUtils.isNull(resultAttrMap.get(optionalKey))) {
                    resultMap.put(resultAttrMap.get(optionalKey), resultAttrMap);
                } else {
                    resultAttrMap.put("compasId", "");
                    resultMap.put(resultAttrMap.get(uniqueKey), resultAttrMap);
                }

            } catch (NamingException e) {
                Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e);
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }

    return resultMap;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected Organisation convertSearchResultToOrganization(final SearchResult sr)
        throws ExecutionException, NameNotFoundException {
    if (sr == null) {
        throw new ExecutionException("SearchResult sr == NULL", new NullPointerException());
    }//from  w w w.  j ava  2 s. co m
    Organisation vOrganisation = null;
    try {
        Attributes attributes = sr.getAttributes();

        Attribute attr;
        String vStr;
        String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null
                ? String.valueOf(attr.get())
                : null);
        String vName = sr.getName();
        String vNameInNamespace = sr.getNameInNamespace();
        // --- EntryDN
        String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null
                ? String.valueOf(attr.get())
                : "");

        int idx;
        // -- Parent node detections:
        String vParent = null;
        //vParent = sr.getName();
        //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'");
        //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'");
        // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de'
        // -- getName() = 'o=99900711,o=00008125,o=00050350'

        //sr.getName(): 'o=00000116', 
        //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', 
        //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de'            
        vParent = sr.getNameInNamespace();
        if ((idx = vParent.indexOf(",ou=")) >= 0) {
            vParent = vParent.substring(0, idx);
        }
        vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", "");
        // -- 99900711,00008125,00050350'
        String[] vParents = vParent.split(",");

        if (vParents.length >= 2) {
            vParent = vParents[1];
        } else {
            vParent = null;
        }

        LOG.log(Level.INFO,
                "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent
                        + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace
                        + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'");
        /*
         * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName,
         * vDescription, vParent);
         */
        if ((vEntryDN != null) && (!vEntryDN.isEmpty())) {
            vOrganisation = new Organisation(vEntryDN,
                    (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                            ? String.valueOf(attr.get())
                            : null);
            // Public-ID: (s.o.)
            // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) :
            // "");
            // Parent (s.o.)
            vOrganisation.setOrgParent(vParent);

            // Kurzbeschreibung der Einrichtung
            vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- Rechtsform
            try {
                vOrganisation.setBusinessCategory(
                        (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null
                                ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get()))
                                : null);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            // -- Sub-Sectors:
            if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) {
                ConstEnumOrgSubSector vSubSector;
                NamingEnumeration<?> allSubSectors = attr.getAll();
                while (allSubSectors.hasMore()) {
                    try {
                        vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next());
                        vOrganisation.addSubSectors(vSubSector);
                    } catch (IllegalArgumentException ex) {
                        LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage());
                    }
                }
            }

            // -- Funding Agency
            vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // Name der Einrichtung
            vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            // E-Mail
            vOrganisation.setEmail(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get())
                            : null);
            // Telefonnummer
            vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);
            // -- FAX
            vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- PLZ
            vOrganisation.getAddress()
                    .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- City/Ortsname [l, localityName]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("l")) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            }

            // -- HouseIdentifier
            vOrganisation.getAddress()
                    .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null
                            ? String.valueOf(attr.get())
                            : "");
            // -- Strasse
            vOrganisation.getAddress()
                    .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Bundesland [stateOrProvinceName, st]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("st")) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            }

            // -- Land [countryName, c]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) {
                vOrganisation.getAddress().setCountryName(String.valueOf(attr.get()));
            }
            // -- AddressSuplement
            vOrganisation.getAddress()
                    .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Geokoordinaten
            try {
                vOrganisation.getAddress()
                        .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage());
            }
            try {
                vOrganisation.getAddress()
                        .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage());
            }
            vOrganisation.getAddress().setLocationDisplayName(
                    (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null
                            ? String.valueOf(attr.get())
                            : null);

            vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null
                    ? String.valueOf(attr.get())
                    : null);

            vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null
                    ? String.valueOf(attr.get())
                    : null);

            if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) {
                NamingEnumeration<?> allURLs = attr.getAll();
                while (allURLs.hasMore()) {
                    vOrganisation.addURLs((String) allURLs.next());
                }
            }

            vOrganisation.setLogo(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get())
                            : null);

            // -- org-Status:
            //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String
            //  .valueOf(attr.get()) : "");
            try {
                vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null
                        ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get()))
                        : ConstEnumOrgStatus.pending);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            try { // createTimestamp-Error: For input string: "20120620142810Z"
                  // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z
                  // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setCreated(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage());
            }

            vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null
                    ? String.valueOf(attr.get())
                    : "");
            try { // modifyTimestamp-Error: For input string: "20120620142810Z"
                  // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setModified(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage());
            }

            if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null
                    && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) {
                vOrganisation.setProperties(serializer.deserialize((String) attr.get()));
            }

        } else {
            throw new NameNotFoundException();
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    }
    return vOrganisation;
}

From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java

@Override
public String authenticate(String username, String password)
        throws BadCredentialsException, AuthenticationSystemException {

    // Mapper for user data if user is successfully authenticated
    AuthenticatedLdapEntryContextMapper<User> mapper = new AuthenticatedLdapEntryContextMapper<User>() {
        @Override/*  w ww.j a  v a  2s.  c o m*/
        public User mapWithContext(DirContext dirContext, LdapEntryIdentification ldapEntryIdentification) {
            try {
                // User entry - extract attributes
                DirContextOperations dirContextOperations = (DirContextOperations) dirContext
                        .lookup(ldapEntryIdentification.getRelativeName());
                Attributes attributes = dirContextOperations.getAttributes();
                String emailAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_EMAIL);
                String firstNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_FIRST_NAME);
                String lastNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_LAST_NAME);
                String siteIdAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_SITE_ID);
                String groupNameAttribName = studioConfiguration
                        .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_GROUP_NAME);
                Attribute emailAttrib = attributes.get(emailAttribName);
                Attribute firstNameAttrib = attributes.get(firstNameAttribName);
                Attribute lastNameAttrib = attributes.get(lastNameAttribName);
                Attribute siteIdAttrib = attributes.get(siteIdAttribName);
                Attribute groupNameAttrib = attributes.get(groupNameAttribName);

                User user = new User();
                user.setGroups(new ArrayList<>());
                user.setActive(1);
                user.setUsername(username);

                if (emailAttrib != null && emailAttrib.get() != null) {
                    user.setEmail(emailAttrib.get().toString());
                } else {
                    logger.error("No LDAP attribute " + emailAttribName + " found for username " + username
                            + ". User will not be imported into DB.");
                    return null;
                }
                if (firstNameAttrib != null && firstNameAttrib.get() != null) {
                    user.setFirstname(firstNameAttrib.get().toString());
                } else {
                    logger.warn("No LDAP attribute " + firstNameAttribName + " found for username " + username);
                }
                if (lastNameAttrib != null && lastNameAttrib.get() != null) {
                    user.setLastname(lastNameAttrib.get().toString());
                } else {
                    logger.warn("No LDAP attribute " + lastNameAttribName + " found for username " + username);
                }

                if (siteIdAttrib != null && siteIdAttrib.get() != null) {
                    Map<String, Object> params = new HashMap<>();
                    NamingEnumeration siteIdValues = siteIdAttrib.getAll();
                    while (siteIdValues.hasMore()) {
                        Object siteIdObj = siteIdValues.next();
                        if (siteIdObj != null) {
                            String[] siteIdAndGroupName = extractSiteIdAndGroupNameFromAttributeValue(
                                    siteIdObj.toString());

                            if (siteIdAndGroupName.length > 0) {
                                params.put("siteId", siteIdAndGroupName[0]);

                                SiteFeed siteFeed = siteFeedMapper.getSite(params);
                                if (siteFeed != null) {
                                    // Add groups, first the one that's specific to the site
                                    if (siteIdAndGroupName.length > 1) {
                                        addGroupToUser(user, siteIdAndGroupName[1], siteFeed);
                                    }

                                    extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib,
                                            siteFeed);
                                } else {
                                    logger.warn("Not site found for ID " + siteIdAndGroupName[0]);
                                }
                            }
                        }
                    }
                } else {
                    String defaultSiteId = studioConfiguration.getProperty(SECURITY_LDAP_DEFAULT_SITE_ID);

                    logger.debug("Assigning user " + username + " to default site " + defaultSiteId);

                    Map<String, Object> params = new HashMap<>();
                    params.put("siteId", defaultSiteId);

                    SiteFeed siteFeed = siteFeedMapper.getSite(params);
                    if (siteFeed != null) {
                        extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed);
                    } else {
                        logger.warn("No site found for default site ID " + defaultSiteId);
                    }
                }

                return user;
            } catch (NamingException e) {
                logger.error("Error getting details from LDAP for username " + username, e);

                return null;
            }
        }
    };

    // Create ldap query to authenticate user
    LdapQuery ldapQuery = query().where(studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_USERNAME))
            .is(username);
    User user;
    try {
        user = ldapTemplate.authenticate(ldapQuery, password, mapper);
    } catch (EmptyResultDataAccessException e) {
        logger.info("User " + username
                + " not found with external security provider. Trying to authenticate against studio database");
        // When user not found try to authenticate against studio database
        return super.authenticate(username, password);
    } catch (CommunicationException e) {
        logger.info("Failed to connect with external security provider. "
                + "Trying to authenticate against studio database");
        // When user not found try to authenticate against studio database
        return super.authenticate(username, password);
    } catch (AuthenticationException e) {
        logger.error("Authentication failed with the LDAP system", e);

        throw new BadCredentialsException();
    } catch (Exception e) {
        logger.error("Authentication failed with the LDAP system", e);

        throw new AuthenticationSystemException("Authentication failed with the LDAP system", e);
    }

    if (user != null) {
        // When user authenticated against LDAP, upsert user data into studio database
        if (super.userExists(username)) {
            try {
                boolean success = updateUserInternal(user.getUsername(), user.getFirstname(),
                        user.getLastname(), user.getEmail());
                if (success) {
                    ActivityService.ActivityType activityType = ActivityService.ActivityType.UPDATED;
                    Map<String, String> extraInfo = new HashMap<>();
                    extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER);
                    activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(),
                            activityType, ActivityService.ActivitySource.API, extraInfo);
                }
            } catch (UserNotFoundException e) {
                logger.error(
                        "Error updating user " + username + " with data from external authentication provider",
                        e);

                throw new AuthenticationSystemException(
                        "Error updating user " + username + " with data from external authentication provider",
                        e);
            }
        } else {
            try {
                boolean success = createUser(user.getUsername(), password, user.getFirstname(),
                        user.getLastname(), user.getEmail(), true);
                if (success) {
                    ActivityService.ActivityType activityType = ActivityService.ActivityType.CREATED;
                    Map<String, String> extraInfo = new HashMap<>();
                    extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER);
                    activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(),
                            activityType, ActivityService.ActivitySource.API, extraInfo);
                }
            } catch (UserAlreadyExistsException e) {
                logger.error("Error adding user " + username + " from external authentication provider", e);

                throw new AuthenticationSystemException(
                        "Error adding user " + username + " from external authentication provider", e);
            }
        }
        for (Group group : user.getGroups()) {
            try {
                upsertUserGroup(group.getSite(), group.getName(), user.getUsername());
            } catch (GroupAlreadyExistsException | SiteNotFoundException | UserNotFoundException
                    | UserAlreadyExistsException | GroupNotFoundException e) {
                logger.error("Failed to upsert user groups data from LDAP", e);
            }
        }

        String token = createToken(user);
        storeSessionTicket(token);
        storeSessionUsername(username);

        return token;
    } else {
        logger.error("Failed to retrieve LDAP user details");

        throw new AuthenticationSystemException("Failed to retrieve LDAP user details");
    }
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(//  ww  w. j a  v  a 2s .  c om
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();

        Attributes attributes = result.getAttributes();

        if (attributes == null) {
            continue;
        }

        Attribute roleAttribute = attributes.get(_roleNameAttribute);

        if (roleAttribute == null) {
            continue;
        }

        NamingEnumeration roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

protected DocumentModel ldapResultToDocumentModel(SearchResult result, String entryId, boolean fetchReferences)
        throws DirectoryException, NamingException {
    Attributes attributes = result.getAttributes();
    String passwordFieldId = getPasswordField();
    Map<String, Object> fieldMap = new HashMap<String, Object>();

    Attribute attribute = attributes.get(idAttribute);
    // NXP-2461: check that id field is filled + NXP-2730: make sure that
    // entry id is the one returned from LDAP
    if (attribute != null) {
        Object entry = attribute.get();
        if (entry != null) {
            entryId = entry.toString();/*  ww  w .  j  a  v a 2  s  . c  o  m*/
        }
    }
    // NXP-7136 handle id case
    entryId = changeEntryIdCase(entryId, idCase);

    if (entryId == null) {
        // don't bother
        return null;
    }
    for (String fieldName : schemaFieldMap.keySet()) {
        List<Reference> references = directory.getReferences(fieldName);
        if (references != null && references.size() > 0) {
            if (fetchReferences) {
                Map<String, List<String>> referencedIdsMap = new HashMap<>();
                for (Reference reference : references) {
                    // reference resolution
                    List<String> referencedIds;
                    if (reference instanceof LDAPReference) {
                        // optim: use the current LDAPSession directly to
                        // provide the LDAP reference with the needed backend entries
                        LDAPReference ldapReference = (LDAPReference) reference;
                        referencedIds = ldapReference.getLdapTargetIds(attributes);
                    } else if (reference instanceof LDAPTreeReference) {
                        // TODO: optimize using the current LDAPSession
                        // directly to provide the LDAP reference with the
                        // needed backend entries (needs to implement getLdapTargetIds)
                        LDAPTreeReference ldapReference = (LDAPTreeReference) reference;
                        referencedIds = ldapReference.getTargetIdsForSource(entryId);
                    } else {
                        referencedIds = reference.getTargetIdsForSource(entryId);
                    }
                    referencedIds = new ArrayList<>(referencedIds);
                    Collections.sort(referencedIds);
                    if (referencedIdsMap.containsKey(fieldName)) {
                        referencedIdsMap.get(fieldName).addAll(referencedIds);
                    } else {
                        referencedIdsMap.put(fieldName, referencedIds);
                    }
                }
                fieldMap.put(fieldName, referencedIdsMap.get(fieldName));
            }
        } else {
            // manage directly stored fields
            String attributeId = getDirectory().getFieldMapper().getBackendField(fieldName);
            if (attributeId.equals(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY)) {
                // this is the special DN readonly attribute
                try {
                    fieldMap.put(fieldName, result.getNameInNamespace());
                } catch (UnsupportedOperationException e) {
                    // ignore ApacheDS partial implementation when running
                    // in embedded mode
                }
            } else {
                // this is a regular attribute
                attribute = attributes.get(attributeId);
                if (fieldName.equals(passwordFieldId)) {
                    // do not try to fetch the password attribute
                    continue;
                } else {
                    fieldMap.put(fieldName, getFieldValue(attribute, fieldName, entryId, fetchReferences));
                }
            }
        }
    }
    // check if the idAttribute was returned from the search. If not
    // set it anyway, maybe changing its case if it's a String instance
    String fieldId = getDirectory().getFieldMapper().getDirectoryField(idAttribute);
    Object obj = fieldMap.get(fieldId);
    if (obj == null) {
        fieldMap.put(fieldId,
                changeEntryIdCase(entryId, getDirectory().getDescriptor().getMissingIdFieldCase()));
    } else if (obj instanceof String) {
        fieldMap.put(fieldId, changeEntryIdCase((String) obj, idCase));
    }
    return fieldMapToDocumentModel(fieldMap);
}