src/Controller/ResetPasswordController.php line 45

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 Symfony\Bridge\Twig\Mime\TemplatedEmail;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. use Twig\Markup;
  20. /**
  21.  * @Route("/reset-password")
  22.  */
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $resetPasswordHelper;
  27.     private $session;
  28.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperSessionInterface $session)
  29.     {
  30.         $this->session $session;
  31.         $this->resetPasswordHelper $resetPasswordHelper;
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      *
  36.      * @Route("", name="app_forgot_password_request")
  37.      */
  38.     public function request(Request $requestMailerInterface $mailer): Response
  39.     {
  40.         $form $this->createForm(ResetPasswordRequestFormType::class);
  41.         $form->handleRequest($request);
  42.         if ($form->isSubmitted() && $form->isValid()) {
  43.             return $this->processSendingPasswordResetEmail(
  44.                 $form->get('email')->getData(),
  45.                 $mailer
  46.             );
  47.         }
  48.         return $this->render('reset_password/request.html.twig', [
  49.             'requestForm' => $form->createView(),
  50.         ]);
  51.     }
  52.     /**
  53.      * Confirmation page after a user has requested a password reset.
  54.      *
  55.      * @Route("/check-email", name="app_check_email")
  56.      */
  57.     public function checkEmail(): Response
  58.     {
  59.         // We prevent users from directly accessing this page
  60.         if (!$this->canCheckEmail()) {
  61.             return $this->redirectToRoute('app_forgot_password_request');
  62.         }
  63.         return $this->render('reset_password/check_email.html.twig', [
  64.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  65.         ]);
  66.     }
  67.     /**
  68.      * Validates and process the reset URL that the user clicked in their email.
  69.      *
  70.      * @Route("/reset/{token}", name="app_reset_password")
  71.      */
  72.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  73.     {
  74.         if ($token) {
  75.             // We store the token in session and remove it from the URL, to avoid the URL being
  76.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  77.             $this->storeTokenInSession($token);
  78.             return $this->redirectToRoute('app_reset_password');
  79.         }
  80.         $token $this->getTokenFromSession();
  81.         if (null === $token) {
  82.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  83.         }
  84.         try {
  85.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  86.         } catch (ResetPasswordExceptionInterface $e) {
  87.             $this->addFlash('reset_password_error'sprintf(
  88.                 'There was a problem validating your reset request - %s',
  89.                 $e->getReason()
  90.             ));
  91.             return $this->redirectToRoute('app_forgot_password_request');
  92.         }
  93.         // The token is valid; allow the user to change their password.
  94.         $form $this->createForm(ChangePasswordFormType::class);
  95.         $form->handleRequest($request);
  96.         if ($form->isSubmitted() && $form->isValid()) {
  97.             // A password reset token should be used only once, remove it.
  98.             $this->resetPasswordHelper->removeResetRequest($token);
  99.             // Encode the plain password, and set it.
  100.             $encodedPassword $passwordEncoder->encodePassword(
  101.                 $user,
  102.                 $form->get('plainPassword')->getData()
  103.             );
  104.             $user->setPassword($encodedPassword);
  105.             $this->getDoctrine()->getManager()->flush();
  106.             // The session is cleaned up after the password has been changed.
  107.             $this->cleanSessionAfterReset();
  108.             return $this->redirectToRoute('app_home');
  109.         }
  110.         return $this->render('reset_password/reset.html.twig', [
  111.             'resetForm' => $form->createView(),
  112.         ]);
  113.     }
  114.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  115.     {
  116.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  117.             'email' => $emailFormData,
  118.         ]);
  119.         // Marks that you are allowed to see the app_check_email page.
  120.         $this->setCanCheckEmailInSession();
  121.         // Do not reveal whether a user account was found or not.
  122.         if (!$user) {
  123.             // return $this->redirectToRoute('app_check_email');
  124.             return $this->redirectToRoute('app_login');
  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.             return $this->redirectToRoute('app_forgot_password_request');
  139.         }
  140.         $email = (new TemplatedEmail())
  141.             ->from(new Address('mailer@example.com''Enjazi mail bot'))
  142.             ->to($user->getEmail())
  143.             ->subject('Your password reset request')
  144.             ->htmlTemplate('reset_password/email.html.twig')
  145.             ->context([
  146.                 'userName' => $user->getFullName(),
  147.                 'resetToken' => $resetToken,
  148.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  149.             ])
  150.         ;
  151.         $mailer->send($email);
  152.         // Remove the flash message if not needed to display a flash message and display the page
  153.         $message = new Markup(
  154.             $this->renderView('reset_password/check_email.html.twig'),
  155.             'UTF-8'
  156.         );
  157.         $this->session->getFlashBag()->add('success'$message);
  158.         // return $this->redirectToRoute('app_check_email');
  159.         return $this->redirectToRoute('app_login');
  160.     }
  161. }