You are here

function saml_sp_drupal_login_get_user in SAML Service Provider 3.x

Same name and namespace in other branches
  1. 8.3 modules/saml_sp_drupal_login/saml_sp_drupal_login.module \saml_sp_drupal_login_get_user()
  2. 4.x modules/saml_sp_drupal_login/saml_sp_drupal_login.module \saml_sp_drupal_login_get_user()

Get the User object 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

\Drupal\user\UserInterface|false The user object in Drupal which matches the NameID or email address, or FALSE if it cannot be found.

1 call to saml_sp_drupal_login_get_user()
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 283
SAML Drupal Login.

Code

function saml_sp_drupal_login_get_user($name_id, $field_name, $email = NULL) {
  if ($field_name == 'mail') {
    return user_load_by_mail($name_id);
  }

  // Find the uid from the field where it is supposed to be stored.
  $db_field = 'field_data_' . $field_name;
  $column = $field_name . '_value';
  $uid = \Drupal::database()
    ->select($db_field, 'nameid')
    ->fields('nameid', [
    '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.
  $update_name_id = FALSE;
  if (empty($uid)) {
    $uid = \Drupal::database()
      ->query("SELECT uid FROM {users} WHERE mail = :mail", [
      ':mail' => $email,
    ])
      ->fetchField();
    $update_name_id = TRUE;
  }
  if (empty($uid)) {
    return FALSE;
  }

  // We found a user; update if necessary and return.
  $user = User::load($uid);
  if ($update_name_id) {
    $wrapper = entity_metadata_wrapper('user', $user);
    $wrapper->field_nameid
      ->set($name_id);
    $wrapper
      ->save();
  }
  return $user;
}