UserLoginForm.php 9.04 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\user\Form\UserLoginForm.
 */

namespace Drupal\user\Form;

use Drupal\Core\Flood\FloodInterface;
11
use Drupal\Core\Form\FormBase;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\user\UserAuthInterface;
14
use Drupal\user\UserStorageInterface;
15 16 17 18 19
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a user login form.
 */
20
class UserLoginForm extends FormBase {
21 22 23 24 25 26 27 28 29

  /**
   * The flood service.
   *
   * @var \Drupal\Core\Flood\FloodInterface
   */
  protected $flood;

  /**
30
   * The user storage.
31
   *
32
   * @var \Drupal\user\UserStorageInterface
33
   */
34
  protected $userStorage;
35

36 37 38 39 40 41 42
  /**
   * The user authentication object.
   *
   * @var \Drupal\user\UserAuthInterface
   */
  protected $userAuth;

43 44 45 46 47
  /**
   * Constructs a new UserLoginForm.
   *
   * @param \Drupal\Core\Flood\FloodInterface $flood
   *   The flood service.
48 49
   * @param \Drupal\user\UserStorageInterface $user_storage
   *   The user storage.
50 51
   * @param \Drupal\user\UserAuthInterface $user_auth
   *   The user authentication object.
52
   */
53
  public function __construct(FloodInterface $flood, UserStorageInterface $user_storage, UserAuthInterface $user_auth) {
54
    $this->flood = $flood;
55
    $this->userStorage = $user_storage;
56
    $this->userAuth = $user_auth;
57 58 59 60 61 62 63 64
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('flood'),
65
      $container->get('entity.manager')->getStorage('user'),
66
      $container->get('user.auth')
67 68 69 70 71 72
    );
  }

  /**
   * {@inheritdoc}
   */
73
  public function getFormId() {
74 75 76 77 78 79
    return 'user_login_form';
  }

  /**
   * {@inheritdoc}
   */
80
  public function buildForm(array $form, FormStateInterface $form_state) {
81 82 83
    // Display login form:
    $form['name'] = array(
      '#type' => 'textfield',
84
      '#title' => $this->t('Username'),
85 86
      '#size' => 60,
      '#maxlength' => USERNAME_MAX_LENGTH,
87
      '#description' => $this->t('Enter your @s username.', array('@s' => $this->config('system.site')->get('name'))),
88 89 90 91 92 93 94 95 96 97 98
      '#required' => TRUE,
      '#attributes' => array(
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ),
    );

    $form['pass'] = array(
      '#type' => 'password',
99
      '#title' => $this->t('Password'),
100
      '#size' => 60,
101
      '#description' => $this->t('Enter the password that accompanies your username.'),
102 103 104 105
      '#required' => TRUE,
    );

    $form['actions'] = array('#type' => 'actions');
106
    $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Log in'));
107

108 109 110
    $form['#validate'][] = '::validateName';
    $form['#validate'][] = '::validateAuthentication';
    $form['#validate'][] = '::validateFinal';
111 112 113 114 115 116 117

    return $form;
  }

  /**
   * {@inheritdoc}
   */
118
  public function submitForm(array &$form, FormStateInterface $form_state) {
119
    $account = $this->userStorage->load($form_state->get('uid'));
120 121

    // A destination was set, probably on an exception controller,
122
    if (!$this->getRequest()->request->has('destination')) {
123
      $form_state->setRedirect(
124
        'entity.user.canonical',
125
        array('user' => $account->id())
126 127 128
      );
    }
    else {
129
      $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
130
    }
131 132 133 134 135 136 137

    user_login_finalize($account);
  }

  /**
   * Sets an error if supplied username has been blocked.
   */
138
  public function validateName(array &$form, FormStateInterface $form_state) {
139
    if (!$form_state->isValueEmpty('name') && user_is_blocked($form_state->getValue('name'))) {
140
      // Blocked in user administration.
141
      $form_state->setErrorByName('name', $this->t('The username %name has not been activated or is blocked.', array('%name' => $form_state->getValue('name'))));
142 143 144 145 146 147
    }
  }

  /**
   * Checks supplied username/password against local users table.
   *
148
   * If successful, $form_state->get('uid') is set to the matching user ID.
149
   */
