Find LDAP user DN by his username

@param  string $username

@return string | null
194766
protected function findLdapUserDnByUsername($username)
    {
        $ldapClient = $this->getLdapClient();
        $options = $this->getUtils()->getOptions();

        $loginFilterString = '';
        if (!empty($options['userLoginFilter'])) {
            $loginFilterString = $this->convertToFilterFormat($options['userLoginFilter']);
        }

        $searchString = '(&(objectClass='.$options['userObjectClass'].')('.$options['userNameAttribute'].'='.$username.')'.$loginFilterString.')';
        $result = $ldapClient->search($searchString, null, LDAP\Client::SEARCH_SCOPE_SUB);
        $GLOBALS['log']->debug('LDAP: user search string: "' . $searchString . '"');

        foreach ($result as $item) {
            return $item["dn"];
        }
    }
693445
protected function findUsersByUsernamePattern($usernamePattern, $authenticationProviderName = null)
    {
        if (preg_match('/[\\?\\*\\{\\[]/u', $usernamePattern)) {
            return array_filter(
                $this->userService->getUsers()->toArray(),
                function ($user) use ($usernamePattern, $authenticationProviderName) {
                    return fnmatch($usernamePattern, $this->userService->getUsername($user, $authenticationProviderName));
                }
            );
        } else {
            $user = $this->userService->getUser($usernamePattern, $authenticationProviderName);
            if ($user instanceof User) {
                return [$user];
            }
        }
        return [];
    }
949106
public function getUserByUsername($username)
    {
        $return = array();

        $users = $this->repository->users;
        foreach ($users as $user) {
            if ($user->username == $username) {
                $return = $user;
                break;
            }
        }

        return $return;
    }
728580
public function getUserIdFromLogin(string $username): int
    {
        return (int) $this->getDriver()->user->get($username, ['by' => 'login'])->ID;
    }
335486
public function delete($dn) {
    if (!$this->connection) {
      $this->connect();
      $this->bind();
    }
    $result = @ldap_delete($this->connection, $dn);
    if (!$result) {
      $error = "LDAP Server delete(%dn) in LdapServer::delete() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
      $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
      watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
    }
    return $result;
  }
1117639
def _get_user(self, username, attrs=ALL_ATTRS):
        """"""

        username = ldap.filter.escape_filter_chars(username)
        user_filter = self.user_filter_tmpl % {
            'username': self._uni(username)
        }
        r = self._search(self._byte_p2(user_filter), attrs, self.userdn)

        if len(r) == 0:
            return None

        # if NO_ATTR, only return the DN
        if attrs == NO_ATTR:
            dn_entry = r[0][0]
        # in other cases, return everything (dn + attributes)
        else:
            dn_entry = r[0]
        return dn_entry
1271176
@SuppressWarnings("unchecked")
    public LdapUser getLdapUser(final String username) {
        final Query query = pm.newQuery(LdapUser.class, "username == :username");
        final List<LdapUser> result = (List<LdapUser>) query.execute(username);
        return Collections.isEmpty(result) ? null : result.get(0);
    }
413416
public static function isExistByUsername( $username ) {

		$user = self::find()->where( 'username=:username', [ ':username' => $username ] )->one();

		return isset( $user );
	}
409867
protected function getUserInfo($username)
    {
        if (!isset(self::$users[$username])) return null;
    
        $user = compact('username') + self::$users[$username];
        unset($user['password']);
        
        return $user;
    }
221312
public function loadUserByUsername($username)
    {
        $user = $this->session->get(AuthenticationConstants::SECURITY_TOKEN_NAME);

        if ($user instanceof User) {
            return $user;
        }

        $authenticationError = $this->session->get(Security::AUTHENTICATION_ERROR);

        if ($authenticationError instanceof AuthenticationException) {
            throw new UsernameNotFoundException($authenticationError->getMessage());
        }

        throw new UsernameNotFoundException(
            sprintf('User %s was not authenticated by API.', $username)
        );
    }
180880
public function getSingleUser(string $username): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/users/:username', $username));
    }
