src/Controller/ResetPasswordController.php line 47

  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 Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. use Psr\Log\LoggerInterface;
  21. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  22. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  23. #[Route('/reset-password')]
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $logger;
  28.     private $fromEmail;
  29.     public function __construct(
  30.         private ResetPasswordHelperInterface $resetPasswordHelper,
  31.         private EntityManagerInterface $entityManager,
  32.         LoggerInterface $logger,
  33.         ParameterBagInterface $params
  34.     ) {
  35.         $this->logger $logger;
  36.         $this->fromEmail $params->get('mailer_from_email');
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      */
  41.     #[Route(''name'app_forgot_password_request')]
  42.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  43.     {
  44.         $form $this->createForm(ResetPasswordRequestFormType::class);
  45.         $form->handleRequest($request);
  46.         if ($form->isSubmitted() && $form->isValid()) {
  47.             return $this->processSendingPasswordResetEmail(
  48.                 $form->get('email')->getData(),
  49.                 $mailer,
  50.                 $translator
  51.             );
  52.         }
  53.         return $this->render('reset_password/request.html.twig', [
  54.             'requestForm' => $form->createView(),
  55.         ]);
  56.     }
  57.     /**
  58.      * Confirmation page after a user has requested a password reset.
  59.      */
  60.     #[Route('/check-email'name'app_check_email')]
  61.     public function checkEmail(): Response
  62.     {
  63.         // Generate a fake token if the user does not exist or someone hit this page directly.
  64.         // This prevents exposing whether or not a user was found with the given email address or not
  65.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  66.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  67.         }
  68.         return $this->render('reset_password/check_email.html.twig', [
  69.             'resetToken' => $resetToken,
  70.         ]);
  71.     }
  72.     /**
  73.      * Validates and process the reset URL that the user clicked in their email.
  74.      */
  75.     #[Route('/reset/{token}'name'app_reset_password')]
  76.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  77.     {
  78.         if ($token) {
  79.             // We store the token in session and remove it from the URL, to avoid the URL being
  80.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  81.             $this->storeTokenInSession($token);
  82.     
  83.             return $this->redirectToRoute('app_reset_password');
  84.         }
  85.     
  86.         $token $this->getTokenFromSession();
  87.     
  88.         if (null === $token) {
  89.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  90.         }
  91.     
  92.         try {
  93.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  94.         } catch (ResetPasswordExceptionInterface $e) {
  95.             $this->addFlash('reset_password_error'sprintf(
  96.                 '%s - %s',
  97.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  98.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  99.             ));
  100.     
  101.             return $this->redirectToRoute('app_forgot_password_request');
  102.         }
  103.     
  104.         // The token is valid; allow the user to change their password.
  105.         $form $this->createForm(ChangePasswordFormType::class);
  106.         $form->handleRequest($request);
  107.     
  108.         if ($form->isSubmitted() && $form->isValid()) {
  109.             // A password reset token should be used only once, remove it.
  110.             $this->resetPasswordHelper->removeResetRequest($token);
  111.     
  112.             // Encode(hash) the plain password, and set it.
  113.             $encodedPassword $passwordHasher->hashPassword(
  114.                 $user,
  115.                 $form->get('plainPassword')->getData()
  116.             );
  117.     
  118.             $user->setPassword($encodedPassword);
  119.             $this->entityManager->flush();
  120.     
  121.             // The session is cleaned up after the password has been changed.
  122.             $this->cleanSessionAfterReset();
  123.     
  124.             // Redirigir basado en el rol del usuario
  125.             $roles $user->getRoles();
  126.             if (in_array('ROLE_DISTRIBUTOR'$rolestrue) || in_array('ROLE_DESIGNER'$rolestrue)) {
  127.                 return $this->redirect('https://profesional.herdasa.es/signin');
  128.             }
  129.     
  130.             return $this->redirectToRoute('app_login');
  131.         }
  132.     
  133.         return $this->render('reset_password/reset.html.twig', [
  134.             'resetForm' => $form->createView(),
  135.         ]);
  136.     }
  137.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  138.     {
  139.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  140.             'email' => $emailFormData,
  141.         ]);
  142.         // Do not reveal whether a user account was found or not.
  143.         if (!$user) {
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         try {
  147.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  148.         } catch (ResetPasswordExceptionInterface $e) {
  149.             // If you want to tell the user why a reset email was not sent, uncomment
  150.             // the lines below and change the redirect to 'app_forgot_password_request'.
  151.             // Caution: This may reveal if a user is registered or not.
  152.             return $this->redirectToRoute('app_check_email');
  153.             //
  154.             // $this->addFlash('reset_password_error', sprintf(
  155.             //     '%s - %s',
  156.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  157.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  158.             // ));
  159.             return $this->redirectToRoute('app_check_email');
  160.         }
  161.         $email = (new TemplatedEmail())
  162.             ->from($this->fromEmail)
  163.             ->to($user->getEmail())
  164.             ->subject('Reestablecer contraseña')
  165.             ->htmlTemplate('reset_password/email.html.twig')
  166.             ->context([
  167.                 'resetToken' => $resetToken,
  168.             ])
  169.         ;
  170.         try {
  171.             $mailer->send($email);
  172.         } catch (\Exception $e) {
  173.             // Aquí puedes manejar el error como prefieras, por ejemplo, registrándolo
  174.             $this->logger->error('No se pudo enviar el correo electrónico de registro', ['exception' => $e]);
  175.         }
  176.         // Store the token object in session for retrieval in check-email route.
  177.         $this->setTokenObjectInSession($resetToken);
  178.         return $this->redirectToRoute('app_check_email');
  179.     }
  180.     #[Route('/request-password-reset-api'name'app_request_password_reset_nextjs'methods: ['POST'])]
  181.     public function requestPasswordResetNextjs(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  182.     {
  183.         $data json_decode($request->getContent(), true);
  184.         $email $data['email'] ?? null;
  185.         $source 'nextjs';
  186.         if (!$email) {
  187.             return $this->json(['error' => 'Email es requerido.'], 400);
  188.         }
  189.         return $this->processSendingPasswordResetEmailNext($email$source$mailer$translator$request);
  190.     }
  191.     private function processSendingPasswordResetEmailNext(string $emailFormDatastring $sourceMailerInterface $mailerTranslatorInterface $translatorRequest $request): Response
  192.     {
  193.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  194.             'email' => $emailFormData,
  195.         ]);
  196.     
  197.         // No revelar si el usuario fue encontrado o no.
  198.         if (!$user) {
  199.             return $this->json(['message' => 'Si el email es válido, se enviará un correo de recuperación.']);
  200.         }
  201.     
  202.         try {
  203.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  204.         } catch (ResetPasswordExceptionInterface $e) {
  205.             return $this->json(['message' => 'Si el email es válido, se enviará un correo de recuperación.']);
  206.         }
  207.     
  208.         $email = (new TemplatedEmail())
  209.             ->from($this->fromEmail)
  210.             ->to($user->getEmail())
  211.             ->subject('Reestablecer contraseña')
  212.             ->htmlTemplate('reset_password/email.html.twig')
  213.             ->context([
  214.                 'resetToken' => $resetToken,
  215.             ]);
  216.     
  217.         try {
  218.             $mailer->send($email);
  219.         } catch (\Exception $e) {
  220.             $this->logger->error('No se pudo enviar el correo electrónico de recuperación', ['exception' => $e]);
  221.         }
  222.     
  223.         // Almacenar el token y la fuente en la sesión
  224.         $this->setTokenObjectInSession($resetToken);
  225.         $request->getSession()->set('reset_password_source'$source);
  226.     
  227.         return $this->json(['message' => 'Si el email es válido, se enviará un correo de recuperación.']);
  228.     }
  229. }