|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the SymfonyCasts ResetPasswordBundle package. |
| 5 | + * Copyright (c) SymfonyCasts <https://symfonycasts.com/> |
| 6 | + * For the full copyright and license information, please view the LICENSE |
| 7 | + * file that was distributed with this source code. |
| 8 | + */ |
| 9 | + |
| 10 | +namespace App\Controller; |
| 11 | + |
| 12 | +use App\Entity\User; |
| 13 | +use App\Form\ChangePasswordFormType; |
| 14 | +use App\Form\ResetPasswordRequestFormType; |
| 15 | +use Doctrine\ORM\EntityManagerInterface; |
| 16 | +use Symfony\Bridge\Twig\Mime\TemplatedEmail; |
| 17 | +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
| 18 | +use Symfony\Component\HttpFoundation\RedirectResponse; |
| 19 | +use Symfony\Component\HttpFoundation\Request; |
| 20 | +use Symfony\Component\HttpFoundation\Response; |
| 21 | +use Symfony\Component\Mailer\MailerInterface; |
| 22 | +use Symfony\Component\Mime\Address; |
| 23 | +use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; |
| 24 | +use Symfony\Component\Routing\Attribute\Route; |
| 25 | +use Symfony\Contracts\Translation\TranslatorInterface; |
| 26 | +use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait; |
| 27 | +use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface; |
| 28 | +use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface; |
| 29 | + |
| 30 | +#[Route('/reset-password')] |
| 31 | +class ResetPasswordController extends AbstractController |
| 32 | +{ |
| 33 | + use ResetPasswordControllerTrait; |
| 34 | + |
| 35 | + public function __construct( |
| 36 | + private ResetPasswordHelperInterface $resetPasswordHelper, |
| 37 | + private EntityManagerInterface $entityManager |
| 38 | + ) { |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Display & process form to request a password reset. |
| 43 | + */ |
| 44 | + #[Route('', name: 'app_forgot_password_request')] |
| 45 | + public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): Response |
| 46 | + { |
| 47 | + $form = $this->createForm(ResetPasswordRequestFormType::class); |
| 48 | + $form->handleRequest($request); |
| 49 | + |
| 50 | + if ($form->isSubmitted() && $form->isValid()) { |
| 51 | + return $this->processSendingPasswordResetEmail( |
| 52 | + $form->get('email')->getData(), |
| 53 | + $mailer, |
| 54 | + $translator |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + return $this->render('reset_password/request.html.twig', [ |
| 59 | + 'requestForm' => $form, |
| 60 | + ]); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Confirmation page after a user has requested a password reset. |
| 65 | + */ |
| 66 | + #[Route('/check-email', name: 'app_check_email')] |
| 67 | + public function checkEmail(): Response |
| 68 | + { |
| 69 | + // Generate a fake token if the user does not exist or someone hit this page directly. |
| 70 | + // This prevents exposing whether or not a user was found with the given email address or not |
| 71 | + if (null === ($resetToken = $this->getTokenObjectFromSession())) { |
| 72 | + $resetToken = $this->resetPasswordHelper->generateFakeResetToken(); |
| 73 | + } |
| 74 | + |
| 75 | + return $this->render('reset_password/check_email.html.twig', [ |
| 76 | + 'resetToken' => $resetToken, |
| 77 | + ]); |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Validates and process the reset URL that the user clicked in their email. |
| 82 | + */ |
| 83 | + #[Route('/reset/{token}', name: 'app_reset_password')] |
| 84 | + public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, ?string $token = null): Response |
| 85 | + { |
| 86 | + if ($token) { |
| 87 | + // We store the token in session and remove it from the URL, to avoid the URL being |
| 88 | + // loaded in a browser and potentially leaking the token to 3rd party JavaScript. |
| 89 | + $this->storeTokenInSession($token); |
| 90 | + |
| 91 | + return $this->redirectToRoute('app_reset_password'); |
| 92 | + } |
| 93 | + |
| 94 | + $token = $this->getTokenFromSession(); |
| 95 | + |
| 96 | + if (null === $token) { |
| 97 | + throw $this->createNotFoundException('No reset password token found in the URL or in the session.'); |
| 98 | + } |
| 99 | + |
| 100 | + try { |
| 101 | + /** @var User $user */ |
| 102 | + $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token); |
| 103 | + } catch (ResetPasswordExceptionInterface $e) { |
| 104 | + $this->addFlash('reset_password_error', sprintf( |
| 105 | + '%s - %s', |
| 106 | + $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'), |
| 107 | + $translator->trans($e->getReason(), [], 'ResetPasswordBundle') |
| 108 | + )); |
| 109 | + |
| 110 | + return $this->redirectToRoute('app_forgot_password_request'); |
| 111 | + } |
| 112 | + |
| 113 | + // The token is valid; allow the user to change their password. |
| 114 | + $form = $this->createForm(ChangePasswordFormType::class); |
| 115 | + $form->handleRequest($request); |
| 116 | + |
| 117 | + if ($form->isSubmitted() && $form->isValid()) { |
| 118 | + // A password reset token should be used only once, remove it. |
| 119 | + $this->resetPasswordHelper->removeResetRequest($token); |
| 120 | + |
| 121 | + // Encode(hash) the plain password, and set it. |
| 122 | + $encodedPassword = $passwordHasher->hashPassword( |
| 123 | + $user, |
| 124 | + $form->get('plainPassword')->getData() |
| 125 | + ); |
| 126 | + |
| 127 | + $user->setPassword($encodedPassword); |
| 128 | + $this->entityManager->flush(); |
| 129 | + |
| 130 | + // The session is cleaned up after the password has been changed. |
| 131 | + $this->cleanSessionAfterReset(); |
| 132 | + |
| 133 | + return $this->redirectToRoute('app_home'); |
| 134 | + } |
| 135 | + |
| 136 | + return $this->render('reset_password/reset.html.twig', [ |
| 137 | + 'resetForm' => $form, |
| 138 | + ]); |
| 139 | + } |
| 140 | + |
| 141 | + private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse |
| 142 | + { |
| 143 | + $user = $this->entityManager->getRepository(User::class)->findOneBy([ |
| 144 | + 'email' => $emailFormData, |
| 145 | + ]); |
| 146 | + |
| 147 | + // Do not reveal whether a user account was found or not. |
| 148 | + if (!$user) { |
| 149 | + return $this->redirectToRoute('app_check_email'); |
| 150 | + } |
| 151 | + |
| 152 | + try { |
| 153 | + $resetToken = $this->resetPasswordHelper->generateResetToken($user); |
| 154 | + } catch (ResetPasswordExceptionInterface $e) { |
| 155 | + // If you want to tell the user why a reset email was not sent, uncomment |
| 156 | + // the lines below and change the redirect to 'app_forgot_password_request'. |
| 157 | + // Caution: This may reveal if a user is registered or not. |
| 158 | + // |
| 159 | + // $this->addFlash('reset_password_error', sprintf( |
| 160 | + // '%s - %s', |
| 161 | + // $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'), |
| 162 | + // $translator->trans($e->getReason(), [], 'ResetPasswordBundle') |
| 163 | + // )); |
| 164 | + |
| 165 | + return $this->redirectToRoute('app_check_email'); |
| 166 | + } |
| 167 | + |
| 168 | + $email = (new TemplatedEmail()) |
| 169 | + ->from(new Address('bot@example.com', 'SymfonyCasts')) |
| 170 | + ->to($user->getEmail()) |
| 171 | + ->subject('Your password reset request') |
| 172 | + ->htmlTemplate('reset_password/email.html.twig') |
| 173 | + ->context([ |
| 174 | + 'resetToken' => $resetToken, |
| 175 | + ]) |
| 176 | + ; |
| 177 | + |
| 178 | + $mailer->send($email); |
| 179 | + |
| 180 | + // Store the token object in session for retrieval in check-email route. |
| 181 | + $this->setTokenObjectInSession($resetToken); |
| 182 | + |
| 183 | + return $this->redirectToRoute('app_check_email'); |
| 184 | + } |
| 185 | +} |
0 commit comments