Returns the search scope used in LDAP search
492645
public int get_searchScope() {
        int searchScope = SearchControls.OBJECT_SCOPE;
        String scopeBuf = get_scope();
        if (scopeBuf != null) {
            if (scopeBuf.compareToIgnoreCase("base") == 0) {
                searchScope = SearchControls.OBJECT_SCOPE;
            } else if (scopeBuf.compareToIgnoreCase("one") == 0) {
                searchScope = SearchControls.ONELEVEL_SCOPE;
            } else if (scopeBuf.compareToIgnoreCase("sub") == 0) {
                searchScope = SearchControls.SUBTREE_SCOPE;
            }
        }
        return searchScope;
    }
182025
def search(self, searchstring):
        
        ret = {}
        for user in self.users:
            match = False
            for attr in self.search_attrs:
                if attr not in self.users[user]:
                    pass
                elif re.search(searchstring + '.*', self.users[user][attr]):
                    match = True
            if match:
                ret[user] = self.users[user]
        return ret
816592
def get_all_knoreq_user_objects(self, include_machine = False):
		
		logger.debug('Polling AD for all user objects, machine accounts included: %s'% include_machine)
		if include_machine == True:
			ldap_filter = r'(userAccountControl:1.2.840.113556.1.4.803:=4194304)'
		else:
			ldap_filter = r'(&(userAccountControl:1.2.840.113556.1.4.803:=4194304)(!(sAMAccountName = *$)))'

		attributes = MSADUser.ATTRS
		for entry in self.pagedsearch(ldap_filter, attributes):
			# TODO: return ldapuser object
			yield MSADUser.from_ldap(entry, self._ldapinfo)
		logger.debug('Finished polling for entries!')
475357
def search_with_additional_terms(self, term_dict, escape=True):
        
        term_strings = [self.filterstr]

        for name, value in term_dict.items():
            if escape:
                value = self.ldap.filter.escape_filter_chars(value)
            term_strings.append("({}={})".format(name, value))

        filterstr = "(&{})".format("".join(term_strings))

        return self.__class__(
            self.base_dn, self.scope, filterstr, attrlist=self.attrlist
        )
601300
def scoped_search(query, default_sort_by, default_sort_order, options = {})
      params[:sort_by] ||= default_sort_by
      params[:sort_order] ||= default_sort_order

      resource = options[:resource_class] || resource_class
      includes = options.fetch(:includes, [])
      group = options.fetch(:group, nil)
      params[:full_result] = true if options[:csv]
      blank_query = resource.none

      if params[:order]
        (params[:sort_by], params[:sort_order]) = params[:order].split(' ')
      else
        params[:order] = "#{params[:sort_by]} #{params[:sort_order]}"
      end

      total = scoped_search_total(query, group)

      query = query.select(:id) if query.respond_to?(:select)
      query = resource.search_for(*search_options).where("#{resource.table_name}.id" => query)

      query = self.final_custom_index_relation(query) if self.respond_to?(:final_custom_index_relation)

      query = query.select(group).group(group) if group
      sub_total = total.zero? ? 0 : scoped_search_total(query, group)

      if options[:custom_sort]
        query = options[:custom_sort].call(query)
      end
      query = query.order("#{query.table_name}.id DESC") unless group #secondary order to ensure sort is deterministic
      query = query.includes(includes) if includes.length > 0

      if ::Foreman::Cast.to_bool(params[:full_result])
        params[:per_page] = total
      else
        query = query.paginate(paginate_options)
      end
      page = params[:page] || 1
      per_page = params[:per_page] || Setting[:entries_per_page]
      query = (total.zero? || sub_total.zero?) ? blank_query : query

      options[:csv] ? query : scoped_search_results(query, sub_total, total, page, per_page)
    rescue ScopedSearch::QueryNotSupported, ActiveRecord::StatementInvalid => error
      message = error.message
      if error.class == ActiveRecord::StatementInvalid
        Rails.logger.error("Invalid search: #{error.message}")
        message = _('Your search query was invalid. Please revise it and try again. The full error has been sent to the application logs.')
      end

      scoped_search_results(blank_query, 0, 0, page, per_page, message)
    end
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);
        }
    }
