Bind with searchDN and searchPW and search for the user's DN.
Use search_base and search_filter defined in config file.
Return the found DN.
509342
function search_userdn($rcmail)
    {
        $binddn = $rcmail->config->get('password_ldap_searchDN');
        $bindpw = $rcmail->config->get('password_ldap_searchPW');

        $ldapConfig = array (
            'basedn'    => $rcmail->config->get('password_ldap_basedn'),
            'host'      => $rcmail->config->get('password_ldap_host', 'localhost'),
            'port'      => $rcmail->config->get('password_ldap_port', '389'),
            'starttls'  => $rcmail->config->get('password_ldap_starttls'),
            'version'   => $rcmail->config->get('password_ldap_version', '3'),
        );

        // allow anonymous searches
        if (!empty($binddn)) {
            $ldapConfig['binddn'] = $binddn;
            $ldapConfig['bindpw'] = $bindpw;
        }

        $ldap = Net_LDAP2::connect($ldapConfig);

        if (is_a($ldap, 'PEAR_Error')) {
            return '';
        }

        $base   = self::substitute_vars($rcmail->config->get('password_ldap_search_base'));
        $filter = self::substitute_vars($rcmail->config->get('password_ldap_search_filter'));
        $options = array (
            'scope' => 'sub',
            'attributes' => array(),
        );

        $result = $ldap->search($base, $filter, $options);
        if (is_a($result, 'PEAR_Error') || ($result->count() != 1)) {
            $ldap->done();
            return '';
        }
        $userDN = $result->current()->dn();
        $ldap->done();

        return $userDN;
    }
140503
def find(source = @source)
      scope = 0
      filter = "(objectClass=*)"
      if source.respond_to?(:search2_ext)
        source.search2(
          to_s,
          scope,
          filter
        )
      elsif source.respond_to?(:search)
        Array(source.search(
          :base => to_s,
          :scope => scope,
          :filter => filter,
          :limit => 1
        ))
      else
        raise RuntimeError, "missing or invalid source for LDAP search", caller
      end.first
    end
1218248
public static Response<SearchResult> executeSearchOperation(final ConnectionFactory connectionFactory,
                                                                final String baseDn,
                                                                final SearchFilter filter) throws LdapException {
        return executeSearchOperation(connectionFactory, baseDn, filter, ReturnAttributes.ALL_USER.value(), ReturnAttributes.ALL_USER.value());
    }
201351
def find_subnet(sb_id=None, sb_name=None):
        
        LOGGER.debug("SubnetService.find_subnet")
        if (sb_id is None or not sb_id) and (sb_name is None or not sb_name):
            raise exceptions.ArianeCallParametersError('id and name')

        if (sb_id is not None and sb_id) and (sb_name is not None and sb_name):
            LOGGER.warn('Both id and name are defined. Will give you search on id.')
            sb_name = None

        params = None
        if sb_id is not None and sb_id:
            params = {'id': sb_id}
        elif sb_name is not None and sb_name:
            params = {'name': sb_name}

        ret = None
        if params is not None:
            args = {'http_operation': 'GET', 'operation_path': 'get', 'parameters': params}
            response = SubnetService.requester.call(args)
            if response.rc == 0:
                ret = Subnet.json_2_subnet(response.response_content)
            elif response.rc != 404:
                err_msg = 'SubnetService.find_subnet - Problem while finding subnet (id:' + str(sb_id) + \
                          ', name:' + str(sb_name) + '). ' + \
                          '. Reason: ' + str(response.response_content) + '-' + str(response.error_message) + \
                          " (" + str(response.rc) + ")"
                LOGGER.warning(err_msg)

        return ret
1373350
def _load_user_dn(self):
        
        if self._using_simple_bind_mode():
            self._user_dn = self._construct_simple_user_dn()
        else:
            if self.settings.CACHE_TIMEOUT > 0:
                cache_key = valid_cache_key(
                    "django_auth_ldap.user_dn.{}".format(self._username)
                )
                self._user_dn = cache.get_or_set(
                    cache_key, self._search_for_user_dn, self.settings.CACHE_TIMEOUT
                )
            else:
                self._user_dn = self._search_for_user_dn()
31217
def _cache_get_for_dn(self, dn: str) -> Dict[str, bytes]:
        

        # no cached item, retrieve from ldap
        self._do_with_retry(
            lambda obj: obj.search(
                dn,
                '(objectclass=*)',
                ldap3.BASE,
                attributes=['*', '+']))
        results = self._obj.response
        if len(results) < 1:
            raise NoSuchObject("No results finding current value")
        if len(results) > 1:
            raise RuntimeError("Too many results finding current value")

        return results[0]['raw_attributes']
1168345
def bind(self):
        

        conn = self.initialize
        try:
            conn.simple_bind_s(
                current_app.config['LDAP_USERNAME'],
                current_app.config['LDAP_PASSWORD'])
            return conn
        except ldap.LDAPError as e:
            raise LDAPException(self.error(e.args))
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')
1108841
def search(cls, query, search_opts=None):
        

        if search_opts is None:
            search_opts = {}

        xmlrpc = XMLRPCConnection()
        try:
            search_result = xmlrpc.connection.search_pool(
                {
                    'query': query,
                    'search_options': search_opts,
                    'auth': AuthOptions().options
                })
        except xmlrpclib.Fault as xml_fault:
            raise _fault_to_exception(xml_fault)
        result = dict()
        result['result'] = []
        result['search_options'] = search_result['search_options']
        for pool in search_result['result']:
            p = Pool.from_dict(pool)
            result['result'].append(p)

        return result
