SendPasswordResetLink::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 31
rs 9.6
c 0
b 0
f 0
cc 4
nc 2
nop 1
1
<?php
2
3
namespace ProjetNormandie\UserBundle\Controller\ResetPassword;
4
5
use DateTime;
6
use Exception;
7
use ProjetNormandie\UserBundle\Manager\UserManager;
8
use ProjetNormandie\UserBundle\Util\TokenGenerator;
9
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpKernel\Attribute\AsController;
13
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
14
use Symfony\Contracts\Translation\TranslatorInterface;
15
use Symfony\Component\Mailer\MailerInterface;
16
use Symfony\Component\Mime\Email;
17
18
#[AsController]
19
class SendPasswordResetLink extends AbstractController
20
{
21
    public function __construct(
22
        private readonly UserManager $userManager,
23
        private readonly TokenGenerator $tokenGenerator,
24
        private readonly MailerInterface $mailer,
25
        private readonly TranslatorInterface $translator,
26
        private readonly int $retryTtl = 7200
27
    ) {
28
    }
29
30
31
    /**
32
     * @param Request $request
33
     * @return JsonResponse
34
     * @throws TransportExceptionInterface
35
     * @throws Exception
36
     */
37
    public function __invoke(Request $request): JsonResponse
38
    {
39
        $data = json_decode($request->getContent(), true);
40
        $email = $data['email'];
41
        $callBackUrl = $data['callBackUrl'];
42
43
        $user = $this->userManager->findUserByUsernameOrEmail($email);
44
        if ($user && (null === $user->getPasswordRequestedAt() || $user->isPasswordRequestExpired($this->retryTtl))) {
45
            $user->setConfirmationToken($this->tokenGenerator->generateToken());
46
            $body = sprintf(
47
                $this->translator->trans('password_reset.message', [], 'email', $user->getLanguage()),
48
                $user->getUsername(),
49
                ($request->server->get('HTTP_ORIGIN') ?? null) .
50
                str_replace('[token]', $user->getConfirmationToken(), $callBackUrl)
51
            );
52
53
            ;
54
55
            $email = (new Email())
56
                ->to($user->getEmail())
57
                ->subject($this->translator->trans('password_reset.subject', [], 'email', $user->getLanguage()))
58
                ->text($body)
59
                ->html($body);
60
61
            $this->mailer->send($email);
62
63
            $user->setPasswordRequestedAt(new DateTime());
64
            $this->userManager->updateUser($user);
65
        }
66
67
        return new JsonResponse(['success' => true]);
68
    }
69
}
70