src/Controller/ResetPasswordController.php line 37

  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. use Symfony\Component\Messenger\MessageBusInterface;
  19. use App\Message\SendEmailMessage;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. #[Route(path'/reset-password')]
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     public function __construct(private ResetPasswordHelperInterface $resetPasswordHelper, private \Doctrine\Persistence\ManagerRegistry $managerRegistry)
  26.     {
  27.     }
  28.     /**
  29.      * Display & process form to request a password reset.
  30.      */
  31.     #[Route(path''name'app_forgot_password_request')]
  32.     public function request(Request $requestMailerInterface $mailer,MessageBusInterface $bus): 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.                 $bus
  41.             );
  42.         }
  43.         return $this->render('reset_password/request.html.twig', [
  44.             'requestForm' => $form,
  45.         ]);
  46.     }
  47.     /**
  48.      * Confirmation page after a user has requested a password reset.
  49.      */
  50.     #[Route(path'/check-email'name'app_check_email')]
  51.     public function checkEmail(): Response
  52.     {
  53.         // We prevent users from directly accessing this page
  54.         if (!$this->canCheckEmail()) {
  55.             return $this->redirectToRoute('app_forgot_password_request');
  56.         }
  57.         return $this->render('reset_password/check_email.html.twig', [
  58.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  59.         ]);
  60.     }
  61.     /**
  62.      * Validates and process the reset URL that the user clicked in their email.
  63.      */
  64.     #[Route(path'/reset/{token}'name'app_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_reset_password');
  72.         }
  73.         $token $this->getTokenFromSession();
  74.         if (null === $token) {
  75.             throw $this->createNotFoundException('No se ha encontrado el token en la URL o en la sesión.');
  76.         }
  77.         try {
  78.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  79.         } catch (ResetPasswordExceptionInterface $e) {
  80.             $this->addFlash('reset_password_error'sprintf(
  81.                 'Ha habido un problema validando tu solicitud de restauración - %s',
  82.                 $e->getReason()
  83.             ));
  84.             return $this->redirectToRoute('app_forgot_password_request');
  85.         }
  86.         // The token is valid; allow the user to change their password.
  87.         $form $this->createForm(ChangePasswordFormType::class);
  88.         $form->handleRequest($request);
  89.         if ($form->isSubmitted() && $form->isValid()) {
  90.             // A password reset token should be used only once, remove it.
  91.             $this->resetPasswordHelper->removeResetRequest($token);
  92.             // Encode the plain password, and set it.
  93.             $encodedPassword $passwordHasher->hashPassword(
  94.                 $user,
  95.                 $form->get('plainPassword')->getData()
  96.             );
  97.             $user->setPassword($encodedPassword);
  98.             $this->managerRegistry->getManager()->flush();
  99.             // The session is cleaned up after the password has been changed.
  100.             $this->cleanSessionAfterReset();
  101.             return $this->redirectToRoute('app_login');
  102.         }
  103.         return $this->render('reset_password/reset.html.twig', [
  104.             'resetForm' => $form,
  105.         ]);
  106.     }
  107.     private function processSendingPasswordResetEmail(
  108.         string $emailFormData,
  109.         MessageBusInterface $bus
  110.     ): RedirectResponse {
  111.         $user $this->managerRegistry->getRepository(User::class)->findOneBy([
  112.             'email' => $emailFormData,
  113.         ]);
  114.         $this->setCanCheckEmailInSession();
  115.         if (!$user) {
  116.             return $this->redirectToRoute('app_check_email');
  117.         }
  118.         try {
  119.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  120.         } catch (ResetPasswordExceptionInterface $e) {
  121.             $this->addFlash(
  122.                 'reset_password_error',
  123.                 'No se ha podido gestionar la solicitud de restauración.'
  124.             );
  125.             return $this->redirectToRoute('app_forgot_password_request');
  126.         }
  127.         $resetUrl $this->generateUrl(
  128.             'app_reset_password',
  129.             ['token' => $resetToken->getToken()],
  130.             UrlGeneratorInterface::ABSOLUTE_URL
  131.         );
  132.         $bus->dispatch(new SendEmailMessage(
  133.             $user->getEmail(),
  134.             'notifications/reset_password.html.twig',
  135.             'Restauración de contraseña',
  136.             $user->getNomComplet(),
  137.             [
  138.                 'resetUrl'      => $resetUrl,
  139.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  140.             ]
  141.         ));
  142.         $this->addFlash(
  143.             'success',
  144.             'Revise su correo para restaurar la contraseña.'
  145.         );
  146.         return $this->redirectToRoute('app_check_email');
  147.     }
  148. }