src/Controller/ResetPasswordController.php line 39

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