You are here

function _ldapauth_user_lookup in LDAP integration 5.2

Same name and namespace in other branches
  1. 5 ldapauth.module \_ldapauth_user_lookup()
  2. 6 ldapauth.module \_ldapauth_user_lookup()
2 calls to _ldapauth_user_lookup()
_ldapauth_login2dn in ./ldapauth.module
_ldapauth_save_user in ./ldapauth.module

File

./ldapauth.module, line 637

Code

function _ldapauth_user_lookup($name) {
  global $ldap;
  $ret = null;
  if (!$ldap) {
    return;
  }
  $row = db_fetch_object(db_query("SELECT binddn, bindpw FROM {ldapauth} WHERE name = '%s'", $ldap
    ->getOption('name')));
  $dn = $row->binddn;
  $pass = $row->bindpw;

  // If there is no BINDDN and BINDPW -- the connect will be an anonymous connect
  $ldap
    ->connect($dn, $pass);
  $possible_base_dns = explode("\r\n", $ldap
    ->getOption('basedn'));
  foreach ($possible_base_dns as $base_dn) {
    if (!$base_dn) {
      continue;
    }
    $name_attr = $ldap
      ->getOption('user_attr') ? $ldap
      ->getOption('user_attr') : LDAP_DEFAULT_USER_ATTRIBUTE;
    $filter = "{$name_attr}={$name}";
    $result = $ldap
      ->search($base_dn, $filter);
    if (!$result) {
      continue;
    }
    $num_matches = $result['count'];

    // must find exactly one user for authentication to
    if ($num_matches != 1) {
      watchdog('user', "Error: {$num_matches} users found with {$filter} under {$base_dn}", WATCHDOG_ERROR);
      continue;
    }
    $match = $result[0];

    // These lines serve to fix the attribute name in case a
    // naughty server (i.e.: MS Active Directory) is messing the
    // characters' case.
    // This was contributed by Dan "Gribnif" Wilga, and described
    // here: http://drupal.org/node/87833
    if (!isset($match[$name_attr][0])) {
      $name_attr = strtolower($name_attr);
      if (!isset($match[$name_attr][0])) {
        continue;
      }
    }

    // Finally, we must filter out results with spaces added before
    // or after, which are considered OK by LDAP but are no good for us
    // We allow lettercase independence, as requested by Marc Galera
    // on http://drupal.org/node/97728
    //
    // Some setups have multiple $name_attr per entry, as pointed out by
    // Clarence "sparr" Risher on http://drupal.org/node/102008, so we
    // loop through all possible options.
    $ok = false;
    foreach ($match[$name_attr] as $value) {
      if (strtolower($value) == strtolower($name)) {
        $ok = true;
        break;
      }
    }
    if (!$ok) {
      continue;
    }
    $ret = $match;
  }
  return $ret;
}