Search in sources :

Example 6 with RepoSearchResults

use of com.sun.identity.idm.RepoSearchResults in project OpenAM by OpenRock.

the class FilesRepo method getMembers.

/*
     * (non-Javadoc)
     *
     * @see com.sun.identity.idm.IdRepo#getMembers(com.iplanet.sso.SSOToken,
     *      com.sun.identity.idm.IdType, java.lang.String,
     *      com.sun.identity.idm.IdType)
     */
public Set getMembers(SSOToken token, IdType type, String name, IdType membersType) throws IdRepoException, SSOException {
    if (debug.messageEnabled()) {
        debug.message("FilesRepo.getMembers called" + type + ": " + name + ": " + membersType);
    }
    if (initializationException != null) {
        debug.error("FilesRepo.getMembers: throwing initialization exception");
        throw (initializationException);
    }
    // Memers can be returned for roles and groups
    if (!type.equals(IdType.ROLE) && !type.equals(IdType.GROUP)) {
        debug.message("FilesRepo.getMembers supported for roles and groups");
        throw new IdRepoException(IdRepoBundle.getString(IdRepoErrorCode.MEMBERSHIP_TO_USERS_AND_AGENTS_NOT_ALLOWED), IdRepoErrorCode.MEMBERSHIP_TO_USERS_AND_AGENTS_NOT_ALLOWED);
    }
    // Set to maintain the members
    Set results = new HashSet();
    // Process group members
    if (type.equals(IdType.GROUP)) {
        // Read the group files and return the membership attribute
        File file = constructFile(directory, type, name);
        Map attrs = decodeAttributes(readFile(file), encryptAttributes);
        Set members = (Set) attrs.get(groupMembersAttribute);
        // matches
        if (members != null && !members.isEmpty()) {
            String mtype = membersType.getName();
            int mtypeLen = mtype.length();
            for (Iterator items = members.iterator(); items.hasNext(); ) {
                String sname = (String) items.next();
                if (sname.startsWith(mtype)) {
                    results.add(sname.substring(mtypeLen));
                }
            }
        }
    } else if (type.equals(IdType.ROLE)) {
        // Get the list of all "membersType" and check if they belong
        // to the group
        Set returnAttrs = new HashSet();
        returnAttrs.add(roleMembershipAttribute);
        RepoSearchResults allUsers = search(token, membersType, "*", 0, 0, returnAttrs, false, IdRepo.OR_MOD, null, false);
        Map userAttributes = null;
        if ((allUsers != null) && ((userAttributes = allUsers.getResultAttributes()) != null)) {
            for (Iterator i = userAttributes.keySet().iterator(); i.hasNext(); ) {
                String sname = (String) i.next();
                Map attrs = (Map) userAttributes.get(sname);
                // Check if user belongs to the role
                Set roles = (Set) attrs.get(roleMembershipAttribute);
                if (roles != null && roles.contains(name)) {
                    results.add(sname);
                }
            }
        }
    } else {
        // throw unsupported operation exception
        Object[] args = { NAME, IdOperation.READ.getName(), type.getName() };
        throw new IdRepoUnsupportedOpException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.PLUGIN_OPERATION_NOT_SUPPORTED, args);
    }
    return (results);
}
Also used : IdRepoUnsupportedOpException(com.sun.identity.idm.IdRepoUnsupportedOpException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) Set(java.util.Set) IdRepoException(com.sun.identity.idm.IdRepoException) Iterator(java.util.Iterator) RepoSearchResults(com.sun.identity.idm.RepoSearchResults) File(java.io.File) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Map(java.util.Map) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet)

Example 7 with RepoSearchResults

use of com.sun.identity.idm.RepoSearchResults in project OpenAM by OpenRock.

the class AgentsRepo method getFullyQualifiedName.

public String getFullyQualifiedName(SSOToken token, IdType type, String name) throws IdRepoException, SSOException {
    CrestQuery crestQuery = new CrestQuery(name);
    RepoSearchResults results = search(token, type, crestQuery, 0, 0, null, true, 0, null, false);
    Set dns = results.getSearchResults();
    if (dns.size() != 1) {
        String[] args = { name };
        throw (new IdRepoException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.UNABLE_FIND_ENTRY, args));
    }
    return ("sms://AgentsRepo/" + dns.iterator().next().toString());
}
Also used : CrestQuery(org.forgerock.openam.utils.CrestQuery) NotificationSet(com.iplanet.services.comm.share.NotificationSet) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) IdRepoException(com.sun.identity.idm.IdRepoException) RepoSearchResults(com.sun.identity.idm.RepoSearchResults)

