You are here

function simple_ldap_user_login_validate in Simple LDAP 8

Custom validation handler for the login form.

Attempts LDAP authentication for user login attempts.

1 string reference to 'simple_ldap_user_login_validate'
simple_ldap_user_form_user_login_form_alter in modules/simple_ldap_user/simple_ldap_user.module
Implements hook_form_FORM_ID_alter().

File

modules/simple_ldap_user/simple_ldap_user.module, line 59

Code

function simple_ldap_user_login_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $name = $form_state
    ->getValue('name');
  $password = $form_state
    ->getValue('pass');
  $authenticator = \Drupal::service('simple_ldap_user.auth');
  $manager = \Drupal::service('simple_ldap_user.manager');

  // Ensure we should provide extra authentication for this user.
  if (!$authenticator
    ->canAuthenticate($name)) {
    return;
  }

  // Check whether the user exists on LDAP.
  $ldap_user = $manager
    ->getLdapUser($name);
  if (!$ldap_user) {
    $form_state
      ->set('uid', FALSE);
    $form_state
      ->setErrorByName('name', t('An account could not be found or an ID conflict has been detected.  Please contact your site administrator.'));

    // If we could not get an LdapUser, we don't need to worry about the rest of this function.
    return;
  }

  // Attempt LDAP authentication.
  if (!$authenticator
    ->authenticate($ldap_user
    ->getDn(), $password)) {
    $form_state
      ->set('uid', FALSE);
    $form_state
      ->setError($form, t('Could not authenticate with your username/password in LDAP. Please contact your site administrator.'));
    return;
  }
  $user = \Drupal::service('simple_ldap_user.sync')
    ->importIntoDrupal($ldap_user, $password);

  // Set the uid so Drupal authentication passes if LDAP authentication passes.
  $form_state
    ->set('uid', $user
    ->id());
}