150
  public function validateAuthentication(array &$form, FormStateInterface $form_state) {
151
    $password = trim($form_state->getValue('pass'));
152
    $flood_config = $this->config('user.flood');
153
    if (!$form_state->isValueEmpty('name') && !empty($password)) {
154 155 156 157 158 159
      // Do not allow any login from the current user's IP if the limit has been
      // reached. Default is 50 failed attempts allowed in one hour. This is
      // independent of the per-user limit to catch attempts from one IP to log
      // in to many different user accounts.  We have a reasonably high limit
      // since there may be only one apparent IP for all users at an institution.
      if (!$this->flood->isAllowed('user.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
160
        $form_state->set('flood_control_triggered', 'ip');
161 162
        return;
      }
163
      $accounts = $this->userStorage->loadByProperties(array('name' => $form_state->getValue('name'), 'status' => 1));
164 165 166 167 168 169 170 171 172 173 174
      $account = reset($accounts);
      if ($account) {
        if ($flood_config->get('uid_only')) {
          // Register flood events based on the uid only, so they apply for any
          // IP address. This is the most secure option.
          $identifier = $account->id();
        }
        else {
          // The default identifier is a combination of uid and IP address. This
          // is less secure but more resistant to denial-of-service attacks that
          // could lock out all users with public user names.
175
          $identifier = $account->id() . '-' . $this->getRequest()->getClientIP();
176
        }
177
        $form_state->set('flood_control_user_identifier', $identifier);
178 179 180 181

        // Don't allow login if the limit for this user has been reached.
        // Default is to allow 5 failed attempts every 6 hours.
        if (!$this->flood->isAllowed('user.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
182
          $form_state->set('flood_control_triggered', 'user');
183 184 185 186
          return;
        }
      }
      // We are not limited by flood control, so try to authenticate.
187 188 189
      // Store $uid in form state as a flag for self::validateFinal().
      $uid = $this->userAuth->authenticate($form_state->getValue('name'), $password);
      $form_state->set('uid', $uid);
190 191 192 193 194 195 196 197
    }
  }

  /**
   * Checks if user was not authenticated, or if too many logins were attempted.
   *
   * This validation function should always be the last one.
   */
198
  public function validateFinal(array &$form, FormStateInterface $form_state) {
199
    $flood_config = $this->config('user.flood');
200
    if (!$form_state->get('uid')) {
201 202 203
      // Always register an IP-based failed login event.
      $this->flood->register('user.failed_login_ip', $flood_config->get('ip_window'));
      // Register a per-user failed login event.
204 205
      if ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
        $this->flood->register('user.failed_login_user', $flood_config->get('user_window'), $flood_control_user_identifier);
206 207
      }

208 209
      if ($flood_control_triggered = $form_state->get('flood_control_triggered')) {
        if ($flood_control_triggered == 'user') {
210
          $form_state->setErrorByName('name', $this->formatPlural($flood_config->get('user_limit'), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => $this->url('user.pass'))));
211 212 213
        }
        else {
          // We did not find a uid, so the limit is IP-based.
214
          $form_state->setErrorByName('name', $this->t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => $this->url('user.pass'))));
215 216 217
        }
      }
      else {
218
        $form_state->setErrorByName('name', $this->t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => $this->url('user.pass', [], array('query' => array('name' => $form_state->getValue('name')))))));
219
        $accounts = $this->userStorage->loadByProperties(array('name' => $form_state->getValue('name')));
220
        if (!empty($accounts)) {
221
          $this->logger('user')->notice('Login attempt failed for %user.', array('%user' => $form_state->getValue('name')));
222 223 224 225
        }
        else {
          // If the username entered is not a valid user,
          // only store the IP address.
226
          $this->logger('user')->notice('Login attempt failed from %ip.', array('%ip' => $this->getRequest()->getClientIp()));
227 228 229
        }
      }
    }
230
    elseif ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
231 232
      // Clear past failures for this user so as not to block a user who might
      // log in and out more than once in an hour.
233
      $this->flood->clear('user.failed_login_user', $flood_control_user_identifier);
234 235 236 237
    }
  }

}