Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / user / src / Form / UserLoginForm.php
1 <?php
2
3 namespace Drupal\user\Form;
4
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;
12
13 /**
14  * Provides a user login form.
15  *
16  * @internal
17  */
18 class UserLoginForm extends FormBase {
19
20   /**
21    * The flood service.
22    *
23    * @var \Drupal\Core\Flood\FloodInterface
24    */
25   protected $flood;
26
27   /**
28    * The user storage.
29    *
30    * @var \Drupal\user\UserStorageInterface
31    */
32   protected $userStorage;
33
34   /**
35    * The user authentication object.
36    *
37    * @var \Drupal\user\UserAuthInterface
38    */
39   protected $userAuth;
40
41   /**
42    * The renderer.
43    *
44    * @var \Drupal\Core\Render\RendererInterface
45    */
46   protected $renderer;
47
48   /**
49    * Constructs a new UserLoginForm.
50    *
51    * @param \Drupal\Core\Flood\FloodInterface $flood
52    *   The flood service.
53    * @param \Drupal\user\UserStorageInterface $user_storage
54    *   The user storage.
55    * @param \Drupal\user\UserAuthInterface $user_auth
56    *   The user authentication object.
57    * @param \Drupal\Core\Render\RendererInterface $renderer
58    *   The renderer.
59    */
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;
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public static function create(ContainerInterface $container) {
71     return new static(
72       $container->get('flood'),
73       $container->get('entity.manager')->getStorage('user'),
74       $container->get('user.auth'),
75       $container->get('renderer')
76     );
77   }
78
79   /**
80    * {@inheritdoc}
81    */
82   public function getFormId() {
83     return 'user_login_form';
84   }
85
86   /**
87    * {@inheritdoc}
88    */
89   public function buildForm(array $form, FormStateInterface $form_state) {
90     $config = $this->config('system.site');
91
92     // Display login form:
93     $form['name'] = [
94       '#type' => 'textfield',
95       '#title' => $this->t('Username'),
96       '#size' => 60,
97       '#maxlength' => USERNAME_MAX_LENGTH,
98       '#description' => $this->t('Enter your @s username.', ['@s' => $config->get('name')]),
99       '#required' => TRUE,
100       '#attributes' => [
101         'autocorrect' => 'none',
102         'autocapitalize' => 'none',
103         'spellcheck' => 'false',
104         'autofocus' => 'autofocus',
105       ],
106     ];
107
108     $form['pass'] = [
109       '#type' => 'password',
110       '#title' => $this->t('Password'),
111       '#size' => 60,
112       '#description' => $this->t('Enter the password that accompanies your username.'),
113       '#required' => TRUE,
114     ];
115
116     $form['actions'] = ['#type' => 'actions'];
117     $form['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Log in')];
118
119     $form['#validate'][] = '::validateName';
120     $form['#validate'][] = '::validateAuthentication';
121     $form['#validate'][] = '::validateFinal';
122
123     $this->renderer->addCacheableDependency($form, $config);
124
125     return $form;
126   }
127
128   /**
129    * {@inheritdoc}
130    */
131   public function submitForm(array &$form, FormStateInterface $form_state) {
132     $account = $this->userStorage->load($form_state->get('uid'));
133
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()]
139       );
140     }
141     else {
142       $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
143     }
144
145     user_login_finalize($account);
146   }
147
148   /**
149    * Sets an error if supplied username has been blocked.
150    */
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')]));
155     }
156   }
157
158   /**
159    * Checks supplied username/password against local users table.
160    *
161    * If successful, $form_state->get('uid') is set to the matching user ID.
162    */
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');
174         return;
175       }
176       $accounts = $this->userStorage->loadByProperties(['name' => $form_state->getValue('name'), 'status' => 1]);
177       $account = reset($accounts);
178       if ($account) {
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();
183         }
184         else {
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();
189         }
190         $form_state->set('flood_control_user_identifier', $identifier);
191
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');
196           return;
197         }
198       }
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);
203     }
204   }
205
206   /**
207    * Checks if user was not authenticated, or if too many logins were attempted.
208    *
209    * This validation function should always be the last one.
210    */
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);
219       }
220
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')]));
224         }
225         else {
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')]));
228         }
229       }
230       else {
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')]);
241         }
242         else {
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()]);
246         }
247       }
248     }
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);
253     }
254   }
255
256 }