You are here

public function LdapBaseManager::queryLdapForUsername in Lightweight Directory Access Protocol (LDAP) 8.4

Queries LDAP server for the user.

@todo This function does return data and check for validity of response. This makes responses difficult to parse and should be optimized.

Parameters

string|null $base_dn: Base DN.

string $drupal_username: Drupal user name.

Return value

\Symfony\Component\Ldap\Entry|false|null LDAP entry.

1 call to LdapBaseManager::queryLdapForUsername()
LdapBaseManager::queryAllBaseDnLdapForUsername in ldap_servers/src/LdapBaseManager.php
Queries LDAP server for the user.

File

ldap_servers/src/LdapBaseManager.php, line 444

Class

LdapBaseManager
LDAP Base Manager.

Namespace

Drupal\ldap_servers

Code

public function queryLdapForUsername(?string $base_dn, string $drupal_username) {
  if (!$this
    ->checkAvailability()) {
    return FALSE;
  }
  if (empty($base_dn)) {
    return NULL;
  }
  $query = sprintf('(%s=%s)', $this->server
    ->getAuthenticationNameAttribute(), $this
    ->ldapEscapeFilter($drupal_username));
  try {

    // We are requesting regular and operational attributes with this filter
    // since some directories (e.g. OpenLDAP) have common overlays such as
    // "memberOf" in operational attributes.
    // @see https://www.drupal.org/i/2939308
    $ldap_response = $this->ldap
      ->query($base_dn, $query, [
      'filter' => [
        '*',
        '+',
      ],
    ])
      ->execute();
  } catch (LdapException $e) {

    // Must find exactly one user for authentication to work.
    $this->logger
      ->error('LDAP server query error %message', [
      '%message' => $e
        ->getMessage(),
    ]);
    return FALSE;
  }
  if ($ldap_response
    ->count() === 0) {
    return NULL;
  }
  if ($ldap_response
    ->count() !== 1) {

    // Must find exactly one user for authentication to work.
    $this->logger
      ->error('Error: %count users found with %filter under %base_dn.', [
      '%count' => $ldap_response
        ->count(),
      '%filter' => $query,
      '%base_dn' => $base_dn,
    ]);
    return NULL;
  }
  return $ldap_response
    ->toArray()[0];
}