1290670
def _search_pn(self, href=None, limit=None,
                   embed_items=None, embed_tracks=None, embed_metadata=None,
                   embed_insights=None):
        """"""

        url_components = urlparse(href)
        path = url_components.path
        data = parse_qs(url_components.query)

        # Change all lists into discrete values.
        for key in data.keys():
            data[key] = data[key][0]

        # Deal with limit overriding.
        if limit is not None:
            data['limit'] = limit

        # Deal with embeds overriding.
        final_embed = helper.process_embed_override(data.get('embed'),
                                                    embed_items,
                                                    embed_tracks,
                                                    embed_metadata,
                                                    embed_insights)
        if final_embed is not None:
            data['embed'] = final_embed

        raw_result = self.get(path, data)

        if raw_result.status < 200 or raw_result.status > 202:
            raise APIException(raw_result.status, raw_result.json)
        else:
            result = raw_result.json

        return result
1211596
def search_user(self, search_str, search_filter, local):
        '''  '''
        response, status_code = self.__pod__.Users.post_v1_user_search(
            sessionToken=self.__session__,
            searchRequest={'query': search_str,
                           'filters': search_filter}
        ).result()
        self.logger.debug('%s: %s' % (status_code, response))
        return status_code, response
883245
def LDAP_search(pattern_search, attribute):
    
    connection, ldap_base = _get_LDAP_connection()

    connection.search(
        search_base=ldap_base,
        search_filter=pattern_search,
        attributes=[attribute]
    )
    return connection.response
1225125
private void
findWin(InputStream in) {
	String packageName = ResolverConfig.class.getPackage().getName();
	String resPackageName = packageName + ".windows.DNSServer";
	ResourceBundle res = ResourceBundle.getBundle(resPackageName);

	String host_name = res.getString("host_name");
	String primary_dns_suffix = res.getString("primary_dns_suffix");
	String dns_suffix = res.getString("dns_suffix");
	String dns_servers = res.getString("dns_servers");

	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	try {
		List lserver = new ArrayList();
		List lsearch = new ArrayList();
		String line = null;
		boolean readingServers = false;
		boolean readingSearches = false;
		while ((line = br.readLine()) != null) {
			StringTokenizer st = new StringTokenizer(line);
			if (!st.hasMoreTokens()) {
				readingServers = false;
				readingSearches = false;
				continue;
			}
			String s = st.nextToken();
			if (line.indexOf(":") != -1) {
				readingServers = false;
				readingSearches = false;
			}
			
			if (line.indexOf(host_name) != -1) {
				while (st.hasMoreTokens())
					s = st.nextToken();
				Name name;
				try {
					name = Name.fromString(s, null);
				}
				catch (TextParseException e) {
					continue;
				}
				if (name.labels() == 1)
					continue;
				addSearch(s, lsearch);
			} else if (line.indexOf(primary_dns_suffix) != -1) {
				while (st.hasMoreTokens())
					s = st.nextToken();
				if (s.equals(":"))
					continue;
				addSearch(s, lsearch);
				readingSearches = true;
			} else if (readingSearches ||
				   line.indexOf(dns_suffix) != -1)
			{
				while (st.hasMoreTokens())
					s = st.nextToken();
				if (s.equals(":"))
					continue;
				addSearch(s, lsearch);
				readingSearches = true;
			} else if (readingServers ||
				   line.indexOf(dns_servers) != -1)
			{
				while (st.hasMoreTokens())
					s = st.nextToken();
				if (s.equals(":"))
					continue;
				addServer(s, lserver);
				readingServers = true;
			}
		}
		
		configureFromLists(lserver, lsearch);
	}
	catch (IOException e) {
	}
	finally {
		try {
			br.close();
		}
		catch (IOException e) {
		}
	}
	return;
}
427399
def _bind_for_search(anonymous=False, opts=None):
    '''
    
    '''
    # Get config params; create connection dictionary
    connargs = {}
    # config params (auth.ldap.*)
    params = {
        'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
                      'no_verify', 'anonymous',
                      'accountattributename', 'activedirectory'],
        'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
                       'auth_by_group_membership_only'],
    }

    paramvalues = {}

    for param in params['mandatory']:
        paramvalues[param] = _config(param, opts=opts)

    for param in params['additional']:
        paramvalues[param] = _config(param, mandatory=False, opts=opts)

    paramvalues['anonymous'] = anonymous

    # Only add binddn/bindpw to the connargs when they're set, as they're not
    # mandatory for initializing the LDAP object, but if they're provided
    # initially, a bind attempt will be done during the initialization to
    # validate them
    if paramvalues['binddn']:
        connargs['binddn'] = paramvalues['binddn']
        if paramvalues['bindpw']:
            params['mandatory'].append('bindpw')

    for name in params['mandatory']:
        connargs[name] = paramvalues[name]

    if not paramvalues['anonymous']:
        if paramvalues['binddn'] and paramvalues['bindpw']:
            # search for the user's DN to be used for the actual authentication
            return _LDAPConnection(**connargs).ldap
376990
def lookup_mail(cn)
      service&.search(base: tree,
                     filter: Net::LDAP::Filter.equals('cn', cn),
                     attributes: 'mail')&.first&.mail&.first.to_s
    end
941056
def system_find_users(input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/system/findUsers', input_params, always_retry=always_retry, **kwargs)
951817
def ldap_login(self, username, password):
        
        self.connect()

        if self.config.get('USER_SEARCH'):
            result = self.bind_search(username, password)
        else:
            result = self.direct_bind(username, password)
        return result