src/Controller/Dashboard/ResetPasswordController.php line 42

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Dashboard;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use App\Service\MailerManager;
  7. use Doctrine\ORM\EntityManagerInterface;
  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\PasswordHasher\Hasher\UserPasswordHasherInterface;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Contracts\Translation\TranslatorInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. #[Route('/login/reset-password')]
  20. class ResetPasswordController extends AbstractController
  21. {
  22.     use ResetPasswordControllerTrait;
  23.     private ResetPasswordHelperInterface $resetPasswordHelper;
  24.     private EntityManagerInterface $entityManager;
  25.     private MailerManager $mailerManager;
  26.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerMailerManager $mailerManager)
  27.     {
  28.         $this->resetPasswordHelper $resetPasswordHelper;
  29.         $this->entityManager $entityManager;
  30.         $this->mailerManager $mailerManager;
  31.     }
  32.     /**
  33.      * Display & process form to request a password reset.
  34.      */
  35.     #[Route('/'name'app_forgot_password_request')]
  36.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  37.     {
  38.         $form $this->createForm(ResetPasswordRequestFormType::class);
  39.         $form->handleRequest($request);
  40.         if ($form->isSubmitted() && $form->isValid()) {
  41.             return $this->processSendingPasswordResetEmail(
  42.                 $form->get('email')->getData(),
  43.                 $mailer,
  44.                 $translator
  45.             );
  46.         }
  47.         return $this->render('dashboard/reset_password/request.html.twig', [
  48.             'requestForm' => $form->createView(),
  49.         ]);
  50.     }
  51.     /**
  52.      * Validates and process the reset URL that the user clicked in their email.
  53.      */
  54.     #[Route('/reset/{token}'name'app_reset_password')]
  55.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  56.     {
  57.         if ($token) {
  58.             // We store the token in session and remove it from the URL, to avoid the URL being
  59.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  60.             $this->storeTokenInSession($token);
  61.             return $this->redirectToRoute('app_reset_password');
  62.         }
  63.         $token $this->getTokenFromSession();
  64.         if (null === $token) {
  65.             throw $this->createNotFoundException('Aucun jeton de réinitialisation du mot de passe n\'a été trouvé dans l\URL ou dans la session.');
  66.         }
  67.         try {
  68.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  69.         } catch (ResetPasswordExceptionInterface $e) {
  70.             $this->addFlash('danger''Votre demande de changement de mot de passe a expiré');
  71.             return $this->redirectToRoute('app_forgot_password_request');
  72.         }
  73.         // The token is valid; allow the user to change their password.
  74.         $form $this->createForm(ChangePasswordFormType::class);
  75.         $form->handleRequest($request);
  76.         if ($form->isSubmitted() && $form->isValid()) {
  77.             // A password reset token should be used only once, remove it.
  78.             $this->resetPasswordHelper->removeResetRequest($token);
  79.             // Encode(hash) the plain password, and set it.
  80.             $encodedPassword $userPasswordHasher->hashPassword(
  81.                 $user,
  82.                 $form->get('plainPassword')->getData()
  83.             );
  84.             $user->setPassword($encodedPassword);
  85.             $this->entityManager->flush();
  86.             // The session is cleaned up after the password has been changed.
  87.             $this->cleanSessionAfterReset();
  88.             $this->addFlash('success''Modification du mot de passe avec succès');
  89.             return $this->redirectToRoute('login');
  90.         }
  91.         return $this->render('dashboard/reset_password/reset.html.twig', [
  92.             'resetForm' => $form->createView(),
  93.         ]);
  94.     }
  95.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  96.     {
  97.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  98.             'email' => $emailFormData,
  99.         ]);
  100.         // Do not reveal whether a user account was found or not.
  101.         if (!$user) {
  102.             $this->addFlash('danger''Impossible de trouver l\'adresse email');
  103.             return $this->redirectToRoute('app_forgot_password_request');
  104.         }
  105.         try {
  106.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  107.         } catch (TooManyPasswordRequestsException $e) {
  108.             $this->addFlash('danger''Une erreur est survenu');
  109.             return $this->redirectToRoute('app_forgot_password_request');
  110.         } catch (ResetPasswordExceptionInterface $e) {
  111.             $this->addFlash('danger''Une erreur est survenu');
  112.             return $this->redirectToRoute('app_forgot_password_request');
  113.         }
  114.         $this->mailerManager->sendMailResetPassword($user$resetToken->getToken());
  115.         $this->addFlash('success''Envoi du courriel de réinitialisation du mot de passe');
  116.         // Store the token object in session for retrieval in check-email route.
  117.         $this->setTokenObjectInSession($resetToken);
  118.         return $this->redirectToRoute('app_forgot_password_request');
  119.     }
  120. }