src/Controller/ResetPasswordController.php line 41

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use App\Session\FlashMessageInterface;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  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 readonly ResetPasswordHelperInterface $resetPasswordHelper,
  28.         private readonly EntityManagerInterface $entityManager
  29.     ) {
  30.     }
  31.     /**
  32.      * Display & process form to request a password reset.
  33.      */
  34.     #[Route('/'name'app_reset_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_reset_password_check_email')]
  54.     public function checkEmail(): Response
  55.     {
  56.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  57.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  58.         }
  59.         return $this->render('reset_password/check_email.html.twig', [
  60.             'resetToken' => $resetToken,
  61.         ]);
  62.     }
  63.     /**
  64.      * Validates and process the reset URL that the user clicked in their email.
  65.      */
  66.     #[Route('/reset/{token}'name'app_reset_password_reset')]
  67.     public function reset(Request $requestUserPasswordHasherInterface $hasherstring $token null): Response {
  68.         if ($token) {
  69.             // We store the token in session and remove it from the URL, to avoid the URL being
  70.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  71.             $this->storeTokenInSession($token);
  72.             return $this->redirectToRoute('app_reset_password_reset');
  73.         }
  74.         $token $this->getTokenFromSession();
  75.         if (null === $token) {
  76.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  77.         }
  78.         try {
  79.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  80.         } catch (ResetPasswordExceptionInterface $e) {
  81.             $this->addFlash(
  82.                 FlashMessageInterface::ERROR,
  83.                 sprintf(
  84.                     'There was a problem validating your reset request - %s',
  85.                     $e->getReason()
  86.                 )
  87.             );
  88.             return $this->redirectToRoute('app_reset_password_request');
  89.         }
  90.         // The token is valid; allow the user to change their password.
  91.         $form $this->createForm(ChangePasswordFormType::class);
  92.         $form->handleRequest($request);
  93.         if ($form->isSubmitted() && $form->isValid() && ($user instanceof User)) {
  94.             $this->resetPasswordHelper->removeResetRequest($token);
  95.             $encodedPassword $hasher->hashPassword(
  96.                 $user,
  97.                 $form->get('plainPassword')->getData()
  98.             );
  99.             $user->setPassword($encodedPassword);
  100.             $this->entityManager->flush();
  101.             $this->cleanSessionAfterReset();
  102.             return $this->redirectToRoute('app_gestion_dashboard_index');
  103.         }
  104.         return $this->render('reset_password/reset.html.twig', [
  105.             'resetForm' => $form->createView(),
  106.         ]);
  107.     }
  108.     private function processSendingPasswordResetEmail(
  109.         string $emailData,
  110.         MailerInterface $mailer,
  111.         TranslatorInterface $translator
  112.     ): RedirectResponse {
  113.         $user $this->entityManager
  114.             ->getRepository(User::class)
  115.             ->findOneBy([
  116.                 'email' => $emailData,
  117.             ]);
  118.         // Do not reveal whether a user account was found or not.
  119.         if (!$user) {
  120.             return $this->redirectToRoute('app_reset_password_check_email');
  121.         }
  122.         try {
  123.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  124.         } catch (ResetPasswordExceptionInterface $e) {
  125.             $this->addFlash(
  126.                 FlashMessageInterface::ERROR,
  127.                 sprintf(
  128.                     'There was a problem handling your password reset request - %s',
  129.                     $e->getReason()
  130.                 )
  131.             );
  132.             return $this->redirectToRoute('app_reset_password_check_email');
  133.         }
  134.         $email = (new TemplatedEmail())
  135.             ->to($user->getEmail())
  136.             ->subject($translator->trans('Your password reset request'))
  137.             ->htmlTemplate('mail/reset_password/email.html.twig')
  138.             ->context([
  139.                 'resetToken' => $resetToken,
  140.                 'expirationDate' => $resetToken->getExpiresAt(),
  141.             ]);
  142.         try {
  143.             $mailer->send($email);
  144.         } catch (TransportExceptionInterface $e) {
  145.             $this->addFlash(
  146.                 FlashMessageInterface::ERROR,
  147.                 sprintf(
  148.                     'Sending message failed - %s',
  149.                     $e->getMessage()
  150.                 )
  151.             );
  152.         }
  153.         $this->setTokenObjectInSession($resetToken);
  154.         return $this->redirectToRoute('app_reset_password_check_email');
  155.     }
  156. }