src/Controller/ResetPasswordController.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  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 SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. #[Route('/reset-password')]
  20. class ResetPasswordController extends AbstractController
  21. {
  22.     use ResetPasswordControllerTrait;
  23.     public function __construct(
  24.         private ResetPasswordHelperInterface $resetPasswordHelper,
  25.         private EntityManagerInterface $entityManager
  26.     ) {
  27.     }
  28.     /**
  29.      * Display & process form to request a password reset.
  30.      */
  31.     #[Route(''name'app_forgot_password_request')]
  32.     public function request(Request $requestMailerInterface $mailer): Response
  33.     {
  34.         $form $this->createForm(ResetPasswordRequestFormType::class);
  35.         $form->handleRequest($request);
  36.         if ($form->isSubmitted() && $form->isValid()) {
  37.             return $this->processSendingPasswordResetEmail(
  38.                 $form->get('email')->getData(),
  39.                 $mailer
  40.             );
  41.         }
  42.         return $this->render('reset_password/request.html.twig', [
  43.             'requestForm' => $form->createView(),
  44.         ]);
  45.     }
  46.     /**
  47.      * Confirmation page after a user has requested a password reset.
  48.      */
  49.     #[Route('/registration_confirmed'name'app_registration_confirmed')]
  50.     public function registrationConfirmed(): Response
  51.     {
  52.         return $this->render('reset_password/registration_confirmed.html.twig');
  53.     }
  54.     /**
  55.      * Confirmation page after a user has succesfully changed password
  56.      */
  57.     #[Route('/password_changed'name'app_password_changed')]
  58.     public function passwordChanged(): Response
  59.     {
  60.         return $this->render('reset_password/password_changed.html.twig');
  61.     }
  62.     /**
  63.      * Confirmation page after a user has requested a password reset.
  64.      */
  65.     #[Route('/check-email'name'app_check_email')]
  66.     public function checkEmail(): Response
  67.     {
  68.         // Generate a fake token if the user does not exist or someone hit this page directly.
  69.         // This prevents exposing whether or not a user was found with the given email address or not
  70.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  71.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  72.         }
  73.         return $this->render('reset_password/check_email.html.twig', [
  74.             'resetToken' => $resetToken,
  75.         ]);
  76.     }
  77.     /**
  78.      * Validates and process the reset URL that the user clicked in their email.
  79.      */
  80.     #[Route('/confirm/{token}'name'app_confirm_password')]
  81.     public function confirm(
  82.         Request $request,
  83.         UserPasswordHasherInterface $passwordHasher,
  84.         string $token null
  85.     ): Response {
  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.             return $this->redirectToRoute('app_confirm_password');
  91.         }
  92.         $token $this->getTokenFromSession();
  93.         if (null === $token) {
  94.             throw $this->createNotFoundException("Aucun token d'initialisation de compte n'a été trouvé.");
  95.         }
  96.         try {
  97.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  98.         } catch (ResetPasswordExceptionInterface $e) {
  99.             $this->addFlash(
  100.                 'error',
  101.                 "Le lien d'initialisation de votre compte a expiré, veuillez réinitialiser votre mot de passe."
  102.             );
  103.             return $this->redirectToRoute('app_forgot_password_request');
  104.         }
  105.         // The token is valid; allow the user to change their password.
  106.         $form $this->createForm(ChangePasswordFormType::class);
  107.         $form->handleRequest($request);
  108.         if ($form->isSubmitted() && $form->isValid()) {
  109.             // A password reset token should be used only once, remove it.
  110.             $this->resetPasswordHelper->removeResetRequest($token);
  111.             // Encode(hash) the plain password, and set it.
  112.             $encodedPassword $passwordHasher->hashPassword(
  113.                 $user,
  114.                 $form->get('plainPassword')->getData()
  115.             );
  116.             $user->setPassword($encodedPassword);
  117.             $this->entityManager->flush();
  118.             // The session is cleaned up after the password has been changed.
  119.             $this->cleanSessionAfterReset();
  120.             // $this->addFlash('success', 'Votre mot de passe a correctement été mis à jour,
  121.             //                             vous pouvez désormais vous connecter');
  122.             return $this->redirectToRoute('app_registration_confirmed');
  123.         }
  124.         return $this->render('reset_password/confirm.html.twig', [
  125.             'resetForm' => $form->createView(),
  126.         ]);
  127.     }
  128.     /**
  129.      * Validates and process the reset URL that the user clicked in their email.
  130.      */
  131.     #[Route('/reset/{token}'name'app_reset_password')]
  132.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $token null): Response
  133.     {
  134.         if ($token) {
  135.             // We store the token in session and remove it from the URL, to avoid the URL being
  136.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  137.             $this->storeTokenInSession($token);
  138.             return $this->redirectToRoute('app_reset_password');
  139.         }
  140.         $token $this->getTokenFromSession();
  141.         if (null === $token) {
  142.             throw $this->createNotFoundException("Aucun token de réinitialisation de mot de passe n'a été trouvé.");
  143.         }
  144.         try {
  145.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  146.         } catch (ResetPasswordExceptionInterface $e) {
  147.             $this->addFlash(
  148.                 'error',
  149.                 "Le lien de réinitialisation de votre mot de passe a expiré, veuillez rééssayer."
  150.             );
  151.             return $this->redirectToRoute('app_forgot_password_request');
  152.         }
  153.         // The token is valid; allow the user to change their password.
  154.         $form $this->createForm(ChangePasswordFormType::class);
  155.         $form->handleRequest($request);
  156.         if ($form->isSubmitted() && $form->isValid()) {
  157.             // A password reset token should be used only once, remove it.
  158.             $this->resetPasswordHelper->removeResetRequest($token);
  159.             // Encode(hash) the plain password, and set it.
  160.             $encodedPassword $passwordHasher->hashPassword(
  161.                 $user,
  162.                 $form->get('plainPassword')->getData()
  163.             );
  164.             $user->setPassword($encodedPassword);
  165.             $this->entityManager->flush();
  166.             // The session is cleaned up after the password has been changed.
  167.             $this->cleanSessionAfterReset();
  168.             // $this->addFlash('success', 'Votre mot de passe a correctement été réinitialisé,
  169.             //                             vous pouvez désormais vous connecter');
  170.             return $this->redirectToRoute('app_password_changed');
  171.         }
  172.         return $this->render('reset_password/reset.html.twig', [
  173.             'resetForm' => $form->createView(),
  174.         ]);
  175.     }
  176.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  177.     {
  178.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  179.             'email' => $emailFormData,
  180.         ]);
  181.         // Do not reveal whether a user account was found or not.
  182.         if (!$user) {
  183.             return $this->redirectToRoute('app_check_email');
  184.         }
  185.         try {
  186.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  187.         } catch (ResetPasswordExceptionInterface $e) {
  188.             // If you want to tell the user why a reset email was not sent, uncomment
  189.             // the lines below and change the redirect to 'app_forgot_password_request'.
  190.             // Caution: This may reveal if a user is registered or not.
  191.             //
  192.             // $this->addFlash('reset_password_error', sprintf(
  193.             //     '%s - %s',
  194.             //     ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
  195.             //     $e->getReason()
  196.             // ));
  197.             return $this->redirectToRoute('app_check_email');
  198.         }
  199.         $email = (new TemplatedEmail())
  200.             ->from(new Address('no-reply.dotafinance@laposte.fr''no-reply DotaFinance'))
  201.             ->to($user->getEmail())
  202.             ->subject('Réinitialiser votre mot de passe - DotaFinance')
  203.             ->textTemplate('email/reset_password_email.txt.twig')
  204.             ->htmlTemplate('email/reset_password_email.html.twig')
  205.             ->context([
  206.                 'resetToken' => $resetToken,
  207.             ])
  208.         ;
  209.         $mailer->send($email);
  210.         // Store the token object in session for retrieval in check-email route.
  211.         $this->setTokenObjectInSession($resetToken);
  212.         return $this->redirectToRoute('app_check_email');
  213.     }
  214. }