src/Controller/ResetPasswordController.php line 34

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