1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Knp\RadBundle\Doctrine\Listener; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\EventSubscriber; |
8
|
|
|
use Doctrine\ORM\Events; |
9
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
10
|
|
|
use Doctrine\ORM\Event\PreUpdateEventArgs; |
11
|
|
|
|
12
|
|
|
use Knp\RadBundle\Security\UserInterface; |
13
|
|
|
use Knp\RadBundle\Security\RecoverableUserInterface; |
14
|
|
|
|
15
|
|
|
class PasswordHashListener implements EventSubscriber |
16
|
|
|
{ |
17
|
|
|
private $encoderFactory; |
18
|
|
|
|
19
|
|
|
public function __construct(EncoderFactoryInterface $encoderFactory) |
20
|
|
|
{ |
21
|
|
|
$this->encoderFactory = $encoderFactory; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function getSubscribedEvents() |
25
|
|
|
{ |
26
|
|
|
return array( |
27
|
|
|
Events::prePersist, |
28
|
|
|
Events::preUpdate, |
29
|
|
|
); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function prePersist(LifecycleEventArgs $args) |
33
|
|
|
{ |
34
|
|
|
$entity = $args->getEntity(); |
35
|
|
|
|
36
|
|
|
if (!$entity instanceof UserInterface) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
if (null === $entity->getPlainPassword()) { |
40
|
|
|
return; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$this->updatePasswordHash($entity); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function preUpdate(PreUpdateEventArgs $args) |
47
|
|
|
{ |
48
|
|
|
$entity = $args->getEntity(); |
49
|
|
|
|
50
|
|
|
if (!$entity instanceof UserInterface) { |
51
|
|
|
return; |
52
|
|
|
} |
53
|
|
|
if (null === $entity->getPlainPassword()) { |
54
|
|
|
return; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$this->updatePasswordHash($entity); |
58
|
|
|
|
59
|
|
|
$args->setNewValue('password', $entity->getPassword()); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function updatePasswordHash(UserInterface $entity) |
63
|
|
|
{ |
64
|
|
|
$password = $this->encoderFactory->getEncoder($entity)->encodePassword( |
65
|
|
|
$entity->getPlainPassword(), $entity->getSalt() |
66
|
|
|
); |
67
|
|
|
$entity->setPassword($password); |
68
|
|
|
$entity->eraseCredentials(); |
69
|
|
|
|
70
|
|
|
if ($entity instanceof RecoverableUserInterface) { |
71
|
|
|
$entity->erasePasswordRecoveryKey(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|