src/Controller/ResetPasswordController.php line 68

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 SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  8. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  9. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  10. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. #[Route('reset-password')]
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     private $translator;
  26.     public function __construct(
  27.         private ResetPasswordHelperInterface $resetPasswordHelper,
  28.         private EntityManagerInterface $entityManager,
  29.         TranslatorInterface $translator
  30.     ) {
  31.         $this->translator $translator;
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      */
  36.     #[Route('/email'name'app_forgot_password_request')]
  37.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  38.     {
  39.         // Create a form for the password reset request.
  40.         $form $this->createForm(ResetPasswordRequestFormType::class);
  41.         $form->handleRequest($request);
  42.         // Check if the form is submitted and valid.
  43.         if ($form->isSubmitted() && $form->isValid()) {
  44.             // Process the sending of the password reset email.
  45.             return $this->processSendingPasswordResetEmail(
  46.                 $form->get('email')->getData(),
  47.                 $mailer,
  48.                 $translator
  49.             );
  50.         }
  51.         $error '';
  52.         // Check if the email field is empty and display a custom error message.
  53.         if ($form->get('email')->getData() === "") {
  54.             $error = throw new CustomUserMessageAuthenticationException(
  55.                 $translator->trans('You are not an active user')
  56.             );
  57.         }
  58.         // Render the password reset request page with the form and error (if any).
  59.         return $this->render('reset_password/request.html.twig', [
  60.             'flash_error' => $error,
  61.             'requestForm' => $form->createView(),
  62.         ]);
  63.     }
  64.     /**
  65.      * Confirmation page after a user has requested a password reset.
  66.      */
  67.     #[Route('/check-email'name'app_check_email')]
  68.     public function checkEmail(): Response
  69.     {
  70.         // Generate a fake token if the user does not exist or someone hit this page directly.
  71.         // This prevents exposing whether or not a user was found with the given email address or not
  72.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  73.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  74.             // $this->resetPasswordHelper->getTokenLifetime(60);
  75.         }
  76.         return $this->render('reset_password/check_email.html.twig', [
  77.             'resetToken' => $resetToken,
  78.         ]);
  79.     }
  80.     /**
  81.      * Validates and process the reset URL that the user clicked in their email.
  82.      */
  83.     #[Route('/reset/{token}'name'app_reset_password')]
  84.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  85.     {
  86.         // If a token is provided in the URL, store it in the session and redirect to the reset route without the token.
  87.         if ($token) {
  88.             $this->storeTokenInSession($token);
  89.             return $this->redirectToRoute('app_reset_password');
  90.         }
  91.         // Retrieve the token from the session.
  92.         $token $this->getTokenFromSession();
  93.         // If no token is found in the session, throw a NotFoundException.
  94.         if (null === $token) {
  95.             throw $this->createNotFoundException($this->translator->trans('message.modules.home.error.reset_token'));
  96.         }
  97.         try {
  98.             // Validate the token and fetch the user associated with it.
  99.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  100.             // $this->resetPasswordHelper->getTokenLifetime(60);
  101.         } catch (ResetPasswordExceptionInterface $e) {
  102.             // Handle validation exceptions by adding a flash message and redirecting to the forgot password request page.
  103.             $this->addFlash('reset_password_error'sprintf(
  104.                 '%s - %s',
  105.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  106.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  107.             ));
  108.             return $this->redirectToRoute('app_forgot_password_request');
  109.         }
  110.         // Create the change password form.
  111.         $form $this->createForm(ChangePasswordFormType::class);
  112.         $form->handleRequest($request);
  113.         // Process form submission and update user password if the form is valid.
  114.         if ($form->isSubmitted() && $form->isValid()) {
  115.             $this->resetPasswordHelper->removeResetRequest($token);
  116.             // $this->resetPasswordHelper->getTokenLifetime(60);
  117.             // Hash the new password and update the user's password in the database.
  118.             $encodedPassword $passwordHasher->hashPassword(
  119.                 $user,
  120.                 $form->get('plainPassword')->getData()
  121.             );
  122.             /* if($encodedPassword==$user->getPassword()){
  123.                 return new JsonResponse([
  124.                     'status' => 'error',
  125.                     'statusCode' => '400',
  126.                     'errors' => $this->translator->trans('message.modules.error.new_password_same', [], 'api'),
  127.                 ], 200);
  128.             } */
  129.             $user->setPassword($encodedPassword);
  130.             $this->entityManager->flush();
  131.             // Add a success flash message and clean the session after a successful password reset.
  132.             $this->addFlash('success'$this->translator->trans('message.modules.success.pwd_reset'));
  133.             $this->cleanSessionAfterReset();
  134.             // Redirect to the home page.
  135.             return $this->redirectToRoute('home');
  136.         }
  137.         // Render the password reset form.
  138.         return $this->render('reset_password/reset.html.twig', [
  139.             'resetForm' => $form->createView(),
  140.         ]);
  141.     }
  142.     // Process the sending of a password reset email.
  143.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  144.     {
  145.         // Find a user with the given email address.
  146.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  147.             'email' => $emailFormData,
  148.         ]);
  149.         // If no user is found, redirect to the check email page.
  150.         if (!$user) {
  151.             return $this->redirectToRoute('app_check_email');
  152.         }
  153.         try {
  154.             // Generate a reset token using the ResetPasswordHelper service.
  155.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  156.             $this->resetPasswordHelper->getTokenLifetime(60);
  157.             
  158.         } catch (ResetPasswordExceptionInterface $e) {
  159.             // Handle exceptions during token generation by redirecting to the check email page.
  160.             return $this->redirectToRoute('app_check_email');
  161.         }
  162.         // Create and send a templated email containing the reset token.
  163.         $email = (new TemplatedEmail())
  164.             ->from(new Address('harita.raba00@gmail.com'))
  165.             ->to($user->getEmail())
  166.             ->subject('Your password reset request')
  167.             ->htmlTemplate('reset_password/email.html.twig')
  168.             ->context([
  169.                 'resetToken' => $resetToken,
  170.             ]);
  171.         $mailer->send($email);
  172.         // Set the reset token object in the session and redirect to the check email page.
  173.         $this->setTokenObjectInSession($resetToken);
  174.         return $this->redirectToRoute('app_check_email');
  175.     }
  176. }