src/Controller/ResetPasswordController.php line 38

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 SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  16. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. use Twig\Environment;
  19. use Symfony\Bridge\Twig\Mime\BodyRenderer;
  20. class ResetPasswordController extends AbstractController
  21. {
  22.     use ResetPasswordControllerTrait;
  23.     public function __construct(
  24.         private ResetPasswordHelperInterface $resetPasswordHelper,
  25.         private EntityManagerInterface $entityManager,
  26.         private Environment $twig,
  27.     ) {
  28.     }
  29.     /**
  30.      * Display & process form to request a password reset.
  31.      */
  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('security/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.     public function checkEmail(): Response
  50.     {
  51.         // Generate a fake token if the user does not exist or someone hit this page directly.
  52.         // This prevents exposing whether or not a user was found with the given email address or not
  53.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  54.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  55.         }
  56.         return $this->render('security/reset_password/check_email.html.twig', [
  57.             'resetToken' => $resetToken,
  58.         ]);
  59.     }
  60.     /**
  61.      * Validates and process the reset URL that the user clicked in their email.
  62.      */
  63.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $token null): Response
  64.     {
  65.         if ($token) {
  66.             // We store the token in session and remove it from the URL, to avoid the URL being
  67.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  68.             $this->storeTokenInSession($token);
  69.             return $this->redirectToRoute('admin_security_forgot_password_reset');
  70.         }
  71.         $token $this->getTokenFromSession();
  72.         if (null === $token) {
  73.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  74.         }
  75.         try {
  76.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  77.         } catch (ResetPasswordExceptionInterface $e) {
  78.             $this->addFlash('reset_password_error'sprintf(
  79.                 '%s - %s',
  80.                 ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  81.                 $e->getReason()
  82.             ));
  83.             return $this->redirectToRoute('admin_security_forgot_password_request');
  84.         }
  85.         // The token is valid; allow the user to change their password.
  86.         $form $this->createForm(ChangePasswordFormType::class);
  87.         $form->handleRequest($request);
  88.         if ($form->isSubmitted() && $form->isValid()) {
  89.             // A password reset token should be used only once, remove it.
  90.             $this->resetPasswordHelper->removeResetRequest($token);
  91.             // Encode(hash) the plain password, and set it.
  92.             $encodedPassword $passwordHasher->hashPassword(
  93.                 $user,
  94.                 $form->get('plainPassword')->getData()
  95.             );
  96.             $user->setPassword($encodedPassword);
  97.             $this->entityManager->flush();
  98.             // The session is cleaned up after the password has been changed.
  99.             $this->cleanSessionAfterReset();
  100.             return $this->redirectToRoute('admin_index');
  101.         }
  102.         return $this->render('security/reset_password/reset.html.twig', [
  103.             'resetForm' => $form->createView(),
  104.         ]);
  105.     }
  106.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  107.     {
  108.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  109.             'email' => $emailFormData,
  110.         ]);
  111.         // Do not reveal whether a user account was found or not.
  112.         if (!$user) {
  113.             return $this->redirectToRoute('admin_security_forgot_password_check_email');
  114.         }
  115.         try {
  116.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  117.         } catch (ResetPasswordExceptionInterface $e) {
  118.             $this->addFlash('reset_password_error'sprintf(
  119.                             '%s - %s',
  120.                             ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
  121.                             $e->getReason()
  122.             ));
  123.             return $this->redirectToRoute('admin_security_forgot_password_check_email');
  124.         }
  125.         $email = (new TemplatedEmail())
  126.             ->from(new Address('no-reply@escappart.com''No-Reply Escappart'))
  127.             ->to($user->getEmail())
  128.             ->subject('Escappart : Your password reset request')
  129.             ->htmlTemplate('security/reset_password/email.html.twig')
  130.             ->context([
  131.                 'resetToken' => $resetToken,
  132.             ])
  133.         ;
  134.         
  135.         $renderer = new BodyRenderer($this->twig);
  136.         $renderer->render($email);
  137.         $mailer->send($email);
  138.         // Store the token object in session for retrieval in check-email route.
  139.         $this->setTokenObjectInSession($resetToken);
  140.         return $this->redirectToRoute('admin_security_forgot_password_check_email');
  141.     }
  142. }