src/Controller/ResetPasswordController.php line 41

  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. /**
  22.  * RĂ©initialisation du mot de passe
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     public function __construct(
  28.         private ResetPasswordHelperInterface $resetPasswordHelper,
  29.         private EntityManagerInterface $entityManager
  30.     ) {
  31.     }
  32.     /**
  33.      * Display & process form to request a password reset.
  34.      */
  35.     #[Route(''name'forgot_password_request')]
  36.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  37.     {
  38.         $form $this->createForm(ResetPasswordRequestFormType::class);
  39.         $form->handleRequest($request);
  40.         if ($form->isSubmitted() && $form->isValid()) {
  41.             return $this->processSendingPasswordResetEmail(
  42.                 $form->get('email')->getData(),
  43.                 $mailer,
  44.                 $translator
  45.             );
  46.         }
  47.         return $this->render('reset_password/request.html.twig', [
  48.             'requestForm' => $form->createView(),
  49.         ]);
  50.     }
  51.     /**
  52.      * Confirmation page after a user has requested a password reset.
  53.      */
  54.     #[Route('/check-email'name'check_email')]
  55.     public function checkEmail(): Response
  56.     {
  57.         // Generate a fake token if the user does not exist or someone hit this page directly.
  58.         // This prevents exposing whether or not a user was found with the given email address or not
  59.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  60.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  61.         }
  62.         return $this->render('reset_password/check_email.html.twig', [
  63.             'resetToken' => $resetToken,
  64.         ]);
  65.     }
  66.     /**
  67.      * Validates and process the reset URL that the user clicked in their email.
  68.      */
  69.     #[Route('/reset/{token}'name'reset_password')]
  70.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  71.     {
  72.         if ($token) {
  73.             // We store the token in session and remove it from the URL, to avoid the URL being
  74.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  75.             $this->storeTokenInSession($token);
  76.             return $this->redirectToRoute('reset_password');
  77.         }
  78.         $token $this->getTokenFromSession();
  79.         if (null === $token) {
  80.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  81.         }
  82.         try {
  83.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  84.         } catch (ResetPasswordExceptionInterface $e) {
  85.             $this->addFlash('reset_password_error'sprintf(
  86.                 '%s - %s',
  87.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  88.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  89.             ));
  90.             return $this->redirectToRoute('forgot_password_request');
  91.         }
  92.         // The token is valid; allow the user to change their password.
  93.         $form $this->createForm(ChangePasswordFormType::class);
  94.         $form->handleRequest($request);
  95.         if ($form->isSubmitted() && $form->isValid()) {
  96.             // A password reset token should be used only once, remove it.
  97.             $this->resetPasswordHelper->removeResetRequest($token);
  98.             // Encode(hash) the plain password, and set it.
  99.             $encodedPassword $passwordHasher->hashPassword(
  100.                 $user,
  101.                 $form->get('plainPassword')->getData()
  102.             );
  103.             $user->setPassword($encodedPassword);
  104.             $this->entityManager->flush();
  105.             // The session is cleaned up after the password has been changed.
  106.             $this->cleanSessionAfterReset();
  107.             return $this->redirectToRoute('dashboard');
  108.         }
  109.         return $this->render('reset_password/reset.html.twig', [
  110.             'resetForm' => $form->createView(),
  111.         ]);
  112.     }
  113.     /**
  114.      * Enoive du mail pour rĂ©initialiser le mot de passe
  115.      *
  116.      * @param string $emailFormData [explicite description]
  117.      * @param MailerInterface $mailer [explicite description]
  118.      * @param TranslatorInterface $translator [explicite description]
  119.      *
  120.      * @return RedirectResponse
  121.      */
  122.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  123.     {
  124.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  125.             'email' => $emailFormData,
  126.         ]);
  127.         // Do not reveal whether a user account was found or not.
  128.         if (!$user) {
  129.             return $this->redirectToRoute('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.             return $this->redirectToRoute('check_email');
  144.         }
  145.         $email = (new TemplatedEmail())
  146.             ->from(new Address('[email protected]''MyCY'))
  147.             ->to($user->getEmail())
  148.             ->subject('MyCY - Votre mot de passe')
  149.             ->htmlTemplate('reset_password/email.html.twig')
  150.             ->context([
  151.                 'resetToken' => $resetToken,
  152.             ]);
  153.         $mailer->send($email);
  154.         // Store the token object in session for retrieval in check-email route.
  155.         $this->setTokenObjectInSession($resetToken);
  156.         return $this->redirectToRoute('check_email');
  157.     }
  158. }