src/Controller/ResetPasswordController.php line 48

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 Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. /**
  21.  * @Route(
  22.  *      {
  23.  *          "es": "/{_locale}/reset-password",
  24.  *          "ca": "/{_locale}/reset-password",
  25.  *          "eu": "/{_locale}/reset-password",
  26.  *      },
  27.  *      requirements={"_locale": "%app.supported_locales%"}
  28.  * )
  29.  */
  30. class ResetPasswordController extends AbstractController
  31. {
  32.     use ResetPasswordControllerTrait;
  33.     public function __construct(
  34.         private ResetPasswordHelperInterface $resetPasswordHelper,
  35.         private EntityManagerInterface $entityManager
  36.     ) {
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      *
  41.      * @Route("", name="app_forgot_password_request")
  42.      */
  43.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  44.     {
  45.         $form $this->createForm(ResetPasswordRequestFormType::class);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('email')->getData(),
  50.                 $mailer,
  51.                 $translator
  52.             );
  53.         }
  54.         return $this->render('reset_password/request.html.twig', [
  55.             'requestForm' => $form->createView(),
  56.         ]);
  57.     }
  58.     /**
  59.      * Confirmation page after a user has requested a password reset.
  60.      *
  61.      * @Route("/check-email", name="app_check_email")
  62.      */
  63.     public function checkEmail(): Response
  64.     {
  65.         // Generate a fake token if the user does not exist or someone hit this page directly.
  66.         // This prevents exposing whether or not a user was found with the given email address or not
  67.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  68.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  69.         }
  70.         return $this->render('reset_password/check_email.html.twig', [
  71.             'resetToken' => $resetToken,
  72.         ]);
  73.     }
  74.     /**
  75.      * Validates and process the reset URL that the user clicked in their email.
  76.      *
  77.      * @Route("/reset/{token}", name="app_reset_password")
  78.      */
  79.     public function reset(
  80.         Request $request,
  81.         UserPasswordHasherInterface $userPasswordHasher,
  82.         TranslatorInterface $translator,
  83.         ?string $token null
  84.     ): Response {
  85.         if ($token) {
  86.             // We store the token in session and remove it from the URL, to avoid the URL being
  87.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  88.             $this->storeTokenInSession($token);
  89.             return $this->redirectToRoute('app_reset_password');
  90.         }
  91.         $token $this->getTokenFromSession();
  92.         if (null === $token) {
  93.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  94.         }
  95.         try {
  96.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  97.         } catch (ResetPasswordExceptionInterface $e) {
  98.             $this->addFlash('reset_password_error'sprintf(
  99.                 '%s - %s',
  100.                 $translator->trans(
  101.                     ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  102.                     [],
  103.                     'ResetPasswordBundle'
  104.                 ),
  105.                 $translator->trans(
  106.                     $e->getReason(),
  107.                     [],
  108.                     'ResetPasswordBundle'
  109.                 )
  110.             ));
  111.             return $this->redirectToRoute('app_forgot_password_request');
  112.         }
  113.         // The token is valid; allow the user to change their password.
  114.         $form $this->createForm(ChangePasswordFormType::class);
  115.         $form->handleRequest($request);
  116.         if ($form->isSubmitted() && $form->isValid()) {
  117.             // A password reset token should be used only once, remove it.
  118.             $this->resetPasswordHelper->removeResetRequest($token);
  119.             // Encode(hash) the plain password, and set it.
  120.             $encodedPassword $userPasswordHasher->hashPassword(
  121.                 $user,
  122.                 $form->get('plainPassword')->getData()
  123.             );
  124.             $user->setPassword($encodedPassword);
  125.             $this->entityManager->flush();
  126.             // The session is cleaned up after the password has been changed.
  127.             $this->cleanSessionAfterReset();
  128.             return $this->redirectToRoute('app_login');
  129.         }
  130.         return $this->render('reset_password/reset.html.twig', [
  131.             'resetForm' => $form->createView(),
  132.         ]);
  133.     }
  134.     private function processSendingPasswordResetEmail(
  135.         string $emailFormData,
  136.         MailerInterface $mailer,
  137.         TranslatorInterface $translator
  138.     ): RedirectResponse {
  139.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  140.             'email' => $emailFormData,
  141.         ]);
  142.         // Do not reveal whether a user account was found or not.
  143.         if (!$user) {
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         try {
  147.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  148.         } catch (ResetPasswordExceptionInterface $e) {
  149.             // If you want to tell the user why a reset email was not sent, uncomment
  150.             // the lines below and change the redirect to 'app_forgot_password_request'.
  151.             // Caution: This may reveal if a user is registered or not.
  152.             $this->addFlash('reset_password_error'sprintf(
  153.                 '%s - %s',
  154.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  155.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  156.             ));
  157.             return $this->redirectToRoute('app_check_email');
  158.         }
  159.         $sender_email $this->getParameter('sender_email');
  160.         $subject $translator->trans('email.password_change_request');
  161.         $email = (new TemplatedEmail())
  162.             ->from(new Address(
  163.                 $sender_email,
  164.                 $translator->trans('login.platform')
  165.             ))
  166.             ->to($user->getEmail())
  167.             ->subject($subject)
  168.             ->htmlTemplate('reset_password/email.html.twig')
  169.             ->context([
  170.                 'resetToken' => $resetToken,
  171.             ]);
  172.         $mailer->send($email);
  173.         // Store the token object in session for retrieval in check-email route.
  174.         $this->setTokenObjectInSession($resetToken);
  175.         return $this->redirectToRoute('app_check_email');
  176.     }
  177. }