src/Controller/App/ResetPasswordController.php line 42

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