src/Controller/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use App\Service\MailerService;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  13. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  14. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  15. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  16. use function Sentry\captureException;
  17. /**
  18.  * @Route("/reset-password")
  19.  */
  20. class ResetPasswordController extends AbstractController
  21. {
  22.     use ResetPasswordControllerTrait;
  23.     private $resetPasswordHelper;
  24.     /** @var MailerService */
  25.     private $mailer;
  26.     public function __construct(
  27.         ResetPasswordHelperInterface $resetPasswordHelper,
  28.         MailerService $mailerService
  29.     ) {
  30.         $this->resetPasswordHelper $resetPasswordHelper;
  31.         $this->mailer $mailerService;
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      *
  36.      * @Route("", name="app_forgot_password_request")
  37.      * @param Request $request
  38.      * @return Response
  39.      */
  40.     public function request(Request $request): Response
  41.     {
  42.         $form $this->createForm(ResetPasswordRequestFormType::class);
  43.         $form->handleRequest($request);
  44.         if ($form->isSubmitted() && $form->isValid()) {
  45.             return $this->processSendingPasswordResetEmail(
  46.                 $form->get('email')->getData()
  47.             );
  48.         }
  49.         return $this->render('reset_password/request.html.twig', [
  50.             'requestForm' => $form->createView(),
  51.         ]);
  52.     }
  53.     /**
  54.      * Confirmation page after a user has requested a password reset.
  55.      *
  56.      * @Route("/check-email", name="app_check_email")
  57.      *
  58.      * @return Response
  59.      */
  60.     public function checkEmail(): Response
  61.     {
  62.         // We prevent users from directly accessing this page
  63.         if (!$this->canCheckEmail()) {
  64.             return $this->redirectToRoute('app_forgot_password_request');
  65.         }
  66.         return $this->render('reset_password/check_email.html.twig', [
  67.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  68.         ]);
  69.     }
  70.     /**
  71.      * Validates and process the reset URL that the user clicked in their email.
  72.      *
  73.      * @Route("/reset/{token}", name="app_reset_password")
  74.      *
  75.      * @param Request $request
  76.      * @param UserPasswordEncoderInterface $passwordEncoder
  77.      * @param string|null $token
  78.      *
  79.      * @return Response
  80.      */
  81.     public function reset(
  82.         Request $request,
  83.         UserPasswordEncoderInterface $passwordEncoder,
  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_reset_password');
  91.         }
  92.         $token $this->getTokenFromSession();
  93.         if (null === $token) {
  94.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  95.         }
  96.         try {
  97.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  98.         } catch (ResetPasswordExceptionInterface $e) {
  99.             captureException($e);
  100.             $this->addFlash('reset_password_error'sprintf(
  101.                 'There was a problem validating your reset request - %s',
  102.                 $e->getReason()
  103.             ));
  104.             return $this->redirectToRoute('app_forgot_password_request');
  105.         }
  106.         // The token is valid; allow the user to change their password.
  107.         $form $this->createForm(ChangePasswordFormType::class);
  108.         $form->handleRequest($request);
  109.         if ($form->isSubmitted() && $form->isValid()) {
  110.             // A password reset token should be used only once, remove it.
  111.             $this->resetPasswordHelper->removeResetRequest($token);
  112.             // Encode the plain password, and set it.
  113.             $encodedPassword $passwordEncoder->encodePassword(
  114.                 $user,
  115.                 $form->get('plainPassword')->getData()
  116.             );
  117.             $user->setPassword($encodedPassword);
  118.             $this->getDoctrine()->getManager()->flush();
  119.             // The session is cleaned up after the password has been changed.
  120.             $this->cleanSessionAfterReset();
  121.             return $this->redirectToRoute('index');
  122.         }
  123.         return $this->render('reset_password/reset.html.twig', [
  124.             'resetForm' => $form->createView(),
  125.         ]);
  126.     }
  127.     private function processSendingPasswordResetEmail(string $emailFormData): RedirectResponse
  128.     {
  129.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  130.             'email' => $emailFormData,
  131.         ]);
  132.         // Marks that you are allowed to see the app_check_email page.
  133.         $this->setCanCheckEmailInSession();
  134.         // Do not reveal whether a user account was found or not.
  135.         if (!$user) {
  136.             return $this->redirectToRoute('app_check_email');
  137.         }
  138.         try {
  139.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  140.         } catch (ResetPasswordExceptionInterface $e) {
  141.             captureException($e);
  142.             $this->addFlash('reset_password_error'sprintf(
  143.                 'There was a problem handling your password reset request - %s',
  144.                 $e->getReason()
  145.             ));
  146.             return $this->redirectToRoute('app_forgot_password_request');
  147.         }
  148.         $this->mailer->sendMailWithTemplate(
  149.             $user,
  150.             'We Act | Renouvellement de votre mot de passe',
  151.             'mailer/user_password_forgot_mail.html.twig',
  152.             [
  153.                 'resetToken' => $resetToken,
  154.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  155.             ]
  156.         );
  157.         return $this->redirectToRoute('app_check_email');
  158.     }
  159. }