src/Controller/ResetPasswordController.php line 44

  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 App\Entity\Settings;
  21. use App\Repository\SettingsRepository;
  22. #[Route('/reset-password')]
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $settings;
  27.     
  28.     public function __construct(
  29.         private ResetPasswordHelperInterface $resetPasswordHelper,
  30.         private EntityManagerInterface $entityManager,
  31.         SettingsRepository $settingsRepository
  32.     ) {
  33.         $this->settings = $settingsRepository->findOneById(1);
  34.     }
  35.     /**
  36.      * Display & process form to request a password reset.
  37.      */
  38.     #[Route('', name: 'app_forgot_password_request')]
  39.     public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): Response
  40.     {
  41.         $form = $this->createForm(ResetPasswordRequestFormType::class);
  42.         $form->handleRequest($request);
  43.         if ($form->isSubmitted() && $form->isValid()) {
  44.             return $this->processSendingPasswordResetEmail(
  45.                 $form->get('email')->getData(),
  46.                 $mailer,
  47.                 $translator
  48.             );
  49.         }
  50.         return $this->render('reset_password/request.html.twig', [
  51.             'requestForm' => $form->createView(),
  52.             'settings' => $this->settings,
  53.         ]);
  54.     }
  55.     /**
  56.      * Confirmation page after a user has requested a password reset.
  57.      */
  58.     #[Route('/check-email', name: 'app_check_email')]
  59.     public function checkEmail(): Response
  60.     {
  61.         // Generate a fake token if the user does not exist or someone hit this page directly.
  62.         // This prevents exposing whether or not a user was found with the given email address or not
  63.         if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  64.             $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  65.         }
  66.         return $this->render('reset_password/check_email.html.twig', [
  67.             'settings' => $this->settings,
  68.             'resetToken' => $resetToken,
  69.         ]);
  70.     }
  71.     
  72.     /**
  73.      * Confirmation page after success password reset.
  74.      */
  75.     #[Route('/reset-success', name: 'app_reset_success')]
  76.     public function resetSuccess(): Response
  77.     {
  78.         return $this->render('reset_password/reset_success.html.twig', [
  79.             'settings' => $this->settings,
  80.         ]);
  81.     }
  82.     /**
  83.      * Validates and process the reset URL that the user clicked in their email.
  84.      */
  85.     #[Route('/reset/{token}', name: 'app_reset_password')]
  86.     public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, string $token = null): Response
  87.     {
  88.         if ($token) {
  89.             // We store the token in session and remove it from the URL, to avoid the URL being
  90.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  91.             $this->storeTokenInSession($token);
  92.             return $this->redirectToRoute('app_reset_password');
  93.         }
  94.         $token = $this->getTokenFromSession();
  95.         if (null === $token) {
  96.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  97.         }
  98.         try {
  99.             $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  100.         } catch (ResetPasswordExceptionInterface $e) {
  101.             $this->addFlash('reset_password_error', sprintf(
  102.                 '%s - %s',
  103.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  104.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  105.             ));
  106.             return $this->redirectToRoute('app_forgot_password_request');
  107.         }
  108.         // The token is valid; allow the user to change their password.
  109.         $form = $this->createForm(ChangePasswordFormType::class);
  110.         $form->handleRequest($request);
  111.         if ($form->isSubmitted() && $form->isValid()) {
  112.             // A password reset token should be used only once, remove it.
  113.             $this->resetPasswordHelper->removeResetRequest($token);
  114.             // Encode(hash) the plain password, and set it.
  115.             $encodedPassword = $passwordHasher->hashPassword(
  116.                 $user,
  117.                 $form->get('plainPassword')->getData()
  118.             );
  119.             $user->setPassword($encodedPassword);
  120.             $this->entityManager->flush();
  121.             // The session is cleaned up after the password has been changed.
  122.             $this->cleanSessionAfterReset();
  123.             return $this->redirectToRoute('app_reset_success');
  124.         }
  125.         return $this->render('reset_password/reset.html.twig', [
  126.             'settings' => $this->settings,
  127.             'resetForm' => $form->createView(),
  128.         ]);
  129.     }
  130.     private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse
  131.     {
  132.         $user = $this->entityManager->getRepository(User::class)->findOneBy([
  133.             'email' => $emailFormData,
  134.         ]);
  135.         // Do not reveal whether a user account was found or not.
  136.         if (!$user) {
  137.             return $this->redirectToRoute('app_check_email');
  138.         }
  139.         try {
  140.             $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  141.         } catch (ResetPasswordExceptionInterface $e) {
  142.             // If you want to tell the user why a reset email was not sent, uncomment
  143.             // the lines below and change the redirect to 'app_forgot_password_request'.
  144.             // Caution: This may reveal if a user is registered or not.
  145.             //
  146.             // $this->addFlash('reset_password_error', sprintf(
  147.             //     '%s - %s',
  148.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  149.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  150.             // ));
  151.             return $this->redirectToRoute('app_check_email');
  152.         }
  153.         $email = (new TemplatedEmail())
  154.             ->from(new Address($this->settings->getContactEmail(), strip_tags($this->settings->getTitle())))
  155.             ->to($user->getEmail())
  156.             ->subject('Restablecer contraseƱa')
  157.             ->htmlTemplate('reset_password/email.html.twig')
  158.             ->context([
  159.                 'resetToken' => $resetToken,
  160.                 'settings' => $this->settings,
  161.             ])
  162.         ;
  163.         $mailer->send($email);
  164.         // Store the token object in session for retrieval in check-email route.
  165.         $this->setTokenObjectInSession($resetToken);
  166.         return $this->redirectToRoute('app_check_email');
  167.     }
  168. }