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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Observer;
use Magento\Customer\Model\Customer;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\CustomerRegistry;
/**
* Class observer UpgradeCustomerPasswordObserver to upgrade customer password hash when customer has logged in
*/
class UpgradeCustomerPasswordObserver implements ObserverInterface
{
/**
* Encryption model
*
* @var EncryptorInterface
*/
protected $encryptor;
/**
* @var CustomerRegistry
*/
private $customerRegistry;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* @param EncryptorInterface $encryptor
* @param CustomerRegistry $customerRegistry
* @param CustomerRepositoryInterface $customerRepository
*/
public function __construct(
EncryptorInterface $encryptor,
CustomerRegistry $customerRegistry,
CustomerRepositoryInterface $customerRepository
) {
$this->encryptor = $encryptor;
$this->customerRegistry = $customerRegistry;
$this->customerRepository = $customerRepository;
}
/**
* Upgrade customer password hash when customer has logged in
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$password = $observer->getEvent()->getData('password');
/** @var \Magento\Customer\Model\Customer $model */
$model = $observer->getEvent()->getData('model');
$customer = $this->customerRepository->getById($model->getId());
$customerSecure = $this->customerRegistry->retrieveSecureData($model->getId());
if (!$this->encryptor->validateHashVersion($customerSecure->getPasswordHash(), true)) {
$customerSecure->setPasswordHash($this->encryptor->getHash($password, true));
// No need to validate customer and customer address while upgrading customer password
$this->setIgnoreValidationFlag($customer);
$this->customerRepository->save($customer);
}
}
/**
* Set ignore_validation_flag to skip unnecessary address and customer validation
*
* @param Customer $customer
* @return void
*/
private function setIgnoreValidationFlag($customer)
{
$customer->setData('ignore_validation_flag', true);
}
}