950720
function ldapQuery($scope, $params) {

    $this->connectAndBindIfNotAlready();

    switch ($scope) {
      case LDAP_SCOPE_SUBTREE:
        $result = @ldap_search($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'],
          $params['sizelimit'], $params['timelimit'], $params['deref']);
        if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
          // false positive error thrown.  do not return result limit error when $sizelimit specified
        }
        elseif ($this->hasError()) {
          watchdog('ldap_server', 'ldap_search() function error. LDAP Error: %message, ldap_search() parameters: %query',
            array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']),
            WATCHDOG_ERROR);
        }
        break;

      case LDAP_SCOPE_BASE:
        $result = @ldap_read($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'],
          $params['sizelimit'], $params['timelimit'], $params['deref']);
        if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
          // false positive error thrown.  do not result limit error when $sizelimit specified
        }
        elseif ($this->hasError()) {
          watchdog('ldap_server', 'ldap_read() function error.  LDAP Error: %message, ldap_read() parameters: %query',
            array('%message' => $this->errorMsg('ldap'), '%query' => @$params['query_display']),
            WATCHDOG_ERROR);
        }
        break;

      case LDAP_SCOPE_ONELEVEL:
        $result = @ldap_list($this->connection, $params['base_dn'], $params['filter'], $params['attributes'], $params['attrsonly'],
          $params['sizelimit'], $params['timelimit'], $params['deref']);
        if ($params['sizelimit'] && $this->ldapErrorNumber() == LDAP_SIZELIMIT_EXCEEDED) {
          // false positive error thrown.  do not result limit error when $sizelimit specified
        }
        elseif ($this->hasError()) {
          watchdog('ldap_server', 'ldap_list() function error. LDAP Error: %message, ldap_list() parameters: %query',
            array('%message' => $this->errorMsg('ldap'), '%query' => $params['query_display']),
            WATCHDOG_ERROR);
        }
        break;
    }
    return $result;
  }
13548
def user_groups(self, ldap_user, group_search):
        
        groups = []

        try:
            user_uid = ldap_user.attrs["uid"][0]

            if "gidNumber" in ldap_user.attrs:
                user_gid = ldap_user.attrs["gidNumber"][0]
                filterstr = "(|(gidNumber={})(memberUid={}))".format(
                    self.ldap.filter.escape_filter_chars(user_gid),
                    self.ldap.filter.escape_filter_chars(user_uid),
                )
            else:
                filterstr = "(memberUid={})".format(
                    self.ldap.filter.escape_filter_chars(user_uid)
                )

            search = group_search.search_with_additional_term_string(filterstr)
            groups = search.execute(ldap_user.connection)
        except (KeyError, IndexError):
            pass

        return groups
595926
function query() {
    ldap_servers_module_load_include('php', 'ldap_servers', 'LdapServer.class');
    $ldap_server = new LdapServer($this->sid);
    $ldap_server->connect();
    $ldap_server->bind();
    $results = array();

    $count = 0;

    foreach ($this->baseDn as $base_dn) {
      $result = $ldap_server->search($base_dn, $this->filter, $this->attributes, 0, $this->sizelimit, $this->timelimit, $this->deref, $this->scope);
      if ($result !== FALSE && $result['count'] > 0) {
        $count = $count + $result['count'];
        $results = array_merge($results, $result);
      }
    }
    $results['count'] = $count;

    return $results;
  }
671912
@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);

            LOG.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.debug("no password available under attribute: " + _userPasswordAttribute);
                }
            }
        } catch (NamingException e) {
            throw new LoginException("Root context binding failure.");
        }

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

        return ldapCredential;
    }
215265
@When("^I search in LDAP using the filter '(.+?)' and the baseDn '(.+?)'$")
    public void searchLDAP(String filter, String baseDn) throws Exception {
        this.commonspec.setPreviousLdapResults(commonspec.getLdapUtils().search(new SearchRequest(baseDn, filter)));
    }
