src/Controller/ResetPasswordController.php line 59

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 App\Service\MailService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  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. use Twig\Environment;
  23. /**
  24.  * @Route("/reset-password")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private $resetPasswordHelper;
  30.     private $entityManager;
  31.     private $mailer;
  32.     private $twig;
  33.     private $mailRemitente;
  34.     private $mailCopia;
  35.     private $mailService;
  36.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerMailerInterface $mailer,ParameterBagInterface $parameterBagEnvironment $twigMailService $mailService)
  37.     {
  38.         $this->resetPasswordHelper $resetPasswordHelper;
  39.         $this->entityManager $entityManager;
  40.         $this->mailer $mailer;       
  41.         $this->twig $twig;
  42.         $this->mailRemitente $parameterBag->get('mailRemitente');
  43.         $this->mailCopia $parameterBag->get('mailCopia');
  44.         //Servicios
  45.         $this->mailService $mailService;
  46.     }
  47.     /**
  48.      * Display & process form to request a password reset.
  49.      *
  50.      * @Route("", name="app_forgot_password_request")
  51.      */
  52.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  53.     {
  54.         $form $this->createForm(ResetPasswordRequestFormType::class);
  55.         $form->handleRequest($request);
  56.         if ($form->isSubmitted() && $form->isValid()) {
  57.             return $this->processSendingPasswordResetEmail(
  58.                 $form->get('mail')->getData(),
  59.                 $mailer,
  60.                 $translator
  61.             );
  62.         }
  63.         return $this->render('reset_password/request.html.twig', [
  64.             'requestForm' => $form->createView(),
  65.         ]);
  66.     }
  67.     /**
  68.      * Confirmation page after a user has requested a password reset.
  69.      *
  70.      * @Route("/check-email", name="app_check_email")
  71.      */
  72.     public function checkEmail(): Response
  73.     {
  74.         // Genere un token falso si el usuario no existe o si alguien accedió directamente a esta página.
  75.         // Esto evita exponer si se encontró o no un usuario con la dirección de correo electrónico dada o no
  76.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  77.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  78.         }
  79.         return $this->render('reset_password/check_email.html.twig', [
  80.             'resetToken' => $resetToken,
  81.         ]);
  82.     }
  83.     /**
  84.      * Validates and process the reset URL that the user clicked in their email.
  85.      *
  86.      * @Route("/reset/{token}", name="app_reset_password")
  87.      */
  88.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  89.     {
  90.         if ($token) {
  91.             // We store the token in session and remove it from the URL, to avoid the URL being
  92.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  93.             $this->storeTokenInSession($token);
  94.             return $this->redirectToRoute('app_reset_password');
  95.         }
  96.         $token $this->getTokenFromSession();
  97.         if (null === $token) {
  98.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  99.         }
  100.         try {
  101.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  102.         } catch (ResetPasswordExceptionInterface $e) {
  103.             $this->addFlash('reset_password_error'sprintf(
  104.                 '%s - %s',
  105.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  106.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  107.             ));
  108.             return $this->redirectToRoute('app_forgot_password_request');
  109.         }
  110.         // The token is valid; allow the user to change their password.
  111.         $form $this->createForm(ChangePasswordFormType::class);
  112.         $form->handleRequest($request);
  113.         if ($form->isSubmitted() && $form->isValid()) {
  114.             // A password reset token should be used only once, remove it.
  115.             $this->resetPasswordHelper->removeResetRequest($token);
  116.             // Encode(hash) the plain password, and set it.
  117.             $encodedPassword $userPasswordHasher->hashPassword(
  118.                 $user,
  119.                 $form->get('plainPassword')->getData()
  120.             );
  121.             $user->setPassword($encodedPassword);
  122.             $this->entityManager->flush();
  123.             // The session is cleaned up after the password has been changed.
  124.             $this->cleanSessionAfterReset();
  125.             return $this->redirectToRoute('index');
  126.         }
  127.         return $this->render('reset_password/reset.html.twig', [
  128.             'resetForm' => $form->createView(),
  129.         ]);
  130.     }
  131.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  132.     {
  133.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  134.             'mail' => $emailFormData,
  135.         ]);
  136.         // Do not reveal whether a user account was found or not.
  137.         if (!$user) {
  138.             return $this->redirectToRoute('app_check_email');
  139.         }
  140.         try {
  141.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  142.         } catch (ResetPasswordExceptionInterface $e) {
  143.             // If you want to tell the user why a reset email was not sent, uncomment
  144.             // the lines below and change the redirect to 'app_forgot_password_request'.
  145.             // Caution: This may reveal if a user is registered or not.
  146.             //
  147.             
  148.             $this->addFlash('reset_password_error'sprintf(
  149.                  '%s - %s',
  150.                  $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  151.                  $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  152.             ));
  153.             //return $this->redirectToRoute('app_check_email');
  154.             return $this->redirectToRoute('app_forgot_password_request');
  155.         }
  156.         //Envio el Mail
  157.         $this->mailService->restablecerPassword($user,$resetToken);
  158.         // Store the token object in session for retrieval in check-email route.
  159.         $this->setTokenObjectInSession($resetToken);
  160.         return $this->redirectToRoute('app_check_email');
  161.     }
  162. }