Extract groups from ldap.

@param username username to search for
@param property the property to extract the groups from
@return a list of group names from ldap
163957
public List<String> getGroups(String username, String property) {
        final List<String> result = new ArrayList<>();
        ldapTemplate.search(query().where("cn").is(username), new AttributesMapper<String>() {
            public String mapFromAttributes(Attributes attrs) throws NamingException {
                NamingEnumeration<?> ous = attrs.get(property).getAll();
                // since we can generate multiple values here but may only return a single string, we ignore
                // the ldapTemplate#search result and just put the values in our own list, returning an empty string
                // which is effectively ignored
                while (ous.hasMore()) {
                    result.add((String) ous.next());
                }
                return "";
            }
        });
        return result;
    }
1093349
@Override
    public Set<String> getGroups(String user) throws IOException {
        if (cachedGroups.containsKey(user)) {
            return cachedGroups.get(user);
        }
        Set<String> groups = getUnixGroups(user);
        if (!groups.isEmpty())
            cachedGroups.put(user, groups);
        return groups;
    }
1333075
public List<String> getGroups(final DirContext dirContext) throws NamingException {
        LOGGER.debug("Retrieving all groups");
        final List<String> groupDns = new ArrayList<>();
        final SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, GROUPS_FILTER, sc);
        while (hasMoreEnum(ne)) {
            final SearchResult result = ne.next();
            groupDns.add(result.getNameInNamespace());
            LOGGER.debug("Found group: " + result.getNameInNamespace());
        }
        closeQuietly(ne);
        return groupDns;
    }
425927
@Override
    public List<User> findUsers() {
        List<User> userList;
        try {
            userList = createUsers(ldapDao.getDirectChildren(DnFactory.users()));
        } catch (NoSuchNodeException | MissingParentException e) {
            LOGGER.error("LDAP exception", e);
            throw new LdapRuntimeException(e);
        }
        return userList;
    }
916537
@Override
    public Node getGroup(final String cn) {
        try {
            String query = "(&(objectClass=" + groupObjectClass + ")(" + groupIdentifyer + "=" + cn + "))";
            SearchResult searchResult;
            Attributes attributes;
            SearchControls controls = new SearchControls();
            controls.setReturningAttributes(new String[]{LdapKeys.ASTERISK, LdapKeys.MODIFY_TIMESTAMP, LdapKeys.MODIFIERS_NAME, LdapKeys.ENTRY_UUID});
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = ctx.search("", query, controls);
            queryCount++;
            if (results.hasMore()) {
                LdapGroup group = new LdapGroup(cn, this);
            	searchResult = results.next();
                group.setDn(searchResult.getNameInNamespace());
                attributes = searchResult.getAttributes();
                group = fillAttributesInGroup((LdapGroup) group, attributes);
                return group;
            }
        } catch (NamingException ex) {
            handleNamingException(instanceName + ":" + cn, ex);
        }
       return new LdapGroup();
    }
1277423
@Nullable
    protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException {
        LdapContext ctx = null;
        try {
            // Binds using the system username and password.
            ctx = ldapContextFactory.getSystemLdapContext();

            final SearchControls ctrl = new SearchControls();
            ctrl.setCountLimit(1);
            ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
            ctrl.setTimeLimit(searchTimeoutMillis);

            final String filter =
                    searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter)
                                                               .replaceAll(username)
                                         : username;
            final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl);
            try {
                if (!result.hasMore()) {
                    return null;
                }
                return result.next().getNameInNamespace();
            } finally {
                result.close();
            }
        } finally {
            LdapUtils.closeContext(ctx);
        }
    }
197786
public static List<String> getPropertyValues( AbstractBlockHolder holder, String propertyName ) {

		List<String> result = new ArrayList<> ();
		for( BlockProperty p : holder.findPropertiesBlockByName( propertyName )) {
			result.addAll( Utils.splitNicely( p.getValue(), ParsingConstants.PROPERTY_SEPARATOR ));
		}

		return result;
	}
381788
@SuppressWarnings("unchecked")
    public ConfigProperty getConfigProperty(final String groupName, final String propertyName) {
        final Query query = pm.newQuery(ConfigProperty.class, "groupName == :groupName && propertyName == :propertyName");
        final List<ConfigProperty> result = (List<ConfigProperty>) query.execute(groupName, propertyName);
        return Collections.isEmpty(result) ? null : result.get(0);
    }
527525
def del_from_groups(self, username, groups):
        """"""
        # it follows the same logic than add_to_groups
        # but with MOD_DELETE
        ldap_client = self._bind()
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = tmp[0]
        attrs = tmp[1]
        attrs['dn'] = dn
        self._normalize_group_attrs(attrs)
        dn = self._byte_p2(tmp[0])
        for group in groups:
            group = self._byte_p2(group)
            for attr in self.group_attrs:
                content = self._byte_p2(self.group_attrs[attr] % attrs)
                ldif = [(ldap.MOD_DELETE, attr, self._byte_p3(content))]
                try:
                    ldap_client.modify_s(group, ldif)
                except ldap.NO_SUCH_ATTRIBUTE as e:
                    self._logger(
                        severity=logging.INFO,
                        msg="%(backend)s: user '%(user)s'"
                        " wasn't member of group '%(group)s'"
                        " (attribute '%(attr)s')" % {
                            'user': username,
                            'group': self._uni(group),
                            'attr': attr,
                            'backend': self.backend_name
                            }
                    )
                except Exception as e:
                    ldap_client.unbind_s()
                    self._exception_handler(e)
        ldap_client.unbind_s()
