src/Controller/ResetPasswordController.php line 50

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\BodyRenderer;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Mailer\Mailer;
  14. use Symfony\Component\Mailer\MailerInterface;
  15. use Symfony\Component\Mailer\Transport;
  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. /**
  27.  * @Route("/reset-password")
  28.  */
  29. class ResetPasswordController extends AbstractController
  30. {
  31.     use ResetPasswordControllerTrait;
  32.     private $resetPasswordHelper;
  33.     private $entityManager;
  34.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  35.     {
  36.         $this->resetPasswordHelper $resetPasswordHelper;
  37.         $this->entityManager $entityManager;
  38.     }
  39.     /**
  40.      * Display & process form to request a password reset.
  41.      *
  42.      * @Route("", name="app_forgot_password_request")
  43.      */
  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.      */
  64.     public function checkEmail(): Response
  65.     {
  66.         // Generate a fake token if the user does not exist or someone hit this page directly.
  67.         // This prevents exposing whether or not a user was found with the given email address or not
  68.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  69.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  70.         }
  71.         return $this->render('reset_password/check_email.html.twig', [
  72.             'resetToken' => $resetToken,
  73.         ]);
  74.     }
  75.     /**
  76.      * Validates and process the reset URL that the user clicked in their email.
  77.      *
  78.      * @Route("/reset/{token}", name="app_reset_password")
  79.      */
  80.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  81.     {
  82.         if ($token) {
  83.             // We store the token in session and remove it from the URL, to avoid the URL being
  84.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  85.             $this->storeTokenInSession($token);
  86.             return $this->redirectToRoute('app_reset_password');
  87.         }
  88.         $token $this->getTokenFromSession();
  89.         if (null === $token) {
  90.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  91.         }
  92.         try {
  93.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  94.         } catch (ResetPasswordExceptionInterface $e) {
  95.             $this->addFlash('reset_password_error'sprintf(
  96.                 '%s - %s',
  97.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  98.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  99.             ));
  100.             return $this->redirectToRoute('app_forgot_password_request');
  101.         }
  102.         // The token is valid; allow the user to change their password.
  103.         $form $this->createForm(ChangePasswordFormType::class);
  104.         $form->handleRequest($request);
  105.         if ($form->isSubmitted() && $form->isValid()) {
  106.             // A password reset token should be used only once, remove it.
  107.             $this->resetPasswordHelper->removeResetRequest($token);
  108.             // Encode(hash) the plain password, and set it.
  109.             $encodedPassword $userPasswordHasher->hashPassword(
  110.                 $user,
  111.                 $form->get('plainPassword')->getData()
  112.             );
  113.             $user->setPassword($encodedPassword);
  114.             $this->entityManager->flush();
  115.             // The session is cleaned up after the password has been changed.
  116.             $this->cleanSessionAfterReset();
  117.             return $this->redirectToRoute('login');
  118.         }
  119.         return $this->render('reset_password/reset.html.twig', [
  120.             'resetForm' => $form->createView(),
  121.         ]);
  122.     }
  123.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  124.     {
  125.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  126.             'email' => $emailFormData,
  127.         ]);
  128.         // Do not reveal whether a user account was found or not.
  129.         if (!$user) {
  130.             return $this->redirectToRoute('app_check_email');
  131.         }
  132.         try {
  133.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  134.         } catch (ResetPasswordExceptionInterface $e) {
  135.             // If you want to tell the user why a reset email was not sent, uncomment
  136.             // the lines below and change the redirect to 'app_forgot_password_request'.
  137.             // Caution: This may reveal if a user is registered or not.
  138.             //
  139.             // $this->addFlash('reset_password_error', sprintf(
  140.             //     '%s - %s',
  141.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  142.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  143.             // ));
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         $transport Transport::fromDsn($this->getParameter('mailer_dsn'));
  147.         $mailer = new Mailer($transport);
  148.         $email = (new TemplatedEmail())
  149.             ->from(new Address('contact@asb-digital.fr''ASB Digital Support'))
  150.             ->to($user->getEmail())
  151.             ->subject('Votre demande de rĂ©initialisation de mot de passe')
  152.             ->htmlTemplate('reset_password/email.html.twig')
  153.             ->context([
  154.                 'resetToken' => $resetToken,
  155.                 'expirationMessageKey' => $translator->trans($resetToken->getExpirationMessageKey(), [], 'ResetPasswordBundle'),
  156.                 "url"=>$this->generateUrl('app_reset_password', ["token"=>$resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL)
  157.             ]);
  158.         $loader = new FilesystemLoader($this->getParameter('kernel.project_dir') . '/templates/');
  159.         $twigEnv = new Environment($loader);
  160.         $twigBodyRenderer = new BodyRenderer($twigEnv);
  161.         $twigBodyRenderer->render($email);
  162.         $mailer->send($email);
  163.         // Store the token object in session for retrieval in check-email route.
  164.         $this->setTokenObjectInSession($resetToken);
  165.         return $this->redirectToRoute('app_check_email');
  166.     }
  167. }