152303
private function getUser($username)
    {
        if (!isset($this->users[strtolower($username)])) {
            $ex = new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
            $ex->setUsername($username);

            throw $ex;
        }

        return $this->users[strtolower($username)];
    }
958896
function iscreator($username) {
        if (empty($this->config->host_url) or (empty($this->config->attrcreators) && empty($this->config->groupecreators)) or empty($this->config->memberattribute)) {
            return false;
        }

        $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);

        // Test for group creator
        if (!empty($this->config->groupecreators)) {
            $ldapconnection = $this->ldap_connect();
            if ($this->config->memberattribute_isdn) {
                if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
                    return false;
                }
            } else {
                $userid = $extusername;
            }

            $group_dns = explode(';', $this->config->groupecreators);
            if (ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute)) {
                return true;
            }
        }

        // Build filter for attrcreator
        if (!empty($this->config->attrcreators)) {
            $attrs = explode(';', $this->config->attrcreators);
            $filter = '(& ('.$this->config->user_attribute."=$username)(|";
            foreach ($attrs as $attr){
                if(strpos($attr, '=')) {
                    $filter .= "($attr)";
                } else {
                    $filter .= '('.$this->config->memberattribute."=$attr)";
                }
            }
            $filter .= '))';

            // Search
            $result = $this->ldap_get_userlist($filter);
            if (count($result) != 0) {
                return true;
            }
        }

        return false;
    }
353795
public function get($username)
    {
        return isset($this->storage[$username]) ? $this->storage[$username] : false;
    }
1016791
public static function deleteUser($username)
	{
		if ( ! self::userExists( $username ) ) return false;

		$deleted_user = self::$auth['users'][ $username ];
		unset( self::$auth['users'][ $username ] );

		return $deleted_user;
	}
613635
private function buildUsernameWhere($username)
    {
        $userClass = $this->auth->getUserClass();

        $conditions = array_map(
            function ($prop, $username) { return $prop." = '".$username."'"; },
            $userClass::$usernameProperties,
            array_fill(0, count($userClass::$usernameProperties),
            addslashes($username)));

        return '('.implode(' OR ', $conditions).')';
    }
829909
private function getLDAPUser($username)
    {
        $adldap = false;
        $adUser = false;

        try {
            $ldapQuery = Settings::get('eloquent-ldap.user_filter');
            if (strpos($ldapQuery, self::USER_TOKEN)) {
                $ldapQuery = str_replace(self::USER_TOKEN, $username, $ldapQuery);
            }
            else {
                throw new \Exception("Invalid AD/LDAP query filter, check the configuration of 'LDAP_USER_FILTER'.");
            }

            $ldapFields = [
                Settings::get('eloquent-ldap.username_field'),
                Settings::get('eloquent-ldap.first_name_field'),
                Settings::get('eloquent-ldap.last_name_field'),
                Settings::get('eloquent-ldap.email_field'),
                'useraccountcontrol',
                'dn',
            ];

            // Build connection info.
            $ldapConOp = $this->GetLDAPConnectionOptions();

            if (Settings::get('eloquent-ldap.debug')) {
                // Set LDAP debug log level - useful in DEV, dangerous in PROD!!
                ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
            }

            // Connect to AD/LDAP
            $adldap = new Adldap();
            $adldap->addProvider($ldapConOp);
            $provider = $adldap->connect();

            // Search...
            $adUser = $provider->search()->select($ldapFields)->rawFilter($ldapQuery)->first();
//            $adResults = $provider->search()->select($ldapFields)->rawFilter($ldapQuery)->get();
//
//            if (isset($adResults) && is_array($adResults) && isset($adResults[0])) {
//                $adResults = $adResults[0];
//            }

            if (!$adUser) {
                $this->handleLDAPError($adldap);
            }
        } catch (\Exception $ex) {
            Log::error('Exception retrieving user information: ' . $ex->getMessage());
            Log::error($ex->getTraceAsString());
        }

        // Close connection.
        if (isset($provider)) {
            unset($provider);
        }
        // Close connection.
        if (isset($adldap)) {
            unset($adldap);
        }

        return $adUser;
    }