src/Controller/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Usuario;
  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 Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     private $entityManager;
  29.     private $params;
  30.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerParameterBagInterface $params)
  31.     {
  32.         $this->resetPasswordHelper $resetPasswordHelper;
  33.         $this->entityManager $entityManager;
  34.         $this->params $params;
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      *
  39.      * @Route("", name="app_forgot_password_request")
  40.      */
  41.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  42.     {
  43.         $form $this->createForm(ResetPasswordRequestFormType::class);
  44.         $form->handleRequest($request);
  45.         if ($form->isSubmitted() && $form->isValid()) {
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $form->get('email')->getData(),
  48.                 $mailer,
  49.                 $translator
  50.             );
  51.         }
  52.         return $this->render('reset_password/request.html.twig', [
  53.             'requestForm' => $form->createView(),
  54.         ]);
  55.     }
  56.     /**
  57.      * Confirmation page after a user has requested a password reset.
  58.      *
  59.      * @Route("/check-email", name="app_check_email")
  60.      */
  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.      */
  77.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  78.     {
  79.         if ($token) {
  80.             // We store the token in session and remove it from the URL, to avoid the URL being
  81.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  82.             $this->storeTokenInSession($token);
  83.             return $this->redirectToRoute('app_reset_password');
  84.         }
  85.         $token $this->getTokenFromSession();
  86.         if (null === $token) {
  87.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  88.         }
  89.         try {
  90.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  91.         } catch (ResetPasswordExceptionInterface $e) {
  92.             $this->addFlash('reset_password_error'sprintf(
  93.                 '%s - %s',
  94.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  95.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  96.             ));
  97.             return $this->redirectToRoute('app_forgot_password_request');
  98.         }
  99.         // The token is valid; allow the user to change their password.
  100.         $form $this->createForm(ChangePasswordFormType::class);
  101.         $form->handleRequest($request);
  102.         if ($form->isSubmitted() && $form->isValid()) {
  103.             // A password reset token should be used only once, remove it.
  104.             $this->resetPasswordHelper->removeResetRequest($token);
  105.             // Encode(hash) the plain password, and set it.
  106.             $encodedPassword $userPasswordHasher->hashPassword(
  107.                 $user,
  108.                 $form->get('plainPassword')->getData()
  109.             );
  110.             $user->setPassword($encodedPassword);
  111.             $this->entityManager->flush();
  112.             // The session is cleaned up after the password has been changed.
  113.             $this->cleanSessionAfterReset();
  114.             $this->addFlash('success''Su contraseña ha sido restablecida correctamente.');
  115.             return $this->redirectToRoute('index');
  116.         }
  117.         return $this->render('reset_password/reset.html.twig', [
  118.             'resetForm' => $form->createView(),
  119.         ]);
  120.     }
  121.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  122.     {
  123.         $user $this->entityManager->getRepository(Usuario::class)->findOneBy([
  124.             'email' => $emailFormData,
  125.         ]);
  126.         // Do not reveal whether a user account was found or not.
  127.         if (!$user) {
  128.             return $this->redirectToRoute('app_check_email');
  129.         }
  130.         try {
  131.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  132.         } catch (ResetPasswordExceptionInterface $e) {
  133.             // If you want to tell the user why a reset email was not sent, uncomment
  134.             // the lines below and change the redirect to 'app_forgot_password_request'.
  135.             // Caution: This may reveal if a user is registered or not.
  136.             //
  137.             // $this->addFlash('reset_password_error', sprintf(
  138.             //     '%s - %s',
  139.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  140.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  141.             // ));
  142.             return $this->redirectToRoute('app_check_email');
  143.         }
  144.         $email = (new TemplatedEmail())
  145.         ->from(new Address('contabilidad@iubeo.mx''Ventanilla Virtual'))
  146.         ->to($user->getEmail())
  147.         ->subject('Recuperación de contraseña')
  148.         ->embedFromPath($this->params->get('path_logo'), 'logo')
  149.         ->htmlTemplate('reset_password/email.html.twig')
  150.             ->context([
  151.                 'resetToken' => $resetToken,
  152.                 'sistema_empresa' => $this->params->get('sistema_empresa'),
  153.                 'url_vud' => $this->params->get('url_vuv'),
  154.             ])
  155.         ;
  156.         $mailer->send($email);
  157.         // Store the token object in session for retrieval in check-email route.
  158.         $this->setTokenObjectInSession($resetToken);
  159.         return $this->redirectToRoute('app_check_email');
  160.     }
  161. }