src/Controller/ResetPasswordController.php line 38

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. #[Route('/reset-password')]
  21. class ResetPasswordController extends AbstractController
  22. {
  23.     use ResetPasswordControllerTrait;
  24.     public function __construct(protected ResetPasswordHelperInterface $resetPasswordHelper,
  25.                                 protected EntityManagerInterface       $entityManager,
  26.                                 protected TranslatorInterface          $translator)
  27.     {
  28.     }
  29.     /**
  30.      * Display & process form to request a password reset.
  31.      */
  32.     #[Route(''name'app_forgot_password_request')]
  33.     public function request(Request $requestMailerInterface $mailer): Response
  34.     {
  35.         $form $this->createForm(ResetPasswordRequestFormType::class);
  36.         $form->handleRequest($request);
  37.         if ($form->isSubmitted() && $form->isValid()) {
  38.             return $this->processSendingPasswordResetEmail(
  39.                 $form->get('email')->getData(),
  40.                 $mailer
  41.             );
  42.         }
  43.         return $this->render('reset_password/request.html.twig', [
  44.             'requestForm' => $form->createView(),
  45.         ]);
  46.     }
  47.     /**
  48.      * Confirmation page after a user has requested a password reset.
  49.      */
  50.     #[Route('/check-email'name'app_check_email')]
  51.     public function checkEmail(): Response
  52.     {
  53.         // Generate a fake token if the user does not exist or someone hit this page directly.
  54.         // This prevents exposing whether or not a user was found with the given email address or not
  55.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  56.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  57.         }
  58.         return $this->render('reset_password/check_email.html.twig', [
  59.             'resetToken' => $resetToken,
  60.         ]);
  61.     }
  62.     /**
  63.      * Validates and process the reset URL that the user clicked in their email.
  64.      */
  65.     #[Route('/reset/{token}'name'app_reset_password')]
  66.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $token null): Response
  67.     {
  68.         if ($token) {
  69.             // We store the token in session and remove it from the URL, to avoid the URL being
  70.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  71.             $this->storeTokenInSession($token);
  72.             return $this->redirectToRoute('app_reset_password');
  73.         }
  74.         $token $this->getTokenFromSession();
  75.         if (null === $token) {
  76.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  77.         }
  78.         try {
  79.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  80.         } catch (ResetPasswordExceptionInterface $e) {
  81.             $this->addFlash('reset_password_error'$this->translator->trans('rp.info.text.link.expired'));
  82.             return $this->redirectToRoute('app_forgot_password_request');
  83.         }
  84.         // The token is valid; allow the user to change their password.
  85.         $form $this->createForm(ChangePasswordFormType::class);
  86.         $form->handleRequest($request);
  87.         if ($form->isSubmitted() && $form->isValid()) {
  88.             // A password reset token should be used only once, remove it.
  89.             $this->resetPasswordHelper->removeResetRequest($token);
  90.             // Encode(hash) the plain password, and set it.
  91.             $encodedPassword $userPasswordHasher->hashPassword(
  92.                 $user,
  93.                 $form->get('plainPassword')->getData()
  94.             );
  95.             $user->setPassword($encodedPassword);
  96.             $this->entityManager->flush();
  97.             // The session is cleaned up after the password has been changed.
  98.             $this->cleanSessionAfterReset();
  99.             return $this->redirectToRoute('app_login');
  100.         }
  101.         return $this->render('reset_password/reset.html.twig', [
  102.             'resetForm' => $form->createView(),
  103.         ]);
  104.     }
  105.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  106.     {
  107.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  108.             'email' => $emailFormData,
  109.         ]);
  110.         // Do not reveal whether a user account was found or not.
  111.         if (!$user) {
  112.             return $this->redirectToRoute('app_check_email');
  113.         }
  114.         try {
  115.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  116.         } catch (ResetPasswordExceptionInterface $e) {
  117.             // If you want to tell the user why a reset email was not sent, uncomment
  118.             // the lines below and change the redirect to 'app_forgot_password_request'.
  119.             // Caution: This may reveal if a user is registered or not.
  120.             //
  121.             // $this->addFlash('reset_password_error', sprintf(
  122.             //     'There was a problem handling your password reset request - %s',
  123.             //     $e->getReason()
  124.             // ));
  125.             return $this->redirectToRoute('app_check_email');
  126.         }
  127.         $email = (new TemplatedEmail())
  128.             ->from(new Address('livenexx66@gmail.com''fleet_car_services'))
  129.             ->to($user->getEmail())
  130.             ->subject('Your password reset request')
  131.             ->htmlTemplate('reset_password/email.html.twig')
  132.             ->context([
  133.                 'resetToken' => $resetToken,
  134.             ]);
  135.         $mailer->send($email);
  136.         // Store the token object in session for retrieval in check-email route.
  137.         $this->setTokenObjectInSession($resetToken);
  138.         return $this->redirectToRoute('app_check_email');
  139.     }
  140. }