1075423
def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True,
                      active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs):
        
        return self._results('domain-search', '/v2/domain-search', query=delimited(query, ' '),
                            exclude_query=delimited(exclude_query, ' '),
                            max_length=max_length, min_length=min_length, has_hyphen=has_hyphen, has_number=has_number,
                            active_only=active_only, deleted_only=deleted_only, anchor_left=anchor_left,
                            anchor_right=anchor_right, page=page, items_path=('results', ), **kwargs)
159676
@Deprecated
	public String getScope() {
        StringBuilder scopeTextStringBuilder = new StringBuilder();
        for (DomainAlwaysInScopeMatcher domainInScope : domainsAlwaysInScope) {
            if (domainInScope.isRegex()) {
                scopeTextStringBuilder.append("\\Q").append(domainInScope.getValue()).append("\\E");
            } else {
                scopeTextStringBuilder.append(domainInScope.getValue());
            }
            scopeTextStringBuilder.append('|');
        }

        if (scopeTextStringBuilder.length() != 0) {
            scopeTextStringBuilder.append("(");
            scopeTextStringBuilder.replace(scopeTextStringBuilder.length() - 1, scopeTextStringBuilder.length() - 1, ")$");
        }

        return scopeTextStringBuilder.toString();
    }
337585
def get_directorship_heads(self, val):
        

        __ldap_group_ou__ = "cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu"

        res = self.__con__.search_s(
                __ldap_group_ou__,
                ldap.SCOPE_SUBTREE,
                "(cn=eboard-%s)" % val,
                ['member'])

        ret = []
        for member in res[0][1]['member']:
            try:
                ret.append(member.decode('utf-8'))
            except UnicodeDecodeError:
                ret.append(member)
            except KeyError:
                continue

        return [CSHMember(self,
                dn.split('=')[1].split(',')[0],
                True)
                for dn in ret]
231067
private void getDACL() throws NamingException {
        final SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        controls.setReturningAttributes(new String[] { "name", "nTSecurityDescriptor" });

        if (ldapContext == null) {
            LOG.warn("getDACL, cannot search for DACL with null ldapContext");
            throw new CommunicationException("NULL ldapContext");
        }

        ldapContext.setRequestControls(new Control[] { new SDFlagsControl(0x00000004) });

        LOG.debug("getDACL, attempting to fetch SD for searchFilter: {}, ldapContext: {}", searchFilter,
                ldapContext.getNameInNamespace());
        NamingEnumeration<SearchResult> results = null;
        try {
            results = ldapContext.search("", searchFilter, controls);
            if (!results.hasMoreElements()) {
                LOG.warn("getDACL, searchFilter '{}' found nothing in context '{}'", searchFilter,
                        ldapContext.getNameInNamespace());
                throw new NameNotFoundException("No results found for: " + searchFilter);
            }

            SearchResult res = results.next();
            if (results.hasMoreElements()) {
                // result from search filter is not unique
                throw new SizeLimitExceededException("The search filter '{}' matched more than one AD object");
            }
            final byte[] descbytes = (byte[]) res.getAttributes().get("nTSecurityDescriptor").get();
            final SDDL sddl = new SDDL(descbytes);
            dacl = sddl.getDacl();
            LOG.debug("getDACL, fetched SD & parsed DACL for searchFilter: {}, ldapContext: {}", searchFilter,
                    ldapContext.getNameInNamespace());
        } finally {
            try {
                if (results != null) {
                    results.close();
                }
            } catch (NamingException e) {
                LOG.debug("NamingException occurred while closing results: ", e);
            }
        }
    }
1357376
def _get_LDAP_connection():
    
    server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVER_FOR_SEARCH'))
    connection = ldap3.Connection(server)
    connection.open()

    return connection, get_optional_env('EPFL_LDAP_BASE_DN_FOR_SEARCH')
857863
def scopes(self):
        
        if not self.__scopes:
            self.__scopes = Scopes(self.__connection)
        return self.__scopes