src/Controller/Public/ResetPasswordController.php line 39

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