src/Controller/ResetPasswordController.php line 53

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\EmailType;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Service\EmailService;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\BodyRenderer;
  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\Mailer;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\Mailer\Transport;
  18. use Symfony\Component\Mime\Address;
  19. use Symfony\Component\Mime\Email;
  20. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Contracts\Translation\TranslatorInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  24. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  25. use SymfonyCasts\Bundle\ResetPassword\Exception\TooManyPasswordRequestsException;
  26. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  27. use Twig\Environment;
  28. use Twig\Loader\FilesystemLoader;
  29. #[Route('/reset-password')]
  30. class ResetPasswordController extends AbstractController
  31. {
  32.     use ResetPasswordControllerTrait;
  33.     public function __construct(
  34.         private ResetPasswordHelperInterface $resetPasswordHelper,
  35.         private EntityManagerInterface $entityManager,
  36.         private Environment $twig,
  37.         private EmailService $emailService
  38.     ) {
  39.     }
  40.     /**
  41.      * Display & process form to request a password reset.
  42.      */
  43.     #[Route(''name'app_forgot_password_request')]
  44.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  45.     {
  46.         $form $this->createForm(ResetPasswordRequestFormType::class);
  47.         $form->handleRequest($request);
  48.         if ($form->isSubmitted() && $form->isValid()) {
  49.             return $this->processSendingPasswordResetEmail(
  50.                 $form->get('email')->getData(),
  51.                 $mailer,
  52.                 $translator
  53.             );
  54.         }
  55.         return $this->render('reset_password/request.html.twig', [
  56.             'requestForm' => $form->createView(),
  57.         ]);
  58.     }
  59.     /**
  60.      * Confirmation page after a user has requested a password reset.
  61.      */
  62.     #[Route('/check-email'name'app_check_email')]
  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.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  79.     {
  80.         if ($token) {
  81.             // We store the token in session and remove it from the URL, to avoid the URL being
  82.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  83.             $this->storeTokenInSession($token);
  84.             return $this->redirectToRoute('app_reset_password');
  85.         }
  86.         $token $this->getTokenFromSession();
  87.         if (null === $token) {
  88.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  89.         }
  90.         try {
  91.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  92.         } catch (ResetPasswordExceptionInterface $e) {
  93.             $this->addFlash('reset_password_error'sprintf(
  94.                 '%s - %s',
  95.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  96.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  97.             ));
  98.             return $this->redirectToRoute('app_forgot_password_request');
  99.         }
  100.         // The token is valid; allow the user to change their password.
  101.         $form $this->createForm(ChangePasswordFormType::class);
  102.         $form->handleRequest($request);
  103.         if ($form->isSubmitted() && $form->isValid()) {
  104.             // A password reset token should be used only once, remove it.
  105.             $this->resetPasswordHelper->removeResetRequest($token);
  106.             // Encode(hash) the plain password, and set it.
  107.             $encodedPassword $passwordHasher->hashPassword(
  108.                 $user,
  109.                 $form->get('plainPassword')->getData()
  110.             );
  111.             $user->setPassword($encodedPassword);
  112.             $this->entityManager->flush();
  113.             // The session is cleaned up after the password has been changed.
  114.             $this->cleanSessionAfterReset();
  115.             return $this->redirectToRoute('app_home');
  116.         }
  117.         return $this->render('reset_password/reset.html.twig', [
  118.             'resetForm' => $form->createView(),
  119.         ]);
  120.     }
  121.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  122.     {
  123.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  124.             'email' => $emailFormData,
  125.         ]);
  126.         // Do not reveal whether a user account was found or not.
  127.         if (!$user) {
  128.             $this->addFlash('notice''Apologies, this email isn\'t registered.');
  129.             return $this->redirectToRoute('app_check_email');
  130.         }
  131.         try {
  132.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  133.         } catch (ResetPasswordExceptionInterface $e) {
  134.             // If you want to tell the user why a reset email was not sent, uncomment
  135.             // the lines below and change the redirect to 'app_forgot_password_request'.
  136.             // Caution: This may reveal if a user is registered or not.
  137.             //
  138.             // $this->addFlash('reset_password_error', sprintf(
  139.             //     '%s - %s',
  140.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  141.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  142.             // ));
  143.             $this->addFlash('reset_password_error'sprintf(
  144.                  '%s - %s',
  145.                  $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  146.                  $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  147.              ));
  148.             return $this->redirectToRoute('app_forgot_password_request');
  149.             //return $this->redirectToRoute('app_check_email');
  150.         } catch (TooManyPasswordRequestsException $e){
  151.             $this->addFlash('reset_password_error'sprintf(
  152.                 '%s - %s',
  153.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  154.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  155.             ));
  156.             return $this->redirectToRoute('app_forgot_password_request');
  157.         }
  158.         $emailType $this->emailService->getEmailTypeEntityByEmailTypeCode(EmailType::RESET_PASSWORD);
  159.         $this->emailService->send(
  160.             $user,
  161.             $user->getEmail(),
  162.             "Your password reset request",
  163.             $emailType,
  164.             [
  165.                 'resetToken' => $resetToken,
  166.             ],
  167.             null
  168.         );
  169.         /*
  170.         $email = (new TemplatedEmail())
  171.             ->from(new Address('noreply@raswapa.com', 'Raswapa Mail Bot'))
  172.             ->to($user->getEmail())
  173.             ->subject('Your password reset request')
  174.             ->htmlTemplate('reset_password/email.html.twig')
  175.             ->context([
  176.                 'resetToken' => $resetToken,
  177.             ]);
  178.         $mailer->send($email);
  179.         */
  180.         /*
  181.         $dsn = "smtp://172.17.0.1:1025";
  182.         $transport = Transport::fromDsn($dsn);
  183.         $mailer = new Mailer($transport);
  184.        $twigBodyRenderer = new BodyRenderer($this->twig);
  185.        $twigBodyRenderer->render($email);
  186.         $mailer->send($email);
  187.         */
  188.         // Store the token object in session for retrieval in check-email route.
  189.         $this->setTokenObjectInSession($resetToken);
  190.         return $this->redirectToRoute('app_check_email');
  191.     }
  192. }