Example 8 with RepoSearchResults

use of com.sun.identity.idm.RepoSearchResults in project OpenAM by OpenRock.

the class DatabaseRepo method search.

/*
     *  Search for specific type of identities.
     *
     * @see com.sun.identity.idm.IdRepo#search(com.iplanet.sso.SSOToken,
     *      com.sun.identity.idm.IdType, java.lang.String, int, int,
     *      java.util.Set, boolean, int, java.util.Map, boolean)
     *
     * @param token
     *     Single signon token of identity performing the task.  (Not Using)
     * @param type
     *     Identity type of this object.
     * @param pattern
     *     pattern to search for. The pattern can either be an id, for example
     *     a user's id. Or pattern can be just a * which means all. Or pattern
     *     can be a string that contains * such as searching for any ids that
     *     match *ea* like 'sean' , or it could be pattern with just one * in
     *     front or back
     *     if pattern is NULL or empty or "*" then they all mean pattern = "*"
     *     which is wildcard char. Note, wildcard searches can be modified as
     *     they are affected by other params like avPairs whxi add other
     *     conditions to the seacrhes.
     * @param maxTime
     *     maximum wait time for search. (Not Using)
     * @param maxResults
     *     maximum records to return.
     * @param returnAttrs
     *     Set of attribute names to return. If this is null, then all
     *     atrributes will be fetched and returned. If empty then no attributes
     *     will be fetched and returned, and just the set of ids will be
     *     returned, and for each id it will have an empty set for values.
     * @param returnAllAttrs
     *     flag specifies if  should return all attributes for each id
     *     that matches search. This overrides the setting of returnAttrs, so if
     *     this flag is true then all attributes will be fecthed and returned
     *     no matter what the value of returnAttrs parameter.
     * @param filterOp
     *     filter condition. For example IdRepo.OR_MOD or IdRepo.AND_MOD and
     *     then the WHERE clause of SQL search will use this operand between
     *     the avPairs comparisons
     * @param avPairs
     *     additional search conditions. For example, these would be added to
     *     the search query WHERE clause, like WHERE last_name = 'Jones' and
     *     you could use the attribute-value in the map for column last_name
     *     and value 'Jones'.
     * @param recursive
     *     boolean to indicate recursive search? (Not Using)
     *
     * @return RepoSearchResults
     * @throws IdRepoException If there are repository related error conditions.
     * @throws SSOException If identity's single sign on token is invalid.
     */
