-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathLogin.php
More file actions
483 lines (439 loc) · 16.8 KB
/
Login.php
File metadata and controls
483 lines (439 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
<?php
namespace Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane;
use Drupal\commerce\CredentialsCheckFloodInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\user\UserAuthInterface;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Provides the login pane.
*
* @CommerceCheckoutPane(
* id = "login",
* label = @Translation("Login or continue as guest"),
* default_step = "login",
* )
*/
class Login extends CheckoutPaneBase implements CheckoutPaneInterface, ContainerFactoryPluginInterface {
/**
* The credentials check flood controller.
*
* @var \Drupal\commerce\CredentialsCheckFloodInterface
*/
protected $credentialsCheckFlood;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The user authentication object.
*
* @var \Drupal\user\UserAuthInterface
*/
protected $userAuth;
/**
* The client IP address.
*
* @var string
*/
protected $clientIp;
/**
* Constructs a new Login object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowInterface $checkout_flow
* The parent checkout flow.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\commerce\CredentialsCheckFloodInterface $credentials_check_flood
* The credentials check flood controller.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\user\UserAuthInterface $user_auth
* The user authentication object.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager, CredentialsCheckFloodInterface $credentials_check_flood, AccountInterface $current_user, UserAuthInterface $user_auth, RequestStack $request_stack) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
$this->credentialsCheckFlood = $credentials_check_flood;
$this->currentUser = $current_user;
$this->userAuth = $user_auth;
$this->clientIp = $request_stack->getCurrentRequest()->getClientIp();
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, CheckoutFlowInterface $checkout_flow = NULL) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$checkout_flow,
$container->get('entity_type.manager'),
$container->get('commerce.credentials_check_flood'),
$container->get('current_user'),
$container->get('user.auth'),
$container->get('request_stack')
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'allow_guest_checkout' => TRUE,
'allow_registration' => FALSE,
] + parent::defaultConfiguration();
}
/**
* {@inheritdoc}
*/
public function buildConfigurationSummary() {
if (!empty($this->configuration['allow_guest_checkout'])) {
$summary = $this->t('Guest checkout: Allowed');
}
else {
$summary = $this->t('Guest checkout: Not allowed') . '<br>';
if (!empty($this->configuration['allow_registration'])) {
$summary .= $this->t('Registration: Allowed');
}
else {
$summary .= $this->t('Registration: Not allowed');
}
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['allow_guest_checkout'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow guest checkout'),
'#default_value' => $this->configuration['allow_guest_checkout'],
];
$form['allow_registration'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow registration'),
'#default_value' => $this->configuration['allow_registration'],
'#states' => [
'visible' => [
':input[name="configuration[panes][login][configuration][allow_guest_checkout]"]' => ['checked' => FALSE],
],
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
if (!$form_state->getErrors()) {
$values = $form_state->getValue($form['#parents']);
$this->configuration['allow_guest_checkout'] = !empty($values['allow_guest_checkout']);
$this->configuration['allow_registration'] = !empty($values['allow_registration']);
}
}
/**
* {@inheritdoc}
*/
public function isVisible() {
return $this->currentUser->isAnonymous();
}
/**
* {@inheritdoc}
*/
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
$pane_form['#attached']['library'][] = 'commerce_checkout/login_pane';
$pane_form['returning_customer'] = [
'#type' => 'fieldset',
'#title' => $this->t('Returning Customer'),
'#attributes' => [
'class' => [
'form-wrapper__login-option',
'form-wrapper__returning-customer',
],
],
];
$pane_form['returning_customer']['name'] = [
'#type' => 'textfield',
'#title' => $this->t('Username'),
'#size' => 60,
'#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
'#attributes' => [
'autocorrect' => 'none',
'autocapitalize' => 'none',
'spellcheck' => 'false',
'autofocus' => 'autofocus',
],
];
$pane_form['returning_customer']['password'] = [
'#type' => 'password',
'#title' => $this->t('Password'),
'#size' => 60,
];
$pane_form['returning_customer']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Log in'),
'#op' => 'login',
];
$pane_form['returning_customer']['forgot_password'] = [
'#type' => 'markup',
'#markup' => Link::createFromRoute($this->t('Forgot password?'), 'user.pass')->toString(),
];
$pane_form['guest'] = [
'#type' => 'fieldset',
'#title' => $this->t('Guest Checkout'),
'#access' => $this->configuration['allow_guest_checkout'],
'#attributes' => [
'class' => [
'form-wrapper__login-option',
'form-wrapper__guest-checkout',
],
],
];
$pane_form['guest']['text'] = [
'#prefix' => '<p>',
'#suffix' => '</p>',
'#markup' => $this->t('Proceed to checkout. You can optionally create an account at the end.'),
];
$pane_form['guest']['continue'] = [
'#type' => 'submit',
'#value' => $this->t('Continue as Guest'),
'#op' => 'continue',
];
$pane_form['register'] = [
'#type' => 'fieldset',
'#title' => $this->t('New Customer'),
'#access' => $this->configuration['allow_registration'],
'#attributes' => [
'class' => [
'form-wrapper__login-option',
'form-wrapper__guest-checkout',
],
],
];
$pane_form['register']['mail'] = [
'#type' => 'email',
'#title' => $this->t('Email address'),
'#required' => FALSE,
];
$pane_form['register']['name'] = [
'#type' => 'textfield',
'#title' => $this->t('Username'),
'#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
'#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."),
'#required' => FALSE,
'#attributes' => [
'class' => ['username'],
'autocorrect' => 'off',
'autocapitalize' => 'off',
'spellcheck' => 'false',
],
'#default_value' => '',
];
$pane_form['register']['password'] = [
'#type' => 'password_confirm',
'#size' => 60,
'#description' => $this->t('Provide a password for the new account in both fields.'),
'#required' => FALSE,
];
$pane_form['register']['register'] = [
'#type' => 'submit',
'#value' => $this->t('Create account and continue'),
'#op' => 'register',
];
return $pane_form;
}
/**
* {@inheritdoc}
*/
public function validatePaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
$triggering_element = $form_state->getTriggeringElement();
switch ($triggering_element['#op']) {
case 'continue':
return;
case 'login':
$this->validateReturningCustomer($pane_form, $form_state, $complete_form);
break;
case 'register':
$this->validateRegister($pane_form, $form_state, $complete_form);
break;
}
}
/**
* Validates a returning customers username and password.
*
* @param array $pane_form
* The pane form, containing the following basic properties:
* - #parents: Identifies the position of the pane form in the overall
* parent form, and identifies the location where the field values are
* placed within $form_state->getValues().
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
* @param array $complete_form
* The complete form structure.
*/
protected function validateReturningCustomer(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
$values = $form_state->getValue($pane_form['#parents']);
$name_element = $pane_form['returning_customer']['name'];
$username = $values['returning_customer']['name'];
$password = trim($values['returning_customer']['password']);
// Generate the "reset password" url.
$query = !empty($username) ? ['name' => $username] : [];
$password_url = Url::fromRoute('user.pass', [], ['query' => $query])->toString();
if (empty($username) || empty($password)) {
$form_state->setError($pane_form['returning_customer'], $this->t('Unrecognized username or password. <a href=":url">Have you forgotten your password?</a>', [':url' => $password_url]));
return;
}
if (user_is_blocked($username)) {
$form_state->setError($name_element, $this->t('The username %name has not been activated or is blocked.', ['%name' => $username]));
return;
}
if (!$this->credentialsCheckFlood->isAllowedHost($this->clientIp)) {
$form_state->setErrorByName($name_element, $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' => Url::fromRoute('user.pass')]));
$this->credentialsCheckFlood->register($this->clientIp, $username);
return;
}
elseif (!$this->credentialsCheckFlood->isAllowedAccount($this->clientIp, $username)) {
$form_state->setErrorByName($name_element, $this->t('Too many failed login attempts for this account. It is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', [':url' => Url::fromRoute('user.pass')]));
$this->credentialsCheckFlood->register($this->clientIp, $username);
return;
}
$uid = $this->userAuth->authenticate($username, $password);
if (!$uid) {
$this->credentialsCheckFlood->register($this->clientIp, $username);
$form_state->setError($name_element, $this->t('Unrecognized username or password. <a href=":url">Have you forgotten your password?</a>', [':url' => $password_url]));
}
$form_state->set('logged_in_uid', $uid);
}
/**
* Validates the registration form and creates a new user.
*
* @param array $pane_form
* The pane form, containing the following basic properties:
* - #parents: Identifies the position of the pane form in the overall
* parent form, and identifies the location where the field values are
* placed within $form_state->getValues().
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
* @param array $complete_form
* The complete form structure.
*/
protected function validateRegister(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
if ($user_values = $this->getAndValidateRegisterUserValues($pane_form, $form_state)) {
/** @var \Drupal\user\UserInterface $account */
$account = $this->entityTypeManager->getStorage('user')->create($user_values);
// Validate the entity. This will ensure that the username and email
// are in the right format and not already taken.
$violations = $account->validate();
foreach ($violations->getByFields(['name', 'mail']) as $violation) {
list($field_name) = explode('.', $violation->getPropertyPath(), 2);
$form_state->setError($pane_form['register'][$field_name], $violation->getMessage());
}
if (!$form_state->hasAnyErrors()) {
$account->save();
$form_state->set('logged_in_uid', $account->id());
}
}
}
/**
* Validates form values for the register form.
*
* @param array $pane_form
* The pane form, containing the following basic properties:
* - #parents: Identifies the position of the pane form in the overall
* parent form, and identifies the location where the field values are
* placed within $form_state->getValues().
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*
* @return array|null
* Either an array of values that can be used to create a new user or NULL
* if there are validation errors.
*/
protected function getAndValidateRegisterUserValues(array &$pane_form, FormStateInterface $form_state) {
$values = $form_state->getValue($pane_form['#parents']);
$user_values = [
'status' => TRUE
];
// If the e-mail, username and password fields are visible, ensure they
// have a value and add them to the user values. This allows subclasses and
// form alters to hide certain form elements and then provide alternative
// values, for example to set the username based on the e-mail.
$email_element = $pane_form['register']['mail'];
if (!isset($email_element['#access']) || $email_element['#access']) {
$email = $values['register']['mail'];
if (empty($email)) {
$form_state->setError($email_element, $this->t('Email field is required.'));
return NULL;
}
else {
$user_values['mail'] = $email;
}
}
$name_element = $pane_form['register']['name'];
if (!isset($name_element['#access']) || $name_element['#access']) {
$username = $values['register']['name'];
if (empty($username)) {
$form_state->setError($name_element, $this->t('Username field is required.'));
return NULL;
}
else {
$user_values['name'] = $username;
}
}
$password_element = $pane_form['register']['password'];
if (!isset($password_element['#access']) || $password_element['#access']) {
$password = trim($values['register']['password']);
if (empty($password)) {
$form_state->setError($pane_form['register']['password'], $this->t('Password field is required.'));
return NULL;
}
else {
$user_values['pass'] = $password;
}
}
return $user_values;
}
/**
* {@inheritdoc}
*/
public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
$triggering_element = $form_state->getTriggeringElement();
switch ($triggering_element['#op']) {
case 'continue':
break;
case 'login':
case 'register':
$storage = $this->entityTypeManager->getStorage('user');
/** @var \Drupal\user\UserInterface $account */
$account = $storage->load($form_state->get('logged_in_uid'));
user_login_finalize($account);
$this->order->setCustomer($account);
$this->credentialsCheckFlood->clearAccount($this->clientIp, $account->getAccountName());
break;
}
$form_state->setRedirect('commerce_checkout.form', [
'commerce_order' => $this->order->id(),
'step' => $this->checkoutFlow->getNextStepId($this->getStepId()),
]);
}
}