3 namespace Drupal\user\Form;
5 use Drupal\Core\Flood\FloodInterface;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Render\RendererInterface;
9 use Drupal\user\UserAuthInterface;
10 use Drupal\user\UserStorageInterface;
11 use Symfony\Component\DependencyInjection\ContainerInterface;
14 * Provides a user login form.
18 class UserLoginForm extends FormBase {
23 * @var \Drupal\Core\Flood\FloodInterface
30 * @var \Drupal\user\UserStorageInterface
32 protected $userStorage;
35 * The user authentication object.
37 * @var \Drupal\user\UserAuthInterface
44 * @var \Drupal\Core\Render\RendererInterface
49 * Constructs a new UserLoginForm.
51 * @param \Drupal\Core\Flood\FloodInterface $flood
53 * @param \Drupal\user\UserStorageInterface $user_storage
55 * @param \Drupal\user\UserAuthInterface $user_auth
56 * The user authentication object.
57 * @param \Drupal\Core\Render\RendererInterface $renderer
60 public function __construct(FloodInterface $flood, UserStorageInterface $user_storage, UserAuthInterface $user_auth, RendererInterface $renderer) {
61 $this->flood = $flood;
62 $this->userStorage = $user_storage;
63 $this->userAuth = $user_auth;
64 $this->renderer = $renderer;
70 public static function create(ContainerInterface $container) {
72 $container->get('flood'),
73 $container->get('entity.manager')->getStorage('user'),
74 $container->get('user.auth'),
75 $container->get('renderer')
82 public function getFormId() {
83 return 'user_login_form';
89 public function buildForm(array $form, FormStateInterface $form_state) {
90 $config = $this->config('system.site');
92 // Display login form:
94 '#type' => 'textfield',
95 '#title' => $this->t('Username'),
97 '#maxlength' => USERNAME_MAX_LENGTH,
98 '#description' => $this->t('Enter your @s username.', ['@s' => $config->get('name')]),
101 'autocorrect' => 'none',
102 'autocapitalize' => 'none',
103 'spellcheck' => 'false',
104 'autofocus' => 'autofocus',
109 '#type' => 'password',
110 '#title' => $this->t('Password'),
112 '#description' => $this->t('Enter the password that accompanies your username.'),
116 $form['actions'] = ['#type' => 'actions'];
117 $form['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Log in')];
119 $form['#validate'][] = '::validateName';
120 $form['#validate'][] = '::validateAuthentication';
121 $form['#validate'][] = '::validateFinal';
123 $this->renderer->addCacheableDependency($form, $config);
131 public function submitForm(array &$form, FormStateInterface $form_state) {
132 $account = $this->userStorage->load($form_state->get('uid'));
134 // A destination was set, probably on an exception controller,
135 if (!$this->getRequest()->request->has('destination')) {
136 $form_state->setRedirect(
137 'entity.user.canonical',
138 ['user' => $account->id()]
142 $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
145 user_login_finalize($account);
149 * Sets an error if supplied username has been blocked.
151 public function validateName(array &$form, FormStateInterface $form_state) {
152 if (!$form_state->isValueEmpty('name') && user_is_blocked($form_state->getValue('name'))) {
153 // Blocked in user administration.
154 $form_state->setErrorByName('name', $this->t('The username %name has not been activated or is blocked.', ['%name' => $form_state->getValue('name')]));
159 * Checks supplied username/password against local users table.
161 * If successful, $form_state->get('uid') is set to the matching user ID.
163 public function validateAuthentication(array &$form, FormStateInterface $form_state) {
164 $password = trim($form_state->getValue('pass'));
165 $flood_config = $this->config('user.flood');
166 if (!$form_state->isValueEmpty('name') && strlen($password) > 0) {
167 // Do not allow any login from the current user's IP if the limit has been
168 // reached. Default is 50 failed attempts allowed in one hour. This is
169 // independent of the per-user limit to catch attempts from one IP to log
170 // in to many different user accounts. We have a reasonably high limit
171 // since there may be only one apparent IP for all users at an institution.
172 if (!$this->flood->isAllowed('user.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
173 $form_state->set('flood_control_triggered', 'ip');
176 $accounts = $this->userStorage->loadByProperties(['name' => $form_state->getValue('name'), 'status' => 1]);
177 $account = reset($accounts);
179 if ($flood_config->get('uid_only')) {
180 // Register flood events based on the uid only, so they apply for any
181 // IP address. This is the most secure option.
182 $identifier = $account->id();
185 // The default identifier is a combination of uid and IP address. This
186 // is less secure but more resistant to denial-of-service attacks that
187 // could lock out all users with public user names.
188 $identifier = $account->id() . '-' . $this->getRequest()->getClientIP();
190 $form_state->set('flood_control_user_identifier', $identifier);
192 // Don't allow login if the limit for this user has been reached.
193 // Default is to allow 5 failed attempts every 6 hours.
194 if (!$this->flood->isAllowed('user.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
195 $form_state->set('flood_control_triggered', 'user');
199 // We are not limited by flood control, so try to authenticate.
200 // Store $uid in form state as a flag for self::validateFinal().
201 $uid = $this->userAuth->authenticate($form_state->getValue('name'), $password);
202 $form_state->set('uid', $uid);
207 * Checks if user was not authenticated, or if too many logins were attempted.
209 * This validation function should always be the last one.
211 public function validateFinal(array &$form, FormStateInterface $form_state) {
212 $flood_config = $this->config('user.flood');
213 if (!$form_state->get('uid')) {
214 // Always register an IP-based failed login event.
215 $this->flood->register('user.failed_login_ip', $flood_config->get('ip_window'));
216 // Register a per-user failed login event.
217 if ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
218 $this->flood->register('user.failed_login_user', $flood_config->get('user_window'), $flood_control_user_identifier);
221 if ($flood_control_triggered = $form_state->get('flood_control_triggered')) {
222 if ($flood_control_triggered == 'user') {
223 $form_state->setErrorByName('name', $this->formatPlural($flood_config->get('user_limit'), '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>.', '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>.', [':url' => $this->url('user.pass')]));
226 // We did not find a uid, so the limit is IP-based.
227 $form_state->setErrorByName('name', $this->t('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>.', [':url' => $this->url('user.pass')]));
231 // Use $form_state->getUserInput() in the error message to guarantee
232 // that we send exactly what the user typed in. The value from
233 // $form_state->getValue() may have been modified by validation
234 // handlers that ran earlier than this one.
235 $user_input = $form_state->getUserInput();
236 $query = isset($user_input['name']) ? ['name' => $user_input['name']] : [];
237 $form_state->setErrorByName('name', $this->t('Unrecognized username or password. <a href=":password">Forgot your password?</a>', [':password' => $this->url('user.pass', [], ['query' => $query])]));
238 $accounts = $this->userStorage->loadByProperties(['name' => $form_state->getValue('name')]);
239 if (!empty($accounts)) {
240 $this->logger('user')->notice('Login attempt failed for %user.', ['%user' => $form_state->getValue('name')]);
243 // If the username entered is not a valid user,
244 // only store the IP address.
245 $this->logger('user')->notice('Login attempt failed from %ip.', ['%ip' => $this->getRequest()->getClientIp()]);
249 elseif ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
250 // Clear past failures for this user so as not to block a user who might
251 // log in and out more than once in an hour.
252 $this->flood->clear('user.failed_login_user', $flood_control_user_identifier);