|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Gbere\SimpleAuth\Controller; |
|
6
|
|
|
|
|
7
|
|
|
use DateTime; |
|
8
|
|
|
use Doctrine\ORM\EntityManager; |
|
9
|
|
|
use Doctrine\ORM\OptimisticLockException; |
|
10
|
|
|
use Doctrine\ORM\ORMException; |
|
11
|
|
|
use Exception; |
|
12
|
|
|
use Gbere\SimpleAuth\Entity\User; |
|
13
|
|
|
use Symfony\Bridge\Twig\Mime\NotificationEmail; |
|
14
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
|
15
|
|
|
use Symfony\Component\Form\Extension\Core\Type\EmailType; |
|
16
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
17
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
18
|
|
|
use Symfony\Component\Mailer\Exception\TransportExceptionInterface; |
|
19
|
|
|
use Symfony\Component\Mailer\MailerInterface; |
|
20
|
|
|
use Symfony\Component\Routing\Annotation\Route; |
|
21
|
|
|
|
|
22
|
|
|
final class PasswordRequestController extends AbstractController |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* @Route("/login/password/request", name="gbere_auth_password_request") |
|
26
|
|
|
* |
|
27
|
|
|
* @throws Exception |
|
28
|
|
|
* @throws ORMException |
|
29
|
|
|
* @throws OptimisticLockException |
|
30
|
|
|
* @throws TransportExceptionInterface |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __invoke(Request $request, MailerInterface $mailer): Response |
|
33
|
|
|
{ |
|
34
|
|
|
$builder = $this->createFormBuilder()->add('email', EmailType::class); |
|
35
|
|
|
$form = $builder->getForm(); |
|
36
|
|
|
$form->handleRequest($request); |
|
37
|
|
|
if ($form->isSubmitted() && $form->isValid()) { |
|
38
|
|
|
$email = $form->get('email')->getData(); |
|
39
|
|
|
/** @var EntityManager $manager */ |
|
40
|
|
|
$manager = $this->getDoctrine()->getManager(); |
|
41
|
|
|
/** @var User|null $user */ |
|
42
|
|
|
$user = $manager->getRepository(User::class)->findOneBy(['email' => $email]); |
|
43
|
|
|
if (null !== $user) { |
|
44
|
|
|
$user->generateToken(); |
|
45
|
|
|
$user->setPasswordRequestAt(new DateTime()); |
|
46
|
|
|
$manager->persist($user); |
|
47
|
|
|
$manager->flush(); |
|
48
|
|
|
$mailer->send((new NotificationEmail()) |
|
49
|
|
|
->from($this->getParameter('email.sender')) |
|
50
|
|
|
->to($user->getEmail()) |
|
51
|
|
|
->subject('Password request') |
|
52
|
|
|
->htmlTemplate('emails/password-reset.html.twig') |
|
53
|
|
|
->context(['token' => $user->getConfirmationToken()]) |
|
54
|
|
|
); |
|
55
|
|
|
$this->addFlash('info', sprintf('An email was sent to %s to restore the password', $email)); |
|
56
|
|
|
|
|
57
|
|
|
return $this->redirectToRoute('gbere_auth_login'); |
|
58
|
|
|
} |
|
59
|
|
|
$this->addFlash('warning', sprintf('The email %s isn\'t registered', $email)); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return $this->render('frontend/password-request.html.twig', [ |
|
63
|
|
|
'form' => $form->createView(), |
|
64
|
|
|
]); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|