-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathAccountManagement.php
1678 lines (1515 loc) · 56.2 KB
/
AccountManagement.php
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Customer\Model;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\ConfirmationEmailLogManagementInterface;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\ValidationResultsInterfaceFactory;
use Magento\Customer\Api\SessionCleanerInterface;
use Magento\Customer\Helper\View as CustomerViewHelper;
use Magento\Customer\Model\AccountManagement\Authenticate;
use Magento\Customer\Model\Config\Share as ConfigShare;
use Magento\Customer\Model\Customer as CustomerModel;
use Magento\Customer\Model\Customer\CredentialsValidator;
use Magento\Customer\Model\ForgotPasswordToken\GetCustomerByToken;
use Magento\Customer\Model\Logger as CustomerLogger;
use Magento\Customer\Model\Metadata\Validator;
use Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory;
use Magento\Directory\Model\AllowedCountries;
use Magento\Eav\Model\Validator\Attribute\Backend;
use Magento\Framework\Api\ExtensibleDataObjectConverter;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\DataObjectFactory as ObjectFactory;
use Magento\Framework\Encryption\EncryptorInterface as Encryptor;
use Magento\Framework\Encryption\Helper\Security;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\InvalidEmailOrPasswordException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\State\ExpiredException;
use Magento\Framework\Exception\State\InputMismatchException;
use Magento\Framework\Exception\State\InvalidTransitionException;
use Magento\Framework\Exception\State\UserLockedException;
use Magento\Framework\Intl\DateTimeFactory;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Math\Random;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Framework\Registry;
use Magento\Framework\Session\SaveHandlerInterface;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Stdlib\DateTime;
use Magento\Framework\Stdlib\StringUtils as StringHelper;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface as PsrLogger;
/**
* Handle various customer account actions
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyFields)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.CookieAndSessionMisuse)
*/
class AccountManagement implements AccountManagementInterface
{
/**
* System Configuration Path for Enable/Disable Login at Guest Checkout
*/
public const GUEST_CHECKOUT_LOGIN_OPTION_SYS_CONFIG = 'checkout/options/enable_guest_checkout_login';
/**
* Configuration paths for create account email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_REGISTER_EMAIL_TEMPLATE = 'customer/create_account/email_template';
/**
* Configuration paths for register no password email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_REGISTER_NO_PASSWORD_EMAIL_TEMPLATE = 'customer/create_account/email_no_password_template';
/**
* Configuration paths for remind email identity
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_REGISTER_EMAIL_IDENTITY = 'customer/create_account/email_identity';
/**
* Configuration paths for remind email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_REMIND_EMAIL_TEMPLATE = 'customer/password/remind_email_template';
/**
* Configuration paths for forgot email email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'customer/password/forgot_email_template';
/**
* Configuration paths for forgot email identity
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_FORGOT_EMAIL_IDENTITY = 'customer/password/forgot_email_identity';
/**
* Configuration paths for account confirmation required
*
* @deprecated Get rid of Helpers in Password Security Management
* @see AccountConfirmation::XML_PATH_IS_CONFIRM
*/
public const XML_PATH_IS_CONFIRM = 'customer/create_account/confirm';
/**
* Configuration paths for account confirmation email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_CONFIRM_EMAIL_TEMPLATE = 'customer/create_account/email_confirmation_template';
/**
* Configuration paths for confirmation confirmed email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_CONFIRMED_EMAIL_TEMPLATE = 'customer/create_account/email_confirmed_template';
/**
* Constants for the type of new account email to be sent
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED
*/
public const NEW_ACCOUNT_EMAIL_REGISTERED = 'registered';
/**
* Welcome email, when password setting is required
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED
*/
public const NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD = 'registered_no_password';
/**
* Welcome email, when confirmation is enabled
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED
*/
public const NEW_ACCOUNT_EMAIL_CONFIRMATION = 'confirmation';
/**
* Confirmation email, when account is confirmed
*
* @deprecated Get rid of Helpers in Password Security Management
* @see EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED
*/
public const NEW_ACCOUNT_EMAIL_CONFIRMED = 'confirmed';
/**
* Constants for types of emails to send out.
* pdl:
* forgot, remind, reset email templates
*/
public const EMAIL_REMINDER = 'email_reminder';
public const EMAIL_RESET = 'email_reset';
/**
* Configuration path to customer password minimum length
*/
public const XML_PATH_MINIMUM_PASSWORD_LENGTH = 'customer/password/minimum_password_length';
/**
* Configuration path to customer password required character classes number
*/
public const XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER = 'customer/password/required_character_classes_number';
/**
* Configuration path to customer reset password email template
*
* @deprecated Get rid of Helpers in Password Security Management
* @see Magento/Customer/Model/EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE
*/
public const XML_PATH_RESET_PASSWORD_TEMPLATE = 'customer/password/reset_password_template';
/**
* Minimum password length
*
* @deprecated Get rid of Helpers in Password Security Management
* @see \Magento\Customer\Model\AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH
*/
public const MIN_PASSWORD_LENGTH = 6;
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
public const ADMIN_RESOURCE = 'Magento_Customer::manage';
/**
* @var CustomerFactory
*/
private $customerFactory;
/**
* @var ValidationResultsInterfaceFactory
*/
private $validationResultsDataFactory;
/**
* @var ManagerInterface
*/
private $eventManager;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var Random
*/
private $mathRandom;
/**
* @var Validator
*/
private $validator;
/**
* @var AddressRepositoryInterface
*/
private $addressRepository;
/**
* @var CustomerMetadataInterface
*/
private $customerMetadataService;
/**
* @var PsrLogger
*/
protected $logger;
/**
* @var Encryptor
*/
private $encryptor;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var ConfigShare
*/
private $configShare;
/**
* @var StringHelper
*/
protected $stringHelper;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var TransportBuilder
*/
private $transportBuilder;
/**
* @var DataObjectProcessor
*/
protected $dataProcessor;
/**
* @var Registry
*/
protected $registry;
/**
* @var CustomerViewHelper
*/
protected $customerViewHelper;
/**
* @var DateTime
*/
protected $dateTime;
/**
* @var ObjectFactory
*/
protected $objectFactory;
/**
* @var ExtensibleDataObjectConverter
*/
protected $extensibleDataObjectConverter;
/**
* @var CustomerModel
*/
protected $customerModel;
/**
* @var AuthenticationInterface
*/
protected $authentication;
/**
* @var EmailNotificationInterface
*/
private $emailNotification;
/**
* @var Backend
*/
private $eavValidator;
/**
* @var CredentialsValidator
*/
private $credentialsValidator;
/**
* @var DateTimeFactory
*/
private $dateTimeFactory;
/**
* @var AccountConfirmation
*/
private $accountConfirmation;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var AddressRegistry
*/
private $addressRegistry;
/**
* @var AllowedCountries
*/
private $allowedCountriesReader;
/**
* @var GetCustomerByToken
*/
private $getByToken;
/**
* @var SessionCleanerInterface
*/
private $sessionCleaner;
/**
* @var AuthorizationInterface
*/
private $authorization;
/**
* @var CustomerLogger
*/
private CustomerLogger $customerLogger;
/**
* @var Authenticate
*/
private Authenticate $authenticate;
/**
* @var ConfirmationEmailLogManagementInterface
*/
private ConfirmationEmailLogManagementInterface $confirmationEmailLogManagement;
/**
* @param CustomerFactory $customerFactory
* @param ManagerInterface $eventManager
* @param StoreManagerInterface $storeManager
* @param Random $mathRandom
* @param Validator $validator
* @param ValidationResultsInterfaceFactory $validationResultsDataFactory
* @param AddressRepositoryInterface $addressRepository
* @param CustomerMetadataInterface $customerMetadataService
* @param CustomerRegistry $customerRegistry
* @param PsrLogger $logger
* @param Encryptor $encryptor
* @param ConfigShare $configShare
* @param StringHelper $stringHelper
* @param CustomerRepositoryInterface $customerRepository
* @param ScopeConfigInterface $scopeConfig
* @param TransportBuilder $transportBuilder
* @param DataObjectProcessor $dataProcessor
* @param Registry $registry
* @param CustomerViewHelper $customerViewHelper
* @param DateTime $dateTime
* @param CustomerModel $customerModel
* @param ObjectFactory $objectFactory
* @param ExtensibleDataObjectConverter $extensibleDataObjectConverter
* @param CredentialsValidator|null $credentialsValidator
* @param DateTimeFactory|null $dateTimeFactory
* @param AccountConfirmation|null $accountConfirmation
* @param SessionManagerInterface|null $sessionManager
* @param SaveHandlerInterface|null $saveHandler
* @param CollectionFactory|null $visitorCollectionFactory
* @param SearchCriteriaBuilder|null $searchCriteriaBuilder
* @param AddressRegistry|null $addressRegistry
* @param GetCustomerByToken|null $getByToken
* @param AllowedCountries|null $allowedCountriesReader
* @param SessionCleanerInterface|null $sessionCleaner
* @param AuthorizationInterface|null $authorization
* @param AuthenticationInterface|null $authentication
* @param Backend|null $eavValidator
* @param CustomerLogger|null $customerLogger
* @param Authenticate|null $authenticate
* @param ConfirmationEmailLogManagementInterface|null $confirmationEmailLogManagement
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.LongVariable)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __construct(
CustomerFactory $customerFactory,
ManagerInterface $eventManager,
StoreManagerInterface $storeManager,
Random $mathRandom,
Validator $validator,
ValidationResultsInterfaceFactory $validationResultsDataFactory,
AddressRepositoryInterface $addressRepository,
CustomerMetadataInterface $customerMetadataService,
CustomerRegistry $customerRegistry,
PsrLogger $logger,
Encryptor $encryptor,
ConfigShare $configShare,
StringHelper $stringHelper,
CustomerRepositoryInterface $customerRepository,
ScopeConfigInterface $scopeConfig,
TransportBuilder $transportBuilder,
DataObjectProcessor $dataProcessor,
Registry $registry,
CustomerViewHelper $customerViewHelper,
DateTime $dateTime,
CustomerModel $customerModel,
ObjectFactory $objectFactory,
ExtensibleDataObjectConverter $extensibleDataObjectConverter,
?CredentialsValidator $credentialsValidator = null,
?DateTimeFactory $dateTimeFactory = null,
?AccountConfirmation $accountConfirmation = null,
?SessionManagerInterface $sessionManager = null,
?SaveHandlerInterface $saveHandler = null,
?CollectionFactory $visitorCollectionFactory = null,
?SearchCriteriaBuilder $searchCriteriaBuilder = null,
?AddressRegistry $addressRegistry = null,
?GetCustomerByToken $getByToken = null,
?AllowedCountries $allowedCountriesReader = null,
?SessionCleanerInterface $sessionCleaner = null,
?AuthorizationInterface $authorization = null,
?AuthenticationInterface $authentication = null,
?Backend $eavValidator = null,
?CustomerLogger $customerLogger = null,
?Authenticate $authenticate = null,
?ConfirmationEmailLogManagementInterface $confirmationEmailLogManagement = null
) {
$this->customerFactory = $customerFactory;
$this->eventManager = $eventManager;
$this->storeManager = $storeManager;
$this->mathRandom = $mathRandom;
$this->validator = $validator;
$this->validationResultsDataFactory = $validationResultsDataFactory;
$this->addressRepository = $addressRepository;
$this->customerMetadataService = $customerMetadataService;
$this->customerRegistry = $customerRegistry;
$this->logger = $logger;
$this->encryptor = $encryptor;
$this->configShare = $configShare;
$this->stringHelper = $stringHelper;
$this->customerRepository = $customerRepository;
$this->scopeConfig = $scopeConfig;
$this->transportBuilder = $transportBuilder;
$this->dataProcessor = $dataProcessor;
$this->registry = $registry;
$this->customerViewHelper = $customerViewHelper;
$this->dateTime = $dateTime;
$this->customerModel = $customerModel;
$this->objectFactory = $objectFactory;
$this->extensibleDataObjectConverter = $extensibleDataObjectConverter;
$objectManager = ObjectManager::getInstance();
$this->credentialsValidator =
$credentialsValidator ?: $objectManager->get(CredentialsValidator::class);
$this->dateTimeFactory = $dateTimeFactory ?: $objectManager->get(DateTimeFactory::class);
$this->accountConfirmation = $accountConfirmation ?: $objectManager
->get(AccountConfirmation::class);
$this->searchCriteriaBuilder = $searchCriteriaBuilder
?: $objectManager->get(SearchCriteriaBuilder::class);
$this->addressRegistry = $addressRegistry
?: $objectManager->get(AddressRegistry::class);
$this->getByToken = $getByToken
?: $objectManager->get(GetCustomerByToken::class);
$this->allowedCountriesReader = $allowedCountriesReader
?: $objectManager->get(AllowedCountries::class);
$this->sessionCleaner = $sessionCleaner ?? $objectManager->get(SessionCleanerInterface::class);
$this->authorization = $authorization ?? $objectManager->get(AuthorizationInterface::class);
$this->authentication = $authentication ?? $objectManager->get(AuthenticationInterface::class);
$this->eavValidator = $eavValidator ?? $objectManager->get(Backend::class);
$this->customerLogger = $customerLogger ?? $objectManager->get(CustomerLogger::class);
$this->authenticate = $authenticate ?? $objectManager->get(Authenticate::class);
$this->confirmationEmailLogManagement = $confirmationEmailLogManagement ?? $objectManager->get(
ConfirmationEmailLogManagementInterface::class
);
}
/**
* @inheritdoc
*/
public function resendConfirmation($email, $websiteId = null, $redirectUrl = '')
{
$customer = $this->customerRepository->get($email, $websiteId);
if (!$customer->getConfirmation()) {
throw new InvalidTransitionException(__("Confirmation isn't needed."));
}
if (!$this->confirmationEmailLogManagement->canSend((int) $customer->getId())) {
throw new LocalizedException(__("You have reached the limit for confirmation emails."));
}
try {
$this->getEmailNotification()->newAccount(
$customer,
self::NEW_ACCOUNT_EMAIL_CONFIRMATION,
$redirectUrl,
$this->storeManager->getStore()->getId()
);
} catch (MailException $e) {
// If we are not able to send a new account email, this should be ignored
$this->logger->critical($e);
return false;
}
return true;
}
/**
* @inheritdoc
*/
public function activate($email, $confirmationKey)
{
$customer = $this->customerRepository->get($email);
return $this->activateCustomer($customer, $confirmationKey);
}
/**
* @inheritdoc
*/
public function activateById($customerId, $confirmationKey)
{
$customer = $this->customerRepository->getById($customerId);
return $this->activateCustomer($customer, $confirmationKey);
}
/**
* Activate a customer account using a key that was sent in a confirmation email.
*
* @param CustomerInterface $customer
* @param string $confirmationKey
* @return CustomerInterface
* @throws InputException
* @throws InputMismatchException
* @throws InvalidTransitionException
* @throws LocalizedException
* @throws NoSuchEntityException
*/
private function activateCustomer($customer, $confirmationKey)
{
// check if customer is inactive
if (!$customer->getConfirmation()) {
throw new InvalidTransitionException(__('The account is already active.'));
}
if ($customer->getConfirmation() !== $confirmationKey) {
throw new InputMismatchException(__('The confirmation token is invalid. Verify the token and try again.'));
}
$customer->setConfirmation(null);
// No need to validate customer and customer address while activating customer
$this->setIgnoreValidationFlag($customer);
$this->customerRepository->save($customer);
$customerLastLoginAt = $this->customerLogger->get((int)$customer->getId())->getLastLoginAt();
if (!$customerLastLoginAt) {
$this->getEmailNotification()->newAccount(
$customer,
'confirmed',
'',
$this->storeManager->getStore()->getId()
);
}
$this->confirmationEmailLogManagement->deleteByCustomerId((int) $customer->getId());
return $customer;
}
/**
* @inheritdoc
*/
public function authenticate($username, $password)
{
return $this->authenticate->execute((string) $username, (string) $password);
}
/**
* @inheritdoc
*/
public function validateResetPasswordLinkToken($customerId, $resetPasswordLinkToken)
{
$this->validateResetPasswordToken($customerId, $resetPasswordLinkToken);
return true;
}
/**
* @inheritdoc
*/
public function initiatePasswordReset($email, $template, $websiteId = null)
{
if ($websiteId === null) {
$websiteId = $this->storeManager->getStore()->getWebsiteId();
}
// load customer by email
$customer = $this->customerRepository->get($email, $websiteId);
// No need to validate customer address while saving customer reset password token
$this->disableAddressValidation($customer);
$newPasswordToken = $this->mathRandom->getUniqueHash();
$this->changeResetPasswordLinkToken($customer, $newPasswordToken);
try {
switch ($template) {
case AccountManagement::EMAIL_REMINDER:
$this->getEmailNotification()->passwordReminder($customer);
break;
case AccountManagement::EMAIL_RESET:
$this->getEmailNotification()->passwordResetConfirmation($customer);
break;
default:
$this->handleUnknownTemplate($template);
break;
}
return true;
} catch (MailException $e) {
// If we are not able to send a reset password email, this should be ignored
$this->logger->critical($e);
}
return false;
}
/**
* Handle not supported template
*
* @param string $template
* @throws InputException
*/
private function handleUnknownTemplate($template)
{
throw new InputException(
__(
'Invalid value of "%value" provided for the %fieldName field. '
. 'Possible values: %template1 or %template2.',
[
'value' => $template,
'fieldName' => 'template',
'template1' => AccountManagement::EMAIL_REMINDER,
'template2' => AccountManagement::EMAIL_RESET
]
)
);
}
/**
* @inheritdoc
*/
public function resetPassword($email, $resetToken, $newPassword)
{
if (!$email) {
$params = ['fieldName' => 'email'];
throw new InputException(__('"%fieldName" is required. Enter and try again.', $params));
} else {
$customer = $this->customerRepository->get($email);
}
// No need to validate customer and customer address while saving customer reset password token
$this->disableAddressValidation($customer);
$this->setIgnoreValidationFlag($customer);
//Validate Token and new password strength
$this->validateResetPasswordToken((int)$customer->getId(), $resetToken);
$this->credentialsValidator->checkPasswordDifferentFromEmail(
$email,
$newPassword
);
$this->checkPasswordStrength($newPassword);
//Update secure data
$customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
$customerSecure->setRpToken(null);
$customerSecure->setRpTokenCreatedAt(null);
$customerSecure->setPasswordHash($this->createPasswordHash($newPassword));
$customerSecure->setFailuresNum(0);
$customerSecure->setFirstFailure(null);
$customerSecure->setLockExpires(null);
$this->sessionCleaner->clearFor((int)$customer->getId());
$this->customerRepository->save($customer);
return true;
}
/**
* Make sure that password complies with minimum security requirements.
*
* @param string $password
* @return void
* @throws InputException
*/
protected function checkPasswordStrength($password)
{
$length = $this->stringHelper->strlen($password);
if ($length > self::MAX_PASSWORD_LENGTH) {
throw new InputException(
__(
'Please enter a password with at most %1 characters.',
self::MAX_PASSWORD_LENGTH
)
);
}
$configMinPasswordLength = $this->getMinPasswordLength();
if ($length < $configMinPasswordLength) {
throw new InputException(
__(
'The password needs at least %1 characters. Create a new password and try again.',
$configMinPasswordLength
)
);
}
$trimmedPassLength = $this->stringHelper->strlen($password === null ? '' : trim($password));
if ($trimmedPassLength != $length) {
throw new InputException(
__("The password can't begin or end with a space. Verify the password and try again.")
);
}
$requiredCharactersCheck = $this->makeRequiredCharactersCheck($password);
if ($requiredCharactersCheck !== 0) {
throw new InputException(
__(
'Minimum of different classes of characters in password is %1.' .
' Classes of characters: Lower Case, Upper Case, Digits, Special Characters.',
$requiredCharactersCheck
)
);
}
}
/**
* Check password for presence of required character sets
*
* @param string $password
* @return int
*/
protected function makeRequiredCharactersCheck($password)
{
$counter = 0;
$requiredNumber = $this->scopeConfig->getValue(self::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER);
$return = 0;
if ($password !== null) {
if (preg_match('/[0-9]+/', $password)) {
$counter++;
}
if (preg_match('/[A-Z]+/', $password)) {
$counter++;
}
if (preg_match('/[a-z]+/', $password)) {
$counter++;
}
if (preg_match('/[^a-zA-Z0-9]+/', $password)) {
$counter++;
}
}
if ($counter < $requiredNumber) {
$return = $requiredNumber;
}
return $return;
}
/**
* Retrieve minimum password length
*
* @return int
*/
protected function getMinPasswordLength()
{
return $this->scopeConfig->getValue(self::XML_PATH_MINIMUM_PASSWORD_LENGTH);
}
/**
* @inheritdoc
*/
public function getConfirmationStatus($customerId)
{
// load customer by id
$customer = $this->customerRepository->getById($customerId);
return $this->isConfirmationRequired($customer)
? $customer->getConfirmation() ? self::ACCOUNT_CONFIRMATION_REQUIRED : self::ACCOUNT_CONFIRMED
: self::ACCOUNT_CONFIRMATION_NOT_REQUIRED;
}
/**
* @inheritdoc
*
* @throws LocalizedException
*/
public function createAccount(CustomerInterface $customer, $password = null, $redirectUrl = '')
{
$customerEmail = $customer->getEmail();
if ($customerEmail === null) {
throw new LocalizedException(
__("The email address is required to create a customer account.")
);
}
if ($password !== null) {
$this->checkPasswordStrength($password);
try {
$this->credentialsValidator->checkPasswordDifferentFromEmail($customerEmail, $password);
} catch (InputException $e) {
throw new LocalizedException(
__("The password can't be the same as the email address. Create a new password and try again.")
);
}
$hash = $this->createPasswordHash($password);
} else {
$hash = null;
}
return $this->createAccountWithPasswordHash($customer, $hash, $redirectUrl);
}
/**
* @inheritdoc
*
* @throws InputMismatchException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function createAccountWithPasswordHash(CustomerInterface $customer, $hash, $redirectUrl = '')
{
// This logic allows an existing customer to be added to a different store. No new account is created.
// The plan is to move this logic into a new method called something like 'registerAccountWithStore'
if ($customer->getId()) {
$customer = $this->customerRepository->get($customer->getEmail());
$websiteId = $customer->getWebsiteId();
if ($this->isCustomerInStore($websiteId, $customer->getStoreId())) {
throw new InputException(__('This customer already exists in this store.'));
}
// Existing password hash will be used from secured customer data registry when saving customer
}
// Make sure we have a storeId to associate this customer with.
if (!$customer->getStoreId()) {
if ($customer->getWebsiteId()) {
$storeId = null;
$website = $this->storeManager->getWebsite($customer->getWebsiteId());
if ($website->getDefaultStore()) {
$storeId = $website->getDefaultStore()->getId();
}
} else {
$this->storeManager->setCurrentStore(null);
$storeId = $this->storeManager->getStore()->getId();
}
$customer->setStoreId($storeId);
}
// Associate website_id with customer
if (!$customer->getWebsiteId()) {
$websiteId = $this->storeManager->getStore($customer->getStoreId())->getWebsiteId();
$customer->setWebsiteId($websiteId);
}
$this->validateCustomerStoreIdByWebsiteId($customer);
// Update 'created_in' value with actual store name
if ($customer->getId() === null) {
$storeName = $this->storeManager->getStore($customer->getStoreId())->getName();
$customer->setCreatedIn($storeName);
}
$customerAddresses = $customer->getAddresses() ?: [];
$customer->setAddresses(null);
try {
// If customer exists existing hash will be used by Repository
$customer = $this->customerRepository->save($customer, $hash);
} catch (AlreadyExistsException $e) {
throw new InputMismatchException(
__('A customer with the same email address already exists in an associated website.')
);
} catch (LocalizedException $e) {
throw $e;
}
try {
foreach ($customerAddresses as $address) {
if (!$this->isAddressAllowedForWebsite($address, $customer->getStoreId())) {
continue;
}
if ($address->getId()) {
$newAddress = clone $address;
$newAddress->setId(null);
$newAddress->setCustomerId($customer->getId());
$this->addressRepository->save($newAddress);
} else {
$address->setCustomerId($customer->getId());
$this->addressRepository->save($address);
}
}
$this->customerRegistry->remove($customer->getId());
} catch (InputException $e) {
$this->customerRepository->delete($customer);
throw $e;
}
$customer = $this->customerRepository->getById($customer->getId());
$newLinkToken = $this->mathRandom->getUniqueHash();
$this->changeResetPasswordLinkToken($customer, $newLinkToken);
$this->sendEmailConfirmation($customer, $redirectUrl);
return $customer;
}
/**
* @inheritdoc
*/
public function getDefaultBillingAddress($customerId)
{
$customer = $this->customerRepository->getById($customerId);
return $this->getAddressById($customer, $customer->getDefaultBilling());
}
/**
* @inheritdoc
*/
public function getDefaultShippingAddress($customerId)
{
$customer = $this->customerRepository->getById($customerId);
return $this->getAddressById($customer, $customer->getDefaultShipping());
}
/**
* Send either confirmation or welcome email after an account creation
*
* @param CustomerInterface $customer
* @param string $redirectUrl