src/Controller/ResetPasswordController.php line 40

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\Form\FormError;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  14. use Symfony\Component\Mailer\MailerInterface;
  15. use Symfony\Component\Mime\Address;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  20. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  22. #[Route('/reset-password')]
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     public function __construct(
  27.         private ResetPasswordHelperInterface $resetPasswordHelper,
  28.         private EntityManagerInterface $entityManager
  29.     ) {
  30.     }
  31.     /**
  32.      * Display & process form to request a password reset.
  33.      */
  34.     #[Route(''name'app_forgot_password_request')]
  35.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  36.     {
  37.         $form $this->createForm(ResetPasswordRequestFormType::class);
  38.         $form->handleRequest($request);
  39.         if ($form->isSubmitted() && $form->isValid()) {
  40.             return $this->processSendingPasswordResetEmail(
  41.                 $form->get('email')->getData(),
  42.                 $mailer,
  43.                 $translator
  44.             );
  45.         }
  46.         return $this->render('reset_password/request.html.twig', [
  47.             'requestForm' => $form->createView(),
  48.         ]);
  49.     }
  50.     /**
  51.      * Confirmation page after a user has requested a password reset.
  52.      */
  53.     #[Route('/check-email'name'app_check_email')]
  54.     public function checkEmail(): Response
  55.     {
  56.         // Generate a fake token if the user does not exist or someone hit this page directly.
  57.         // This prevents exposing whether or not a user was found with the given email address or not
  58.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  59.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  60.         }
  61.         return $this->render('reset_password/check_email.html.twig', [
  62.             'resetToken' => $resetToken,
  63.         ]);
  64.     }
  65.     /**
  66.      * Validates and process the reset URL that the user clicked in their email.
  67.      */
  68.     #[Route('/reset'name'app_reset_password')]
  69.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translator): Response
  70.     {
  71.         $form $this->createForm(ChangePasswordFormType::class);
  72.         $form->handleRequest($request);
  73.         $token $form->get('confirmationToken')->getData();
  74.         try {
  75.             if($token) {
  76.                 $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  77.             }
  78.         }
  79.         catch (ResetPasswordExceptionInterface $e) {
  80.             $form->get('confirmationToken')->addError(new FormError('El token ingresado no es válido'));
  81.         }
  82.         if ($form->isSubmitted() && $form->isValid()) {
  83.             // A password reset token should be used only once, remove it.
  84.             $this->resetPasswordHelper->removeResetRequest($token);
  85.             // Encode(hash) the plain password, and set it.
  86.             $encodedPassword $passwordHasher->hashPassword(
  87.                 $user,
  88.                 $form->get('plainPassword')->getData()
  89.             );
  90.             $user->setPassword($encodedPassword);
  91.             $user->setSecured(true);
  92.             $user->setPasswordUpdatedForNewPolicy(true);
  93.             $this->entityManager->flush();
  94.             // The session is cleaned up after the password has been changed.
  95.             $this->cleanSessionAfterReset();
  96.             return $this->redirectToRoute('app_login');
  97.         }
  98.         return $this->render('reset_password/reset.html.twig', [
  99.             'resetForm' => $form->createView(),
  100.         ]);
  101.     }
  102.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  103.     {
  104.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  105.             'username' => $emailFormData,
  106.         ]);
  107.         if(!$user) {
  108.             $user $this->entityManager->getRepository(User::class)->findOneBy([
  109.                 'email' => $emailFormData,
  110.             ]);
  111.         }
  112.         // Do not reveal whether a user account was found or not.
  113.         if (!$user) {
  114.             return $this->redirectToRoute('app_reset_password');
  115.         }
  116.         try {
  117.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  118.         } catch (ResetPasswordExceptionInterface $e) {
  119.             return $this->redirectToRoute('app_reset_password');
  120.         }
  121.         $email = (new TemplatedEmail())
  122.             ->from(new Address('soporte@comprasbex.cl''Sistema de Compras de BancoEstado Express'))
  123.             ->to($user->getEmail())
  124.             ->subject('Restablecer contraseña')
  125.             ->htmlTemplate('reset_password/email.html.twig')
  126.             ->context([
  127.                 'resetToken' => $resetToken,
  128.                 'user' => $user
  129.             ])
  130.         ;
  131.         try {
  132.             $mailer->send($email);
  133.         }
  134.         catch (TransportExceptionInterface $e) {
  135.             dd($e);
  136.         }
  137.         // Store the token object in session for retrieval in check-email route.
  138.         $this->setTokenObjectInSession($resetToken);
  139.         return $this->redirectToRoute('app_reset_password');
  140.     }
  141. }