src/Controller/ResetPasswordController.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\AbstractRegisterUserType;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Service\ResetPasswordEmailFactoryInterface;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Mailer\MailerInterface;
  15. use Symfony\Component\Mime\Address;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  20. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  22. /**
  23.  * @Route("/reset-password")
  24.  */
  25. class ResetPasswordController extends AbstractController
  26. {
  27.     use ResetPasswordControllerTrait;
  28.     private ResetPasswordHelperInterface $resetPasswordHelper;
  29.     private EntityManagerInterface $entityManager;
  30.     private ResetPasswordEmailFactoryInterface $resetPasswordEmailFactory;
  31.     public function __construct(
  32.         ResetPasswordHelperInterface $resetPasswordHelper,
  33.         EntityManagerInterface $entityManager,
  34.         ResetPasswordEmailFactoryInterface $resetPasswordEmailFactory
  35.     )
  36.     {
  37.         $this->resetPasswordHelper $resetPasswordHelper;
  38.         $this->entityManager $entityManager;
  39.         $this->resetPasswordEmailFactory $resetPasswordEmailFactory;
  40.     }
  41.     /**
  42.      * Display & process form to request a password reset.
  43.      *
  44.      * @Route("", name="app_forgot_password_request")
  45.      */
  46.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  47.     {
  48.         if ($this->getUser()) return $this->redirectToRoute('main');
  49.         $form $this->createForm(ResetPasswordRequestFormType::class);
  50.         $form->handleRequest($request);
  51.         if ($form->isSubmitted() && $form->isValid()) {
  52.             return $this->processSendingPasswordResetEmail(
  53.                 $form->get('email')->getData(),
  54.                 $mailer,
  55.                 $translator
  56.             );
  57.         }
  58.         return $this->render('reset_password/request.html.twig', [
  59.             'requestForm' => $form->createView(),
  60.         ]);
  61.     }
  62.     /**
  63.      * Confirmation page after a user has requested a password reset.
  64.      *
  65.      * @Route("/check-email", name="app_check_email")
  66.      */
  67.     public function checkEmail(): Response
  68.     {
  69.         // Generate a fake token if the user does not exist or someone hit this page directly.
  70.         // This prevents exposing whether or not a user was found with the given email address or not
  71.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  72.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  73.         }
  74.         return $this->render('reset_password/check_email.html.twig', [
  75.             'resetToken' => $resetToken,
  76.         ]);
  77.     }
  78.     /**
  79.      * Validates and process the reset URL that the user clicked in their email.
  80.      *
  81.      * @Route("/reset/{token}", name="app_reset_password")
  82.      */
  83.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  84.     {
  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.             /** @var User $user */
  97.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  98.         } catch (ResetPasswordExceptionInterface $e) {
  99.             $this->addFlash('reset_password_error'sprintf(
  100.                 '%s - %s',
  101.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  102.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  103.             ));
  104.             return $this->redirectToRoute('app_forgot_password_request');
  105.         }
  106.         // The token is valid; allow the user to change their password.
  107.         $form $this->createForm(ChangePasswordFormType::class);
  108.         $form->handleRequest($request);
  109.         if ($form->isSubmitted() && $form->isValid()) {
  110.             // A password reset token should be used only once, remove it.
  111.             $this->resetPasswordHelper->removeResetRequest($token);
  112.             // Encode(hash) the plain password, and set it.
  113.             $encodedPassword $userPasswordHasher->hashPassword(
  114.                 $user,
  115.                 $form->get(AbstractRegisterUserType::PLAIN_PASSWORD_FIELD_NAME)->getData()
  116.             );
  117.             $user->setPassword($encodedPassword);
  118.             $this->entityManager->flush();
  119.             // The session is cleaned up after the password has been changed.
  120.             $this->cleanSessionAfterReset();
  121.             return $this->redirectToRoute('app_login');
  122.         }
  123.         return $this->render('reset_password/reset.html.twig', [
  124.             'resetForm' => $form->createView(),
  125.         ]);
  126.     }
  127.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  128.     {
  129.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  130.             'email' => $emailFormData,
  131.         ]);
  132.         // Do not reveal whether a user account was found or not.
  133.         if (!$user) {
  134.             return $this->redirectToRoute('app_check_email');
  135.         }
  136.         try {
  137.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  138.         } catch (ResetPasswordExceptionInterface $e) {
  139.              $this->addFlash('reset_password_error'sprintf(
  140.                  '%s - %s',
  141.                  $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  142.                  $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  143.              ));
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         $mailer->send(
  147.             $this->resetPasswordEmailFactory->getResetPasswordEmail($resetToken$user->getEmail())
  148.         );
  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. }