src/Controller/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use Symfony\Component\Mime\Address;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\Mailer\MailerInterface;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     private $params;
  29.     private $manager;
  30.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperParameterBagInterface $paramsEntityManagerInterface $manager)
  31.     {
  32.         $this->resetPasswordHelper $resetPasswordHelper;
  33.         $this->params $params;
  34.         $this->manager $manager;
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      *
  39.      * @Route("", name="app_forgot_password_request")
  40.      */
  41.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  42.     {
  43.         $form $this->createForm(ResetPasswordRequestFormType::class);
  44.         $form->handleRequest($request);
  45.         if ($form->isSubmitted() && $form->isValid()) {
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $form->get('email')->getData(),
  48.                 $mailer,
  49.                 $translator
  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.      */
  61.     public function checkEmail(): Response
  62.     {
  63.         // Generate a fake token if the user does not exist or someone hit this page directly.
  64.         // This prevents exposing whether or not a user was found with the given email address or not
  65.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  66.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  67.         }
  68.         return $this->render('reset_password/check_email.html.twig', [
  69.             'resetToken' => $resetToken,
  70.         ]);
  71.     }
  72.     /**
  73.      * Validates and process the reset URL that the user clicked in their email.
  74.      *
  75.      * @Route("/reset/{token}", name="app_reset_password")
  76.      */
  77.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherInterfacestring $token nullTranslatorInterface $translator): Response
  78.     {
  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.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  91.         } catch (ResetPasswordExceptionInterface $e) {
  92.             $this->addFlash('reset_password_error'sprintf(
  93.                 'There was a problem validating your reset request - %s',
  94.                 $e->getReason()
  95.             ));
  96.             return $this->redirectToRoute('app_forgot_password_request');
  97.         }
  98.         // The token is valid; allow the user to change their password.
  99.         $form $this->createForm(ChangePasswordFormType::class);
  100.         $form->handleRequest($request);
  101.         if ($form->isSubmitted() && $form->isValid()) {
  102.             // A password reset token should be used only once, remove it.
  103.             $this->resetPasswordHelper->removeResetRequest($token);
  104.             // Encode(hash) the plain password, and set it.
  105.             $encodedPassword $userPasswordHasherInterface->hashPassword(
  106.                 $user,
  107.                 $form->get('plainPassword')->getData()
  108.             );
  109.             $user->setPassword($encodedPassword);
  110.             $this->manager->flush();
  111.             // The session is cleaned up after the password has been changed.
  112.             $this->cleanSessionAfterReset();
  113.             $this->addFlash('success'$translator->trans('resetpswd.flashok'));
  114.             return $this->redirectToRoute('app_login');
  115.         }
  116.         return $this->render('reset_password/reset.html.twig', [
  117.             'resetForm' => $form->createView(),
  118.         ]);
  119.     }
  120.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  121.     {
  122.         $user $this->manager->getRepository(User::class)->findOneBy([
  123.             'email' => $emailFormData,
  124.         ]);
  125.         // Do not reveal whether a user account was found or not.
  126.         if (!$user) {
  127.             return $this->redirectToRoute('app_check_email');
  128.         }
  129.         try {
  130.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  131.         } catch (ResetPasswordExceptionInterface $e) {
  132.             // If you want to tell the user why a reset email was not sent, uncomment
  133.             // the lines below and change the redirect to 'app_forgot_password_request'.
  134.             // Caution: This may reveal if a user is registered or not.
  135.             //
  136.             // $this->addFlash('reset_password_error', sprintf(
  137.             //     'There was a problem handling your password reset request - %s',
  138.             //     $e->getReason()
  139.             // ));
  140.             return $this->redirectToRoute('app_check_email');
  141.         }
  142.         $email = (new TemplatedEmail())
  143.             ->from(new Address($this->params->get('app.sendermail'), $this->params->get('app.title')))
  144.             ->to($user->getEmail())
  145.             ->subject($translator->trans('resetpwsd.subject', [], 'email'))
  146.             ->htmlTemplate('reset_password/email.html.twig')
  147.             ->context([
  148.                 'resetToken' => $resetToken,
  149.             ])
  150.         ;
  151.         $mailer->send($email);
  152.         // Store the token object in session for retrieval in check-email route.
  153.         $this->setTokenObjectInSession($resetToken);
  154.         return $this->redirectToRoute('app_check_email');
  155.     }
  156. }