private RepoSearchResults search(SSOToken token, IdType type, String pattern, int maxTime, int maxResults, Set returnAttrs, boolean returnAllAttrs, int filterOp, Map avPairs, boolean recursive) throws IdRepoException, SSOException {
    if (initializationException != null) {
        debug.error("DatabaseRepo.search: throwing" + " initialization exception");
        throw (initializationException);
    }
    if (debug.messageEnabled()) {
        debug.message("DatabaseRepo:search called with :" + " token=" + token + " IdType=" + type + " pattern=" + pattern + " maxTime=" + maxTime + " maxResults=" + maxResults + " returnAttrs=" + returnAttrs + " filter= " + filterOp + " avPairs= " + avPairs + " recursive=" + recursive);
    }
    //throw exception if this type user not allowed to do this
    isValidType(type, "search");
    if (maxResults < 1) {
        maxResults = defaultSearchMaxResults;
        if (debug.messageEnabled()) {
            debug.message("DatabaseRepo:search changing value of maxResults to default, so now maxResults=" + maxResults);
        }
    }
    //?? SHOULD THE RETURNED LIST BE ORDERED ????
    //a set of Maps where each map is a user and their attributes
    Map<String, Map<String, Set<String>>> users = new HashMap<>();
    //determine the set of attributes to fetch from the database
    Set<String> attributesToFetch = null;
    if (returnAttrs == null) {
        //to fetch all user attributes, need to pass in all attr names
        if (type.equals(IdType.USER)) {
            attributesToFetch = userAtttributesAllowed;
        } else if (type.equals(IdType.GROUP)) {
            //RFE: treat groupAttrsAllowed in same way as userAttributesAllowed
            Set<String> groupAttrsAllowed = new HashSet<String>();
            groupAttrsAllowed.add(membershipIdAttributeName);
            attributesToFetch = groupAttrsAllowed;
        }
    } else if (returnAttrs.isEmpty()) {
        //fetch just userIDs
        attributesToFetch = new HashSet<String>();
        if (type.equals(IdType.USER)) {
            attributesToFetch.add(userIDAttributeName);
        } else if (type.equals(IdType.GROUP)) {
            attributesToFetch.add(membershipIdAttributeName);
        }
    } else {
        attributesToFetch = returnAttrs;
    }
    //IdRepo.NO_MOD default is NONE
    String filterOpString = "NONE";
    if (filterOp == IdRepo.OR_MOD) {
        filterOpString = "OR";
    } else if (filterOp == IdRepo.AND_MOD) {
        filterOpString = "AND";
    }
    if ((pattern == null || pattern.length() == 0 || pattern.equals("*")) && (avPairs == null || avPairs.isEmpty())) {
        // get all users
        if (type.equals(IdType.USER)) {
            users = dao.search(userIDAttributeName, maxResults, "", attributesToFetch, filterOpString, avPairs);
        } else if (type.equals(IdType.GROUP)) {
            users = dao.searchForGroups(membershipIdAttributeName, maxResults, "", attributesToFetch, filterOpString, avPairs);
        }
    } else {
        // get users that match with the pattern
        // not sure if we need to differentiate between case where
        // avPairs==null or empty ??? vs when avPairs has attrs and values??
        // AFAIK the searches on a pattern all include something in avPairs
        // and those attrs/values are used to search for pattern matches
        // substitute % for * for sql LIKE query
        String searchPattern = pattern.replaceAll("\\*", "%");
        //avPairs with values having wildcard chars replaced
        Map<String, Set<String>> avPairsChanged = new HashMap<>();
        // need to replace % for * in all avPairs too
        if (avPairs != null && !avPairs.isEmpty()) {
            Iterator KeysIt = avPairs.keySet().iterator();
            while (KeysIt.hasNext()) {
                String key = (String) KeysIt.next();
                if (key != null) {
                    Set<String> values = (Set<String>) avPairs.get(key);
                    Set<String> changedValues = new HashSet<String>();
                    if (values != null && !values.isEmpty()) {
                        Iterator<String> valSetIt = values.iterator();
                        // modify each value to replace any wildcard chars
                        while (valSetIt.hasNext()) {
                            String attrValue = valSetIt.next();
                            if (attrValue != null && attrValue.contains("*")) {
                                attrValue = attrValue.replaceAll("\\*", "%");
                            }
                            changedValues.add(attrValue);
                        }
                    }
                    // now that Set values has each value with new wildcard
                    // replace it in the changed avPairsMap
                    avPairsChanged.put(key, changedValues);
                }
            }
        }
        if (type.equals(IdType.USER)) {
            users = dao.search(userIDAttributeName, maxResults, searchPattern, attributesToFetch, filterOpString, avPairsChanged);
        } else if (type.equals(IdType.GROUP)) {
            users = dao.searchForGroups(membershipIdAttributeName, maxResults, searchPattern, attributesToFetch, filterOpString, avPairsChanged);
        }
    }
    if (users == null) {
        return new RepoSearchResults(Collections.EMPTY_SET, RepoSearchResults.SUCCESS, Collections.EMPTY_MAP, type);
    }
    if (users.isEmpty()) {
        return new RepoSearchResults(Collections.EMPTY_SET, RepoSearchResults.SUCCESS, Collections.EMPTY_MAP, type);
    }
    Set allUserIds = users.keySet();
    if (returnAttrs != null && returnAttrs.isEmpty()) {
        // I believe that is this case, we should only return the userids
        // and each Map is empty???
        // Or should it be the user id and for
        // each user id the Set of just useridattrname=value ????
        // for now, just return userids and empty map
        // throw away any fetched attrs for each userid, if any
        users = new HashMap<String, Map<String, Set<String>>>();
        // now set each id's value set to an empty set
        for (Iterator<String> usersIt = allUserIds.iterator(); usersIt.hasNext(); ) {
            users.put(usersIt.next(), Collections.EMPTY_MAP);
        }
    }
    if (debug.messageEnabled()) {
        debug.message("DatabaseRepo.search: returning users= " + users);
    }
    return (new RepoSearchResults(allUserIds, RepoSearchResults.SUCCESS, users, type));
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Iterator(java.util.Iterator) RepoSearchResults(com.sun.identity.idm.RepoSearchResults) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 9 with RepoSearchResults

use of com.sun.identity.idm.RepoSearchResults in project OpenAM by OpenRock.

the class DJLDAPv3Repo method search.

/**
     * Performs a search in the directory based on the provided parameters.
     * Using the pattern and avPairs parameters an example search filter would look something like:
     * <code>(&(|(attr1=value1)(attr2=value2))(searchAttr=pattern)(objectclassfilter))</code>.
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param crestQuery Either a string, coming from something like the CREST endpoint _queryId or a fully
     *                        fledged query filter, coming from a CREST endpoint's _queryFilter
     * @param maxTime The time limit for this search (in seconds). When maxTime &lt; 1, the default time limit will
     * be used.
     * @param maxResults The number of maximum results we should receive for this search. When maxResults &lt; 1 the
     * default sizelimit will be used.
     * @param returnAttrs The attributes that should be returned from the "search hits".
     * @param returnAllAttrs <code>true</code> if all user attribute should be returned.
     * @param filterOp When avPairs is provided, this logical operation will be used between them. Use
     * {@link IdRepo#AND_MOD} or {@link IdRepo#OR_MOD}.
     * @param avPairs Attribute-value pairs based on the search should be performed.
     * @param recursive Deprecated setting, not used.
     * @return The search results based on the provided parameters.
     * @throws IdRepoException Shouldn't be thrown as the returned RepoSearchResults will contain the error code.
     */
@Override
public RepoSearchResults search(SSOToken token, IdType type, CrestQuery crestQuery, int maxTime, int maxResults, Set<String> returnAttrs, boolean returnAllAttrs, int filterOp, Map<String, Set<String>> avPairs, boolean recursive) throws IdRepoException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("search invoked with type: " + type + " crestQuery: " + crestQuery + " avPairs: " + avPairs + " maxTime: " + maxTime + " maxResults: " + maxResults + " returnAttrs: " + returnAttrs + " returnAllAttrs: " + returnAllAttrs + " filterOp: " + filterOp + " recursive: " + recursive);
    }
    DN baseDN = getBaseDN(type);
    // Recursive is a deprecated setting on IdSearchControl, hence we should use the searchscope defined in the
    // datastore configuration.
    SearchScope scope = defaultScope;
    String searchAttr = getSearchAttribute(type);
    String[] attrs;
    Filter first;
    if (crestQuery.hasQueryId()) {
        first = Filter.valueOf(searchAttr + "=" + crestQuery.getQueryId());
    } else {
        first = crestQuery.getQueryFilter().accept(new LdapFromJsonQueryFilterVisitor(), null);
    }
    Filter filter = Filter.and(first, getObjectClassFilter(type));
    Filter tempFilter = constructFilter(filterOp, avPairs);
    if (tempFilter != null) {
        filter = Filter.and(tempFilter, filter);
    }
    if (returnAllAttrs || (returnAttrs != null && returnAttrs.contains("*"))) {
        Set<String> predefinedAttrs = getDefinedAttributes(type);
        attrs = predefinedAttrs.toArray(new String[predefinedAttrs.size()]);
        returnAllAttrs = true;
    } else if (returnAttrs != null && !returnAttrs.isEmpty()) {
        returnAttrs.add(searchAttr);
        attrs = returnAttrs.toArray(new String[returnAttrs.size()]);
    } else {
        attrs = new String[] { searchAttr };
    }
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, scope, filter, attrs);
    searchRequest.setSizeLimit(maxResults < 1 ? defaultSizeLimit : maxResults);
    searchRequest.setTimeLimit(maxTime < 1 ? defaultTimeLimit : maxTime);
    Connection conn = null;
    Set<String> names = new HashSet<String>();
    Map<String, Map<String, Set<String>>> entries = new HashMap<String, Map<String, Set<String>>>();
    int errorCode = RepoSearchResults.SUCCESS;
    try {
        conn = connectionFactory.getConnection();
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            Map<String, Set<String>> attributes = new HashMap<String, Set<String>>();
            if (reader.isEntry()) {
                SearchResultEntry entry = reader.readEntry();
                String name = entry.parseAttribute(searchAttr).asString();
                names.add(name);
                if (returnAllAttrs) {
                    for (Attribute attribute : entry.getAllAttributes()) {
                        LDAPUtils.addAttributeToMapAsString(attribute, attributes);
                    }
                    entries.put(name, attributes);
                } else if (returnAttrs != null && !returnAttrs.isEmpty()) {
                    for (String attr : returnAttrs) {
                        Attribute attribute = entry.getAttribute(attr);
                        if (attribute != null) {
                            LDAPUtils.addAttributeToMapAsString(attribute, attributes);
                        }
                    }
                    entries.put(name, attributes);
                } else {
                //there is no attribute to return, don't populate the entries map
                }
            } else {
                //ignore search result references
                reader.readReference();
            }
        }
    } catch (LdapException ere) {
        ResultCode resultCode = ere.getResult().getResultCode();
        if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
            return new RepoSearchResults(new HashSet<String>(0), RepoSearchResults.SUCCESS, Collections.EMPTY_MAP, type);
        } else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED) || resultCode.equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            errorCode = RepoSearchResults.TIME_LIMIT_EXCEEDED;
        } else if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
            errorCode = RepoSearchResults.SIZE_LIMIT_EXCEEDED;
        } else {
            DEBUG.error("Unexpected error occurred during search", ere);
            errorCode = resultCode.intValue();
        }
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return new RepoSearchResults(names, errorCode, entries, type);
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) 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) LdapFromJsonQueryFilterVisitor(org.forgerock.openam.ldap.LdapFromJsonQueryFilterVisitor) 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) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) SearchScope(org.forgerock.opendj.ldap.SearchScope) RepoSearchResults(com.sun.identity.idm.RepoSearchResults) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 10 with RepoSearchResults

