src/Controller/ResetPasswordController.php line 34

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  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\Mailer\MailerInterface;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  16. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. #[Route(path'/reset-password')]
  19. class ResetPasswordController extends AbstractController
  20. {
  21.     use ResetPasswordControllerTrait;
  22.     public function __construct(private ResetPasswordHelperInterface $resetPasswordHelper, private \Doctrine\Persistence\ManagerRegistry $managerRegistry)
  23.     {
  24.     }
  25.     /**
  26.      * Display & process form to request a password reset.
  27.      */
  28.     #[Route(path''name'app_forgot_password_request')]
  29.     public function request(Request $requestMailerInterface $mailer): Response
  30.     {
  31.         $form $this->createForm(ResetPasswordRequestFormType::class);
  32.         $form->handleRequest($request);
  33.         if ($form->isSubmitted() && $form->isValid()) {
  34.             return $this->processSendingPasswordResetEmail(
  35.                 $form->get('email')->getData(),
  36.                 $mailer
  37.             );
  38.         }
  39.         return $this->render('reset_password/request.html.twig', [
  40.             'requestForm' => $form,
  41.         ]);
  42.     }
  43.     /**
  44.      * Confirmation page after a user has requested a password reset.
  45.      */
  46.     #[Route(path'/check-email'name'app_check_email')]
  47.     public function checkEmail(): Response
  48.     {
  49.         // We prevent users from directly accessing this page
  50.         if (!$this->canCheckEmail()) {
  51.             return $this->redirectToRoute('app_forgot_password_request');
  52.         }
  53.         return $this->render('reset_password/check_email.html.twig', [
  54.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  55.         ]);
  56.     }
  57.     /**
  58.      * Validates and process the reset URL that the user clicked in their email.
  59.      */
  60.     #[Route(path'/reset/{token}'name'app_reset_password')]
  61.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $token null): Response
  62.     {
  63.         if ($token) {
  64.             // We store the token in session and remove it from the URL, to avoid the URL being
  65.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  66.             $this->storeTokenInSession($token);
  67.             return $this->redirectToRoute('app_reset_password');
  68.         }
  69.         $token $this->getTokenFromSession();
  70.         if (null === $token) {
  71.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  72.         }
  73.         try {
  74.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  75.         } catch (ResetPasswordExceptionInterface $e) {
  76.             $this->addFlash('reset_password_error'sprintf(
  77.                 'There was a problem validating your reset request - %s',
  78.                 $e->getReason()
  79.             ));
  80.             return $this->redirectToRoute('app_forgot_password_request');
  81.         }
  82.         // The token is valid; allow the user to change their password.
  83.         $form $this->createForm(ChangePasswordFormType::class);
  84.         $form->handleRequest($request);
  85.         if ($form->isSubmitted() && $form->isValid()) {
  86.             // A password reset token should be used only once, remove it.
  87.             $this->resetPasswordHelper->removeResetRequest($token);
  88.             // Encode the plain password, and set it.
  89.             $encodedPassword $passwordHasher->hashPassword(
  90.                 $user,
  91.                 $form->get('plainPassword')->getData()
  92.             );
  93.             $user->setPassword($encodedPassword);
  94.             $this->managerRegistry->getManager()->flush();
  95.             // The session is cleaned up after the password has been changed.
  96.             $this->cleanSessionAfterReset();
  97.             return $this->redirectToRoute('app_login');
  98.         }
  99.         return $this->render('reset_password/reset.html.twig', [
  100.             'resetForm' => $form,
  101.         ]);
  102.     }
  103.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  104.     {
  105.         $user $this->managerRegistry->getRepository(User::class)->findOneBy([
  106.             'email' => $emailFormData,
  107.         ]);
  108.         // Marks that you are allowed to see the app_check_email page.
  109.         $this->setCanCheckEmailInSession();
  110.         // Do not reveal whether a user account was found or not.
  111.         if (!$user) {
  112.             return $this->redirectToRoute('app_check_email');
  113.         }
  114.         try {
  115.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  116.         } catch (ResetPasswordExceptionInterface $e) {
  117.             $this->addFlash('reset_password_error'sprintf(
  118.                 'There was a problem handling your password reset request - %s',
  119.                 $e->getReason()
  120.             ));
  121.             return $this->redirectToRoute('app_forgot_password_request');
  122.         }
  123.         $email = (new TemplatedEmail())
  124.             ->from(new Address('no-reply@uva3.com''GRB'))
  125.             ->to($user->getEmail())
  126.             ->subject('Your password reset request')
  127.             ->htmlTemplate('reset_password/email.html.twig')
  128.             ->context([
  129.                 'resetToken' => $resetToken,
  130.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  131.             ])
  132.         ;
  133.         $mailer->send($email);
  134.         return $this->redirectToRoute('app_check_email');
  135.     }
  136. }