1155903
private List<LDAPGroup> getGroups(final DirContext ldap, final String dn) throws NamingException
	{
		// Get the DN of all grouos the user is directly/indirectly a member of
		final NamingEnumeration<SearchResult> answer;
		{
			SearchControls search = new SearchControls();

			search.setSearchScope(SearchControls.SUBTREE_SCOPE);
			search.setReturningAttributes(new String[]{"dn"});

			final String searchFilter = String.format(this.ldapGroupFilter, dn);

			answer = ldap.search(ldapSearchBase, searchFilter, search);
		}

		List<LDAPGroup> groups = new ArrayList<>();

		while (answer.hasMoreElements())
		{
			SearchResult sr = answer.next();

			final String groupDN = sr.getNameInNamespace();

			groups.add(dnToLdapGroup(groupDN));
		}

		return groups;
	}
1140202
function ldap_get_userlist($filter='*') {
        $fresult = array();

        $ldapconnection = $this->ldap_connect();

        if ($filter == '*') {
           $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
        }

        $contexts = explode(';', $this->config->contexts);
        if (!empty($this->config->create_context)) {
            array_push($contexts, $this->config->create_context);
        }

        $ldap_cookie = '';
        $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version, $ldapconnection);
        foreach ($contexts as $context) {
            $context = trim($context);
            if (empty($context)) {
                continue;
            }

            do {
                if ($ldap_pagedresults) {
                    ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
                }
                if ($this->config->search_sub) {
                    // Use ldap_search to find first user from subtree.
                    $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
                } else {
                    // Search only in this context.
                    $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
                }
                if(!$ldap_result) {
                    continue;
                }
                if ($ldap_pagedresults) {
                    ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
                }
                $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
                // Add found users to list.
                for ($i = 0; $i < count($users); $i++) {
                    $extuser = core_text::convert($users[$i][$this->config->user_attribute][0],
                                                $this->config->ldapencoding, 'utf-8');
                    array_push($fresult, $extuser);
                }
                unset($ldap_result); // Free mem.
            } while ($ldap_pagedresults && !empty($ldap_cookie));
        }

        // If paged results were used, make sure the current connection is completely closed
        $this->ldap_close($ldap_pagedresults);
        return $fresult;
    }
1236319
public List<BlockProperty> findPropertiesBlockByName( String propertyName ) {

		List<BlockProperty> result = new ArrayList<> ();
		for( AbstractBlock region : this.innerBlocks ) {
			if( region.getInstructionType() == PROPERTY
					&& propertyName.equals(((BlockProperty) region).getName())) {

				result.add((BlockProperty) region);
			}
		}

		return result;
	}
1180317
public static aaauser_aaagroup_binding[] get(nitro_service service, String username) throws Exception{
		aaauser_aaagroup_binding obj = new aaauser_aaagroup_binding();
		obj.set_username(username);
		aaauser_aaagroup_binding response[] = (aaauser_aaagroup_binding[]) obj.get_resources(service);
		return response;
	}
630536
def get_ldap_user_membership(self, user_dn):
        """"""
        #Escape parenthesis in DN
        membership_filter = self.conf_LDAP_SYNC_GROUP_MEMBERSHIP_FILTER.replace('{distinguishedName}', user_dn.replace('(', "\(").replace(')', "\)"))
        try:
            uri, groups = self.ldap_search(membership_filter, self.conf_LDAP_SYNC_GROUP_ATTRIBUTES.keys(), False, membership_filter)
        except Exception as e:
            logger.error("Error reading membership: Filter %s, Keys %s" % (membership_filter, str(self.conf_LDAP_SYNC_GROUP_ATTRIBUTES.keys())))
            return None
        #logger.debug("AD Membership: Retrieved %d groups for user '%s'" % (len(groups), user_dn))
        return (uri, groups)
682493
def get_groups_by_token(cls, username, token, request):
        
        try:
            user = cls.get_item(username=username)
        except Exception as ex:
            log.error(str(ex))
            forget(request)
            return
        else:
            if user and user.api_key.token == token:
                return ['g:%s' % g for g in user.groups]
9631
private List<String> getGroups(String dn) throws WIMException {
        List<String> grpList = new ArrayList<String>();
        String filter = iLdapConfigMgr.getGroupMemberFilter(dn);
        String[] searchBases = iLdapConfigMgr.getGroupSearchBases();
        for (int i = 0; i < searchBases.length; i++) {
            String searchBase = searchBases[i];
            NamingEnumeration<SearchResult> nenu = iLdapConn.search(searchBase, filter, SearchControls.SUBTREE_SCOPE,
                                                                    LDAP_ATTR_OBJECTCLASS_ARRAY);
            while (nenu.hasMoreElements()) {
                SearchResult thisEntry = nenu.nextElement();
                if (thisEntry == null) {
                    continue;
                }
                String entryName = thisEntry.getName();
                if (entryName == null || entryName.trim().length() == 0) {
                    continue;
                }
                grpList.add(LdapHelper.prepareDN(entryName, searchBase));
            }
        }
        return grpList;
    }
1279321
public Collection<String> getValues(String property) {
        Multimap<Optional<String>, String> values = properties.get(property);
        if (values == null) {
            return Collections.emptyList();
        }

        return values.values();
    }