src/Controller/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the HEA package.
  4.  *
  5.  * (c) Nicolas COSTA <n.costa@horizonesport.net>
  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\Account;
  12. use App\Form\ChangePasswordFormType;
  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. #[Route('/reset-password')]
  28. class ResetPasswordController extends AbstractController
  29. {
  30.     use ResetPasswordControllerTrait;
  31.     private $resetPasswordHelper;
  32.     private $entityManager;
  33.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  34.     {
  35.         $this->resetPasswordHelper $resetPasswordHelper;
  36.         $this->entityManager $entityManager;
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      */
  41.     #[Route(''name'app_forgot_password_request')]
  42.     public function request(Request $requestMailerInterface $mailer): 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('username')->getData(),
  49.                 $mailer
  50.             );
  51.         }
  52.         return $this->render('reset_password/request.html.twig', [
  53.             'requestForm' => $form->createView(),
  54.         ]);
  55.     }
  56.     /**
  57.      * Confirmation page after a user has requested a password reset.
  58.      */
  59.     #[Route('/check-email'name'app_check_email')]
  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->render('reset_password/check_email.html.twig', [
  68.             'resetToken' => $resetToken,
  69.         ]);
  70.     }
  71.     /**
  72.      * Validates and process the reset URL that the user clicked in their email.
  73.      */
  74.     #[Route('/reset/{token}'name'app_reset_password')]
  75.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $token null): Response
  76.     {
  77.         if ($token) {
  78.             // We store the token in session and remove it from the URL, to avoid the URL being
  79.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  80.             $this->storeTokenInSession($token);
  81.             return $this->redirectToRoute('app_reset_password');
  82.         }
  83.         $token $this->getTokenFromSession();
  84.         if (null === $token) {
  85.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  86.         }
  87.         try {
  88.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  89.         } catch (ResetPasswordExceptionInterface $e) {
  90.             $this->addFlash('reset_password_error'sprintf(
  91.                 'There was a problem validating your reset request - %s',
  92.                 $e->getReason()
  93.             ));
  94.             return $this->redirectToRoute('app_forgot_password_request');
  95.         }
  96.         // The token is valid; allow the user to change their password.
  97.         $form $this->createForm(ChangePasswordFormType::class);
  98.         $form->handleRequest($request);
  99.         if ($form->isSubmitted() && $form->isValid()) {
  100.             // A password reset token should be used only once, remove it.
  101.             $this->resetPasswordHelper->removeResetRequest($token);
  102.             // Encode(hash) the plain password, and set it.
  103.             $encodedPassword $userPasswordHasher->hashPassword(
  104.                 $user,
  105.                 $form->get('plainPassword')->getData()
  106.             );
  107.             $user->setPassword($encodedPassword);
  108.             $this->entityManager->flush();
  109.             // The session is cleaned up after the password has been changed.
  110.             $this->cleanSessionAfterReset();
  111.             return $this->redirectToRoute('app_home');
  112.         }
  113.         return $this->render('reset_password/reset.html.twig', [
  114.             'resetForm' => $form->createView(),
  115.         ]);
  116.     }
  117.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  118.     {
  119.         $user $this->entityManager->getRepository(Account::class)->findOneBy([
  120.             'username' => $emailFormData,
  121.         ]);
  122.         // Do not reveal whether a user account was found or not.
  123.         if (!$user) {
  124.             return $this->redirectToRoute('app_check_email');
  125.         }
  126.         try {
  127.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  128.         } catch (ResetPasswordExceptionInterface $e) {
  129.             // If you want to tell the user why a reset email was not sent, uncomment
  130.             // the lines below and change the redirect to 'app_forgot_password_request'.
  131.             // Caution: This may reveal if a user is registered or not.
  132.             //
  133.             // $this->addFlash('reset_password_error', sprintf(
  134.             //     'There was a problem handling your password reset request - %s',
  135.             //     $e->getReason()
  136.             // ));
  137.             return $this->redirectToRoute('app_check_email');
  138.         }
  139.         $email = (new TemplatedEmail())
  140.             ->from(new Address('no-reply@horizonesport.net''Forgot Password'))
  141.             ->to($user->getUsername())
  142.             ->subject('Your password reset request')
  143.             ->htmlTemplate('reset_password/email.html.twig')
  144.             ->context([
  145.                 'resetToken' => $resetToken,
  146.             ])
  147.         ;
  148.         $mailer->send($email);
  149.         // Store the token object in session for retrieval in check-email route.
  150.         $this->setTokenObjectInSession($resetToken);
  151.         return $this->redirectToRoute('app_check_email');
  152.     }
  153. }