src/Controller/ResetPasswordController.php line 45

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Business\Security\SecurityFacadeInterface;
  4. use App\Form\Frontend\ChangePasswordFormType;
  5. use App\Form\Frontend\ResetPasswordRequestFormType;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  15. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  17. #[Route('/reset-password')]
  18. class ResetPasswordController extends AbstractController
  19. {
  20.     use ResetPasswordControllerTrait;
  21.     /**
  22.      * @param ResetPasswordHelperInterface $resetPasswordHelper
  23.      * @param EntityManagerInterface       $entityManager
  24.      */
  25.     public function __construct(
  26.         private ResetPasswordHelperInterface $resetPasswordHelper,
  27.         private EntityManagerInterface $entityManager
  28.     ) {
  29.     }
  30.     /**
  31.      * Display & process form to request a password reset.
  32.      *
  33.      * @param  Request             $request
  34.      * @param  MailerInterface     $mailer
  35.      * @param  TranslatorInterface $translator
  36.      * @return Response
  37.      * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  38.      */
  39.     #[Route(''name'app_forgot_password_request')]
  40.     public function request(Request $requestSecurityFacadeInterface $securityFacade): Response
  41.     {
  42.         $form $this->createForm(ResetPasswordRequestFormType::class)
  43.             ->handleRequest($request);
  44.         if ($form->isSubmitted() && $form->isValid()) {
  45.             $securityFacade->requestPassword($form->get('email')->getData());
  46.             return $this->redirectToRoute('app_check_email');
  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.      * @return Response
  56.      */
  57.     #[Route('/check-email'name'app_check_email')]
  58.     public function checkEmail(): Response
  59.     {
  60.         // Generate a fake token if the user does not exist or someone hit this page directly.
  61.         // This prevents exposing whether or not a user was found with the given email address or not
  62.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  63.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  64.         }
  65.         return $this->render(
  66.             'reset_password/check_email.html.twig',
  67.             [
  68.             'resetToken' => $resetToken,
  69.             ]
  70.         );
  71.     }
  72.     /**
  73.      * Validates and process the reset URL that the user clicked in their email.
  74.      *
  75.      * @param  Request                     $request
  76.      * @param  UserPasswordHasherInterface $passwordHasher
  77.      * @param  TranslatorInterface         $translator
  78.      * @param  string|null                 $token
  79.      * @return Response
  80.      */
  81.     #[Route('/reset/{token}'name'app_reset_password')]
  82.     public function reset(
  83.         Request $request,
  84.         UserPasswordHasherInterface $passwordHasher,
  85.         TranslatorInterface $translator,
  86.         string $token null
  87.     ): Response {
  88.         if ($token) {
  89.             // We store the token in session and remove it from the URL, to avoid the URL being
  90.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  91.             $this->storeTokenInSession($token);
  92.             return $this->redirectToRoute('app_reset_password');
  93.         }
  94.         $token $this->getTokenFromSession();
  95.         if (null === $token) {
  96.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  97.         }
  98.         try {
  99.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  100.         } catch (ResetPasswordExceptionInterface $e) {
  101.             $this->addFlash(
  102.                 'reset_password_error',
  103.                 sprintf(
  104.                     '%s - %s',
  105.                     $translator->trans(
  106.                         ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  107.                         [],
  108.                         'ResetPasswordBundle'
  109.                     ),
  110.                     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  111.                 )
  112.             );
  113.             return $this->redirectToRoute('app_frontend_index');
  114.         }
  115.         // The token is valid; allow the user to change their password.
  116.         $form $this->createForm(ChangePasswordFormType::class);
  117.         $form->handleRequest($request);
  118.         if ($form->isSubmitted() && $form->isValid()) {
  119.             // A password reset token should be used only once, remove it.
  120.             $this->resetPasswordHelper->removeResetRequest($token);
  121.             // Encode(hash) the plain password, and set it.
  122.             $encodedPassword $passwordHasher->hashPassword($user$form->get('plainPassword')->getData());
  123.             $user->setPassword($encodedPassword);
  124.             $this->entityManager->flush();
  125.             // The session is cleaned up after the password has been changed.
  126.             $this->cleanSessionAfterReset();
  127.             return $this->redirectToRoute('app_frontend_index');
  128.         }
  129.         return $this->render('reset_password/reset.html.twig', [
  130.             'resetForm' => $form->createView()
  131.         ]);
  132.     }
  133. }