src/Controller/ResetPasswordController.php line 42

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\Persistence\ManagerRegistry;
  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 SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. /**
  21.  * @Route("/reset-password")
  22.  */
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $resetPasswordHelper;
  27.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  28.     {
  29.         $this->resetPasswordHelper $resetPasswordHelper;
  30.     }
  31.     /**
  32.      * Display & process form to request a password reset.
  33.      *
  34.      * @Route("", name="app_forgot_password_request")
  35.      */
  36.     public function request(Request $requestMailerInterface $mailerManagerRegistry $registryTranslatorInterface $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.                 $registry,
  45.                 $translator
  46.             );
  47.         }
  48.         return $this->render('reset_password/request.html.twig', [
  49.             'requestForm' => $form->createView(),
  50.         ]);
  51.     }
  52.     /**
  53.      * Confirmation page after a user has requested a password reset.
  54.      *
  55.      * @Route("/check-email", name="app_check_email")
  56.      */
  57.     public function checkEmail(): Response
  58.     {
  59.         // Generate a fake token if the user does not exist or someone hit this page directly.
  60.         // This prevents exposing whether or not a user was found with the given email address or not
  61.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  62.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  63.         }
  64.         return $this->render('reset_password/check_email.html.twig', [
  65.             'resetToken' => $resetToken,
  66.         ]);
  67.     }
  68.     /**
  69.      * Validates and process the reset URL that the user clicked in their email.
  70.      *
  71.      * @Route("/reset/{token}", name="app_reset_password")
  72.      */
  73.     public function reset(
  74.         Request $request,
  75.         UserPasswordHasherInterface $userPasswordHasherInterface,
  76.         string $token null,
  77.         TranslatorInterface $translator
  78.     ): Response
  79.     {
  80.         if ($token) {
  81.             // We store the token in session and remove it from the URL, to avoid the URL being
  82.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  83.             $this->storeTokenInSession($token);
  84.             return $this->redirectToRoute('app_reset_password');
  85.         }
  86.         $token $this->getTokenFromSession();
  87.         if (null === $token) {
  88.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  89.         }
  90.         try {
  91.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  92.         } catch (ResetPasswordExceptionInterface $e) {
  93.             $this->addFlash('reset_password_error'sprintf(
  94.                 'There was a problem validating your reset request - %s',
  95.                 $e->getReason()
  96.             ));
  97.             return $this->redirectToRoute('app_forgot_password_request');
  98.         }
  99.         // The token is valid; allow the user to change their password.
  100.         $form $this->createForm(ChangePasswordFormType::class);
  101.         $form->handleRequest($request);
  102.         if ($form->isSubmitted() && $form->isValid()) {
  103.             // A password reset token should be used only once, remove it.
  104.             $this->resetPasswordHelper->removeResetRequest($token);
  105.             // Encode(hash) the plain password, and set it.
  106.             $encodedPassword $userPasswordHasherInterface->hashPassword(
  107.                 $user,
  108.                 $form->get('plainPassword')->getData()
  109.             );
  110.             $user->setPassword($encodedPassword);
  111.             $this->getDoctrine()->getManager()->flush();
  112.             // The session is cleaned up after the password has been changed.
  113.             $this->cleanSessionAfterReset();
  114.             $this->addFlash(
  115.                 'success',
  116.                 $translator->trans('flash.resetpassword.success')
  117.             );
  118.             return $this->redirectToRoute('login');
  119.         }
  120.         return $this->render('reset_password/reset.html.twig', [
  121.             'resetForm' => $form->createView(),
  122.         ]);
  123.     }
  124.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerManagerRegistry $registryTranslatorInterface $translator): RedirectResponse
  125.     {
  126.         $user $registry->getManager()->getRepository(User::class)->findOneBy([
  127.             'email' => $emailFormData,
  128.         ]);
  129.         // Do not reveal whether a user account was found or not.
  130.         if (!$user) {
  131.             return $this->redirectToRoute('app_check_email');
  132.         }
  133.         try {
  134.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  135.         } catch (ResetPasswordExceptionInterface $e) {
  136.             // If you want to tell the user why a reset email was not sent, uncomment
  137.             // the lines below and change the redirect to 'app_forgot_password_request'.
  138.             // Caution: This may reveal if a user is registered or not.
  139.             //
  140.             // $this->addFlash('reset_password_error', sprintf(
  141.             //     'There was a problem handling your password reset request - %s',
  142.             //     $e->getReason()
  143.             // ));
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         $email = (new TemplatedEmail())
  147.             ->from(new Address('notifications@paris-jetequitte.com''Paris Je Te Quitte'))
  148.             ->to($user->getEmail())
  149.             ->subject($translator->trans('template_email.reset_password.subject'))
  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_check_email');
  159.     }
  160. }