You are here

public function Server::matchUsernameToExistingLdapEntry in Lightweight Directory Access Protocol (LDAP) 8.3

Queries LDAP server for the user.

Parameters

string $drupalUsername: Drupal user name.

Return value

array|bool An associative array representing LDAP data of a user. For example: 'sid' => LDAP server id 'mail' => derived from LDAP mail (not always populated). 'dn' => dn of user 'attr' => single LDAP entry array in form returned from ldap_search() 'dn' => dn of entry

1 call to Server::matchUsernameToExistingLdapEntry()
Server::userUserToExistingLdapEntry in ldap_servers/src/Entity/Server.php
Undocumented.

File

ldap_servers/src/Entity/Server.php, line 1159

Class

Server
Defines the Server entity.

Namespace

Drupal\ldap_servers\Entity

Code

public function matchUsernameToExistingLdapEntry($drupalUsername) {
  foreach ($this
    ->getBaseDn() as $baseDn) {
    if (empty($baseDn)) {
      continue;
    }
    $massager = new MassageAttributes();
    $filter = '(' . $this
      ->get('user_attr') . '=' . $massager
      ->queryLdapAttributeValue($drupalUsername) . ')';
    $result = $this
      ->search($baseDn, $filter);
    if (!$result || !isset($result['count']) || !$result['count']) {
      continue;
    }

    // Must find exactly one user for authentication to work.
    if ($result['count'] != 1) {
      $count = $result['count'];
      $this->logger
        ->error('Error: %count users found with %filter under %base_dn.', [
        '%count' => $count,
        '%filter' => $filter,
        '%base_dn' => $baseDn,
      ]);
      continue;
    }
    $match = $result[0];

    // Fix the attribute name in case a server (i.e.: MS Active Directory) is
    // messing with the characters' case.
    $nameAttribute = $this
      ->get('user_attr');
    if (isset($match[$nameAttribute][0])) {

      // Leave name.
    }
    elseif (isset($match[mb_strtolower($nameAttribute)][0])) {
      $nameAttribute = mb_strtolower($nameAttribute);
    }
    else {
      if ($this
        ->get('bind_method') == 'anon_user') {
        $result = [
          'dn' => $match['dn'],
          'mail' => $this
            ->userEmailFromLdapEntry($match),
          'attr' => $match,
          'id' => $this
            ->id(),
        ];
        return $result;
      }
      else {
        continue;
      }
    }

    // Filter out results with spaces added before or after, which are
    // considered OK by LDAP but are no good for us. Some setups have multiple
    // $nameAttribute per entry, so we loop through all possible options.
    foreach ($match[$nameAttribute] as $value) {
      if (mb_strtolower(trim($value)) == mb_strtolower($drupalUsername)) {
        $result = [
          'dn' => $match['dn'],
          'mail' => $this
            ->userEmailFromLdapEntry($match),
          'attr' => $match,
          'id' => $this
            ->id(),
        ];
        return $result;
      }
    }
  }
}