Test Failed
Push — develop ( 28e0cd...307ddb )
by Daniel
05:05
created

PasswordManager::persistPlainPassword()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Security;
4
5
use Silverback\ApiComponentBundle\Entity\User\User;
6
use Silverback\ApiComponentBundle\Mailer\Mailer;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Silverback\ApiComponentBundle\Exception\InvalidEntityException;
9
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
10
use Symfony\Component\Validator\Validator\ValidatorInterface;
11
12
class PasswordManager
13
{
14
    private $mailer;
15
    private $entityManager;
16
    private $validator;
17
    private $passwordEncoder;
18
    private $tokenGenerator;
19
    private $tokenTtl;
20
21
    public function __construct(
22
        Mailer $mailer,
23
        EntityManagerInterface $entityManager,
24
        ValidatorInterface $validator,
25
        UserPasswordEncoderInterface $passwordEncoder,
26
        TokenGenerator $tokenGenerator,
27
        int $tokenTtl
28
    ) {
29
        $this->mailer = $mailer;
30
        $this->entityManager = $entityManager;
31
        $this->validator = $validator;
32
        $this->passwordEncoder = $passwordEncoder;
33
        $this->tokenGenerator = $tokenGenerator;
34
        $this->tokenTtl = $tokenTtl;
35
    }
36
37
    public function requestResetEmail(User $user, string $resetUrl): void
38
    {
39
        if ($user->isPasswordRequestLimitReached($this->tokenTtl)) {
40
            return;
41
        }
42
        $user->setPasswordResetConfirmationToken($this->tokenGenerator->generateToken());
43
        $user->setPasswordRequestedAt(new \DateTime());
44
        if ($this->mailer->passwordResetEmail($user, $resetUrl)) {
45
            $this->entityManager->flush();
46
        }
47
    }
48
49
    /**
50
     * @param User $user
51
     * @param string $newPassword
52
     */
53
    public function passwordReset(User $user, string $newPassword): void
54
    {
55
        $user->setPlainPassword($newPassword);
56
        $user->setPasswordResetConfirmationToken(null);
57
        $user->setPasswordRequestedAt(null);
58
        $errors = $this->validator->validate($user, null, ['password_reset']);
59
        if (\count($errors)) {
60
            throw new InvalidEntityException($errors, 'The password entered is not valid');
61
        }
62
        $this->persistPlainPassword($user);
63
    }
64
65
    public function persistPlainPassword(User $user): User
66
    {
67
        $password = $this->passwordEncoder->encodePassword($user, $user->getPlainPassword());
68
        $user->setPassword($password);
69
        $this->entityManager->persist($user);
70
        $this->entityManager->flush();
71
        $user->eraseCredentials();
72
        return $user;
73
    }
74
}
75