src/Controller/ResetPasswordController.php line 52

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Kreno package.
  4.  *
  5.  * (c) Valentin Van Meeuwen <contact@wikub.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace App\Controller;
  11. use App\Entity\User;
  12. use App\Form\ResetPasswordFormType;
  13. use App\Form\ResetPasswordRequestFormType;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Mailer\MailerInterface;
  21. use Symfony\Component\Mime\Address;
  22. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  25. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  26. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  27. /**
  28.  * @Route("/reset-password")
  29.  */
  30. class ResetPasswordController extends AbstractController
  31. {
  32.     use ResetPasswordControllerTrait;
  33.     private $resetPasswordHelper;
  34.     private $entityManager;
  35.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  36.     {
  37.         $this->resetPasswordHelper $resetPasswordHelper;
  38.         $this->entityManager $entityManager;
  39.     }
  40.     /**
  41.      * Display & process form to request a password reset.
  42.      *
  43.      * @Route("", name="app_forgot_password_request")
  44.      */
  45.     public function request(Request $requestMailerInterface $mailer): Response
  46.     {
  47.         $form $this->createForm(ResetPasswordRequestFormType::class);
  48.         $form->handleRequest($request);
  49.         if ($form->isSubmitted() && $form->isValid()) {
  50.             return $this->processSendingPasswordResetEmail(
  51.                 $form->get('email')->getData(),
  52.                 $mailer
  53.             );
  54.         }
  55.         return $this->render('reset_password/request.html.twig', [
  56.             'requestForm' => $form->createView(),
  57.         ]);
  58.     }
  59.     /**
  60.      * Confirmation page after a user has requested a password reset.
  61.      *
  62.      * @Route("/check-email", name="app_check_email")
  63.      */
  64.     public function checkEmail(): Response
  65.     {
  66.         // Generate a fake token if the user does not exist or someone hit this page directly.
  67.         // This prevents exposing whether or not a user was found with the given email address or not
  68.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  69.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  70.         }
  71.         return $this->render('reset_password/check_email.html.twig', [
  72.             'resetToken' => $resetToken,
  73.         ]);
  74.     }
  75.     /**
  76.      * Validates and process the reset URL that the user clicked in their email.
  77.      *
  78.      * @Route("/reset/{token}", name="app_reset_password")
  79.      */
  80.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $token null): Response
  81.     {
  82.         if ($token) {
  83.             // We store the token in session and remove it from the URL, to avoid the URL being
  84.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  85.             $this->storeTokenInSession($token);
  86.             return $this->redirectToRoute('app_reset_password');
  87.         }
  88.         $token $this->getTokenFromSession();
  89.         if (null === $token) {
  90.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  91.         }
  92.         try {
  93.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  94.         } catch (ResetPasswordExceptionInterface $e) {
  95.             $this->addFlash('reset_password_error'sprintf(
  96.                 'There was a problem validating your reset request - %s',
  97.                 $e->getReason()
  98.             ));
  99.             return $this->redirectToRoute('app_forgot_password_request');
  100.         }
  101.         // The token is valid; allow the user to change their password.
  102.         $form $this->createForm(ResetPasswordFormType::class);
  103.         $form->handleRequest($request);
  104.         if ($form->isSubmitted() && $form->isValid()) {
  105.             // A password reset token should be used only once, remove it.
  106.             $this->resetPasswordHelper->removeResetRequest($token);
  107.             // Encode(hash) the plain password, and set it.
  108.             $encodedPassword $userPasswordHasher->hashPassword(
  109.                 $user,
  110.                 $form->get('plainPassword')->getData()
  111.             );
  112.             $user->setPassword($encodedPassword);
  113.             $this->entityManager->flush();
  114.             // The session is cleaned up after the password has been changed.
  115.             $this->cleanSessionAfterReset();
  116.             return $this->redirectToRoute('login');
  117.         }
  118.         return $this->render('reset_password/reset.html.twig', [
  119.             'resetForm' => $form->createView(),
  120.         ]);
  121.     }
  122.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  123.     {
  124.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  125.             'email' => $emailFormData,
  126.         ]);
  127.         // Do not reveal whether a user account was found or not.
  128.         if (!$user) {
  129.             return $this->redirectToRoute('app_check_email');
  130.         }
  131.         try {
  132.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  133.         } catch (ResetPasswordExceptionInterface $e) {
  134.             // If you want to tell the user why a reset email was not sent, uncomment
  135.             // the lines below and change the redirect to 'app_forgot_password_request'.
  136.             // Caution: This may reveal if a user is registered or not.
  137.             //
  138.             // $this->addFlash('reset_password_error', sprintf(
  139.             //     'There was a problem handling your password reset request - %s',
  140.             //     $e->getReason()
  141.             // ));
  142.             return $this->redirectToRoute('app_check_email');
  143.         }
  144.         $email = (new TemplatedEmail())
  145.             ->from(new Address('contact@cooplasource.fr''Kreno : La source'))
  146.             ->to($user->getEmail())
  147.             ->subject('Votre demande de rĂ©initialisation de mot de passe')
  148.             ->htmlTemplate('reset_password/email.html.twig')
  149.             ->context([
  150.                 'resetToken' => $resetToken,
  151.             ])
  152.         ;
  153.         $mailer->send($email);
  154.         // Store the token object in session for retrieval in check-email route.
  155.         $this->setTokenObjectInSession($resetToken);
  156.         return $this->redirectToRoute('app_check_email');
  157.     }
  158. }