src/Controller/User/ResetPasswordController.php line 37

  1. <?php
  2. namespace App\Controller\User;
  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('user/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_user_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('emails/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('/check-email'name'app_user_check_email')]
  50.     public function checkEmail(): Response
  51.     {
  52.         // Generate a fake token if the user does not exist or someone hit this page directly.
  53.         // This prevents exposing whether or not a user was found with the given email address or not
  54.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  55.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  56.         }
  57.         return $this->render('emails/reset_password/check_email.html.twig', [
  58.             'resetToken' => $resetToken,
  59.         ]);
  60.     }
  61.     /**
  62.      * Validates and process the reset URL that the user clicked in their email.
  63.      */
  64.     #[Route('/reset/{token}'name'app_user_reset_password')]
  65.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $token null): Response
  66.     {
  67.         if ($token) {
  68.             // We store the token in session and remove it from the URL, to avoid the URL being
  69.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  70.             $this->storeTokenInSession($token);
  71.             return $this->redirectToRoute('app_user_reset_password');
  72.         }
  73.         $token $this->getTokenFromSession();
  74.         if (null === $token) {
  75.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  76.         }
  77.         try {
  78.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  79.         } catch (ResetPasswordExceptionInterface $e) {
  80.             $this->addFlash('reset_password_error'sprintf(
  81.                 '%s - %s',
  82.                 ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  83.                 $e->getReason()
  84.             ));
  85.             return $this->redirectToRoute('app_user_forgot_password_request');
  86.         }
  87.         // The token is valid; allow the user to change their password.
  88.         $form $this->createForm(ChangePasswordFormType::class);
  89.         $form->handleRequest($request);
  90.         if ($form->isSubmitted() && $form->isValid()) {
  91.             // A password reset token should be used only once, remove it.
  92.             $this->resetPasswordHelper->removeResetRequest($token);
  93.             // Encode(hash) the plain password, and set it.
  94.             $encodedPassword $passwordHasher->hashPassword(
  95.                 $user,
  96.                 $form->get('plainPassword')->getData()
  97.             );
  98.             $user->setPassword($encodedPassword);
  99.             $this->entityManager->flush();
  100.             // The session is cleaned up after the password has been changed.
  101.             $this->cleanSessionAfterReset();
  102.             return $this->redirectToRoute('app_home');
  103.         }
  104.         return $this->render('emails/reset_password/reset.html.twig', [
  105.             'resetForm' => $form->createView(),
  106.         ]);
  107.     }
  108.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  109.     {
  110.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  111.             'email' => $emailFormData,
  112.         ]);
  113.         // Do not reveal whether a user account was found or not.
  114.         if (!$user) {
  115.             return $this->redirectToRoute('app_user_check_email');
  116.         }
  117.         try {
  118.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  119.         } catch (ResetPasswordExceptionInterface $e) {
  120.             // If you want to tell the user why a reset email was not sent, uncomment
  121.             // the lines below and change the redirect to 'app_forgot_password_request'.
  122.             // Caution: This may reveal if a user is registered or not.
  123.             //
  124.             // $this->addFlash('reset_password_error', sprintf(
  125.             //     '%s - %s',
  126.             //     ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
  127.             //     $e->getReason()
  128.             // ));
  129.             return $this->redirectToRoute('app_user_check_email');
  130.         }
  131.         $email = (new TemplatedEmail())
  132.             ->from(new Address('contact@arctri-services.com''Arctri Services'))
  133.             ->to($user->getEmail())
  134.             ->subject('Your password reset request')
  135.             ->htmlTemplate('reset_password/email.html.twig')
  136.             ->context([
  137.                 'resetToken' => $resetToken,
  138.             ])
  139.         ;
  140.         $mailer->send($email);
  141.         // Store the token object in session for retrieval in check-email route.
  142.         $this->setTokenObjectInSession($resetToken);
  143.         return $this->redirectToRoute('app_user_check_email');
  144.     }
  145. }