src/Controller/ResetPasswordController.php line 44

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\Repository\UserRepository;
  7. use App\Service\EmailService;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  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. #[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.         private readonly MailerInterface              $mailer,
  30.         private readonly UserRepository               $userRepository,
  31.         private readonly EmailService                 $emailService,
  32.     )
  33.     {
  34.     }
  35.     /**
  36.      * Display & process form to request a password reset.
  37.      */
  38.     #[Route(''name'app_forgot_password_request')]
  39.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $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.         ]);
  53.     }
  54.     /**
  55.      * Confirmation page after a user has requested a password reset.
  56.      */
  57.     #[Route('/check-email'name'app_check_email')]
  58.     public function checkEmail(): Response
  59.     {
  60.         // Generate a fake token if the user does not exist or someone hit this page directly.
  61.         // This prevents exposing whether or not a user was found with the given email address or not
  62.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  63.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  64.         }
  65.         return $this->render('reset_password/check_email.html.twig', [
  66.             'resetToken' => $resetToken,
  67.         ]);
  68.     }
  69.     /**
  70.      * Validates and process the reset URL that the user clicked in their email.
  71.      */
  72.     #[Route('/reset/{token}'name'app_reset_password')]
  73.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  74.     {
  75.         if ($token) {
  76.             // We store the token in session and remove it from the URL, to avoid the URL being
  77.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  78.             $this->storeTokenInSession($token);
  79.             return $this->redirectToRoute('app_reset_password');
  80.         }
  81.         $token $this->getTokenFromSession();
  82.         if (null === $token) {
  83.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  84.         }
  85.         try {
  86.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  87.         } catch (ResetPasswordExceptionInterface $e) {
  88.             $this->addFlash('reset_password_error'sprintf(
  89.                 '%s - %s',
  90.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  91.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  92.             ));
  93.             return $this->redirectToRoute('app_forgot_password_request');
  94.         }
  95.         // The token is valid; allow the user to change their password.
  96.         $form $this->createForm(ChangePasswordFormType::class);
  97.         $form->handleRequest($request);
  98.         if ($form->isSubmitted() && $form->isValid()) {
  99.             // A password reset token should be used only once, remove it.
  100.             $this->resetPasswordHelper->removeResetRequest($token);
  101.             // Encode(hash) the plain password, and set it.
  102.             $encodedPassword $passwordHasher->hashPassword(
  103.                 $user,
  104.                 $form->get('plainPassword')->getData()
  105.             );
  106.             $user->setPassword($encodedPassword);
  107.             $this->entityManager->flush();
  108.             // The session is cleaned up after the password has been changed.
  109.             $this->cleanSessionAfterReset();
  110.             return $this->redirectToRoute('app_home');
  111.         }
  112.         return $this->render('reset_password/reset.html.twig', [
  113.             'resetForm' => $form->createView(),
  114.         ]);
  115.     }
  116.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  117.     {
  118.         $user $this->userRepository->findOneBy([
  119.                                                      'email' => $emailFormData,
  120.                                                  ]);
  121.         // Do not reveal whether a user account was found or not.
  122.         if (!$user) {
  123.             return $this->redirectToRoute('app_check_email');
  124.         }
  125.         try {
  126.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  127.         } catch (ResetPasswordExceptionInterface $e) {
  128.             // If you want to tell the user why a reset email was not sent, uncomment
  129.             // the lines below and change the redirect to 'app_forgot_password_request'.
  130.             // Caution: This may reveal if a user is registered or not.
  131.             //
  132.             // $this->addFlash('reset_password_error', sprintf(
  133.             //     '%s - %s',
  134.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  135.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  136.             // ));
  137.             return $this->redirectToRoute('app_check_email');
  138.         }
  139.         if ($this->emailService->isEmailSendingAllowedTo('app.allow_send_emails_user_reset_password')) {
  140.             $data = [
  141.                 'resetToken' => $resetToken,
  142.             ];
  143.             $email $this->emailService->sendEmail(
  144.                 $this->emailService->getEmailSender(),
  145.                 $user->getEmail(),
  146.                 'Votre demande de rĂ©initialisation de mot de passe',
  147.                 'reset_password/email.html.twig',
  148.                 $data,
  149.             );
  150.             if($email$this->mailer->send($email);
  151.         }
  152.         // Store the token object in session for retrieval in check-email route.
  153.         $this->setTokenObjectInSession($resetToken);
  154.         return $this->redirectToRoute('app_check_email');
  155.     }
  156. }