You are here

function saml_sp_drupal_login_get_uid in SAML Service Provider 7.3

Same name and namespace in other branches
  1. 8.2 modules/saml_sp_drupal_login/saml_sp_drupal_login.module \saml_sp_drupal_login_get_uid()
  2. 7.8 modules/saml_sp_drupal_login/saml_sp_drupal_login.module \saml_sp_drupal_login_get_uid()
  3. 7.2 modules/saml_sp_drupal_login/saml_sp_drupal_login.module \saml_sp_drupal_login_get_uid()

Get the uid from either users table or custom field. Custom field should be used if the users need to be able to change the email address on IdP, because then it cannot be used for identifying a user. Email address can be used as a backup method if user is singing in for the first time and their NameID value has not been stored to the given field yet.

Parameters

String $name_id: The NameID value which SSO server provides in SAML response.

String $field_name: The name of the field in Drupal where NameID is stored.

String $email: User email address which is only used if NameID cannot be found.

Return value

String $uid The user ID in Drupal which matches the NameID or email address. FALSE if it cannot be found.

1 call to saml_sp_drupal_login_get_uid()
saml_sp_drupal_login__saml_authenticate in modules/saml_sp_drupal_login/saml_sp_drupal_login.module
SAML authentication callback.

File

modules/saml_sp_drupal_login/saml_sp_drupal_login.module, line 291
SAML Drupal Login

Code

function saml_sp_drupal_login_get_uid($name_id, $field_name, $email = NULL) {
  if ($field_name == 'mail') {
    return db_query("SELECT uid FROM {users} WHERE mail = :mail", array(
      ':mail' => $name_id,
    ))
      ->fetchField();
  }
  else {

    // Find the uid from the field where it is supposed to be stored
    $db_field = 'field_data_' . $field_name;
    $column = $field_name . '_value';
    $uid = db_select($db_field, 'nameid')
      ->fields('nameid', array(
      'entity_id',
    ))
      ->condition($column, $name_id, '=')
      ->execute()
      ->fetchField();

    // If uid is not found, try to find it from the users table with the email.
    // This might be the case if existing users are exported to new IdP,
    // then they will not have ID from IdP on their first login.
    if (empty($uid)) {
      $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(
        ':mail' => $email,
      ))
        ->fetchField();
      if (!empty($uid)) {
        $user = user_load($uid);
        $wrapper = entity_metadata_wrapper('user', $user);
        $wrapper->field_nameid
          ->set($name_id);
        $wrapper
          ->save();
      }
      else {
        return FALSE;
      }
    }
    return $uid;
  }
}