src/Controller/ResetPasswordController.php line 49

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\Message\ResetPasswordNotification;
  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\Messenger\MessageBusInterface;
  13. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. /**
  20.  * @Route("/reset-password")
  21.  */
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     private $resetPasswordHelper;
  26.     private $entityManager;
  27.     private $messageBus;
  28.     public function __construct(
  29.         ResetPasswordHelperInterface $resetPasswordHelper,
  30.         EntityManagerInterface $entityManager,
  31.         MessageBusInterface $messageBus
  32.     ) {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.         $this->messageBus $messageBus;
  36.     }
  37.     /**
  38.      * Display & process form to request a password reset.
  39.      *
  40.      * @Route("", name="app_forgot_password_request")
  41.      */
  42.     public function request(Request $request): Response
  43.     {
  44.         $form $this->createForm(ResetPasswordRequestFormType::class);
  45.         $form->handleRequest($request);
  46.         if ($form->isSubmitted() && $form->isValid()) {
  47.             return $this->processSendingPasswordResetEmail(
  48.                 $form->get('email')->getData()
  49.             );
  50.         }
  51.         return $this->render('reset_password/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.         ]);
  54.     }
  55.     /**
  56.      * Confirmation page after a user has requested a password reset.
  57.      *
  58.      * @Route("/check-email", name="app_check_email")
  59.      */
  60.     public function checkEmail(): Response
  61.     {
  62.         // Generate a fake token if the user does not exist or someone hit this page directly.
  63.         // This prevents exposing whether or not a user was found with the given email address or not
  64.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  65.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  66.         }
  67.         return $this->redirectToRoute('app_login');
  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.      */
  74.     public function reset(
  75.         Request $request,
  76.         UserPasswordHasherInterface $userPasswordHasher,
  77.         string $token null
  78.     ): Response {
  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.             /** @var PasswordAuthenticatedUserInterface $user */
  91.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  92.         } catch (ResetPasswordExceptionInterface $e) {
  93.             $this->addFlash(
  94.                 'reset_password_error',
  95.                 sprintf(
  96.                     'There was a problem validating your reset request - %s',
  97.                     $e->getReason()
  98.                 )
  99.             );
  100.             return $this->redirectToRoute('app_forgot_password_request');
  101.         }
  102.         // The token is valid; allow the user to change their password.
  103.         $form $this->createForm(ChangePasswordFormType::class);
  104.         $form->handleRequest($request);
  105.         if ($form->isSubmitted() && $form->isValid()) {
  106.             // A password reset token should be used only once, remove it.
  107.             $this->resetPasswordHelper->removeResetRequest($token);
  108.             // Encode(hash) the plain password, and set it.
  109.             $encodedPassword $userPasswordHasher->hashPassword(
  110.                 $user,
  111.                 $form->get('plainPassword')->getData()
  112.             );
  113.             $user->setPassword($encodedPassword);
  114.             $this->entityManager->flush();
  115.             // The session is cleaned up after the password has been changed.
  116.             $this->cleanSessionAfterReset();
  117.             $this->addFlash('success''Le mot de passe a été mis à jour avec succès');
  118.             return $this->redirectToRoute('app_login');
  119.         }
  120.         return $this->render('reset_password/reset.html.twig', [
  121.             'resetForm' => $form->createView(),
  122.             'errors' => $form->getErrors(),
  123.         ]);
  124.     }
  125.     private function processSendingPasswordResetEmail(
  126.         string $emailFormData
  127.     ): RedirectResponse {
  128.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  129.             'email' => $emailFormData,
  130.         ]);
  131.         // Do not reveal whether a user account was found or not.
  132.         if (!$user) {
  133.             return $this->redirectToRoute('app_check_email');
  134.         }
  135.         try {
  136.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  137.         } catch (ResetPasswordExceptionInterface $e) {
  138.             // If you want to tell the user why a reset email was not sent, uncomment
  139.             // the lines below and change the redirect to 'app_forgot_password_request'.
  140.             // Caution: This may reveal if a user is registered or not.
  141.             //
  142.             $this->addFlash(
  143.                 'warning',
  144.                 sprintf(
  145.                     'There was a problem handling your password reset request - %s',
  146.                     $e->getReason()
  147.                 )
  148.             );
  149.             return $this->redirectToRoute('app_check_email');
  150.         }
  151.         $this->messageBus->dispatch(new ResetPasswordNotification($user$resetToken));
  152.         // Store the token object in session for retrieval in check-email route.
  153.         $this->setTokenObjectInSession($resetToken);
  154.         $this->addFlash(
  155.             'success',
  156.             'Un e-mail a été envoyé contenant un lien sur lequel vous pouvez cliquer pour réinitialiser votre mot de passe.'
  157.         );
  158.         return $this->redirectToRoute('app_check_email');
  159.     }
  160. }