src/Controller/ResetPasswordController.php line 49

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 App\Service\MailerService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bridge\Twig\Mime\BodyRenderer;
  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\Mailer;
  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\Routing\Generator\UrlGeneratorInterface;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  22. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. use Twig\Environment;
  25. use Twig\Loader\FilesystemLoader;
  26. #[Route('/reset-password')]
  27. class ResetPasswordController extends AbstractController
  28. {
  29.     use ResetPasswordControllerTrait;
  30.     private ResetPasswordHelperInterface $resetPasswordHelper;
  31.     private EntityManagerInterface $entityManager;
  32.     private $mailer;
  33.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $entityManager, MailerService $mailerService)
  34.     {
  35.         $this->resetPasswordHelper = $resetPasswordHelper;
  36.         $this->entityManager = $entityManager;
  37.         $this->mailer = $mailerService->getMailer();
  38.     }
  39.     /**
  40.      * Display & process form to request a password reset.
  41.      */
  42.     #[Route('', name: 'app_forgot_password_request')]
  43.     public function request(Request $request, TranslatorInterface $translator): Response
  44.     {
  45.         $form = $this->createForm(ResetPasswordRequestFormType::class);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('email')->getData(),
  50.                 $this->mailer,
  51.                 $translator
  52.             );
  53.         }
  54.         return $this->render('reset_password/request.html.twig', [
  55.             'requestForm' => $form->createView(),
  56.         ]);
  57.     }
  58.     /**
  59.      * Confirmation page after a user has requested a password reset.
  60.      */
  61.     #[Route('/check-email', name: 'app_check_email')]
  62.     public function checkEmail(): Response
  63.     {
  64.         // Generate a fake token if the user does not exist or someone hit this page directly.
  65.         // This prevents exposing whether or not a user was found with the given email address or not
  66.         if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  67.             $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  68.         }
  69.         return $this->render('reset_password/check_email.html.twig', [
  70.             'resetToken' => $resetToken,
  71.         ]);
  72.     }
  73.     /**
  74.      * Validates and process the reset URL that the user clicked in their email.
  75.      */
  76.     #[Route('/reset/{token}', name: 'app_reset_password')]
  77.     public function reset(Request $request, UserPasswordHasherInterface $userPasswordHasher, TranslatorInterface $translator, string $token = null): Response
  78.     {
  79.         if ($token) {
  80.             // We store the token in session and remove it from the URL, to avoid the URL being
  81.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  82.             $this->storeTokenInSession($token);
  83.             return $this->redirectToRoute('app_reset_password');
  84.         }
  85.         $token = $this->getTokenFromSession();
  86.         if (null === $token) {
  87.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  88.         }
  89.         try {
  90.             $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  91.         } catch (ResetPasswordExceptionInterface $e) {
  92.             $this->addFlash('reset_password_error', sprintf(
  93.                 '%s - %s',
  94.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  95.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  96.             ));
  97.             return $this->redirectToRoute('app_forgot_password_request');
  98.         }
  99.         // The token is valid; allow the user to change their password.
  100.         $form = $this->createForm(ChangePasswordFormType::class);
  101.         $form->handleRequest($request);
  102.         if ($form->isSubmitted() && $form->isValid()) {
  103.             // A password reset token should be used only once, remove it.
  104.             $this->resetPasswordHelper->removeResetRequest($token);
  105.             // Encode(hash) the plain password, and set it.
  106.             $encodedPassword = $userPasswordHasher->hashPassword(
  107.                 $user,
  108.                 $form->get('plainPassword')->getData()
  109.             );
  110.             $user->setPassword($encodedPassword);
  111.             $this->entityManager->flush();
  112.             // The session is cleaned up after the password has been changed.
  113.             $this->cleanSessionAfterReset();
  114.             return $this->redirectToRoute('front_index');
  115.         }
  116.         return $this->render('reset_password/reset.html.twig', [
  117.             'resetForm' => $form->createView(),
  118.         ]);
  119.     }
  120.     private function processSendingPasswordResetEmail(string $emailFormData, Mailer $mailer, TranslatorInterface $translator): RedirectResponse
  121.     {
  122.         $user = $this->entityManager->getRepository(User::class)->findOneBy([
  123.             'email' => $emailFormData,
  124.         ]);
  125.         // Do not reveal whether a user account was found or not.
  126.         if (!$user) {
  127.             return $this->redirectToRoute('app_check_email');
  128.         }
  129.         try {
  130.             $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  131.         } catch (ResetPasswordExceptionInterface $e) {
  132.             // If you want to tell the user why a reset email was not sent, uncomment
  133.             // the lines below and change the redirect to 'app_forgot_password_request'.
  134.             // Caution: This may reveal if a user is registered or not.
  135.             //
  136.             // $this->addFlash('reset_password_error', sprintf(
  137.             //     '%s - %s',
  138.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  139.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  140.             // ));
  141.             return $this->redirectToRoute('app_check_email');
  142.         }
  143.         $email = (new TemplatedEmail())
  144.             ->from(new Address('noreply@sme.it', 'SME'))
  145.             ->to($user->getEmail())
  146.             ->subject('La tua richiesta di reset password')
  147.             ->htmlTemplate('email.html.twig')
  148.             /*->context([
  149.                 'resetToken' => $resetToken,
  150.             ]) */
  151.         ;
  152.         $loader = new FilesystemLoader('../templates/reset_password');
  153.         $twigEnv = new Environment($loader);
  154.         $twigBodyRenderer = new BodyRenderer($twigEnv, [
  155.             'resetToken' => $resetToken,
  156.             'resetUrl' => $this->generateUrl('app_reset_password', ['token' => $resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL)
  157.         ]);
  158.         $twigBodyRenderer->render($email);
  159.         $mailer->send($email);
  160.         // Store the token object in session for retrieval in check-email route.
  161.         $this->setTokenObjectInSession($resetToken);
  162.         return $this->redirectToRoute('app_check_email');
  163.     }
  164. }