use of com.sun.identity.idm.RepoSearchResults in project OpenAM by OpenRock.

the class ADMailBasedRepoTest method canAuthenticateWithMailAttribute.

@Test(description = "OPENAM-3428")
public void canAuthenticateWithMailAttribute() throws Exception {
    assertThat(idrepo.authenticate(getCredentials(DEMO_MAIL, "changeit"))).isTrue();
    //simulate profile lookup
    CrestQuery crestQuery = new CrestQuery(DEMO_MAIL);
    RepoSearchResults results = idrepo.search(null, IdType.USER, crestQuery, 0, 0, null, true, IdRepo.OR_MOD, null, true);
    assertThat(results.getErrorCode()).isEqualTo(ResultCode.SUCCESS.intValue());
    assertThat(results.getType()).isEqualTo(IdType.USER);
    assertThat(results.getSearchResults()).isNotEmpty().hasSize(1).containsOnly(DEMO_MAIL);
}
Also used : CrestQuery(org.forgerock.openam.utils.CrestQuery) RepoSearchResults(com.sun.identity.idm.RepoSearchResults) Test(org.testng.annotations.Test)

Aggregations

RepoSearchResults (com.sun.identity.idm.RepoSearchResults)25 HashSet (java.util.HashSet)19 Set (java.util.Set)18 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)14 CaseInsensitiveHashMap (com.sun.identity.common.CaseInsensitiveHashMap)13 HashMap (java.util.HashMap)13 Map (java.util.Map)12 IdRepoException (com.sun.identity.idm.IdRepoException)11 Iterator (java.util.Iterator)11 CrestQuery (org.forgerock.openam.utils.CrestQuery)11 Test (org.testng.annotations.Test)7 OrderedSet (com.sun.identity.shared.datastruct.OrderedSet)4 NotificationSet (com.iplanet.services.comm.share.NotificationSet)3 SSOException (com.iplanet.sso.SSOException)3 IdRepo (com.sun.identity.idm.IdRepo)3 IdRepoUnsupportedOpException (com.sun.identity.idm.IdRepoUnsupportedOpException)3 AMHashMap (com.iplanet.am.sdk.AMHashMap)2 SSOToken (com.iplanet.sso.SSOToken)2 AMIdentity (com.sun.identity.idm.AMIdentity)2 IdSearchResults (com.sun.identity.idm.IdSearchResults)2