src/Controller/ResetPasswordController.php line 42

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use DateTimeImmutable;
  5. use App\Form\EditPasswordType;
  6. use App\Entity\PasswordHistory;
  7. use App\Service\PasswordService;
  8. use Symfony\Component\Mime\Address;
  9. use App\Form\ChangePasswordFormType;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use App\Form\ResetPasswordRequestFormType;
  12. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\Mailer\MailerInterface;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  23. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  24. #[Route('/mot-de-passe/reinitialisation')]
  25. class ResetPasswordController extends AbstractController
  26. {
  27.     use ResetPasswordControllerTrait;
  28.     public function __construct(
  29.         private ResetPasswordHelperInterface $resetPasswordHelper,
  30.         private EntityManagerInterface $entityManager
  31.     ) {
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      */
  36.     #[Route('/demande'name'app_forgot_password_request')]
  37.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  38.     {
  39.         $form $this->createForm(ResetPasswordRequestFormType::class);
  40.         $form->handleRequest($request);
  41.         if ($form->isSubmitted() && $form->isValid()) {
  42.             return $this->processSendingPasswordResetEmail(
  43.                 $form->get('email')->getData(),
  44.                 $mailer,
  45.                 $translator
  46.             );
  47.         }
  48.         return $this->render('reset_password/request.html.twig', [
  49.             'requestForm' => $form->createView(),
  50.         ]);
  51.     }
  52.     /**
  53.      * Confirmation page after a user has requested a password reset.
  54.      */
  55.     #[Route('/verifier-email'name'app_check_email')]
  56.     public function checkEmail(): Response
  57.     {
  58.         // Generate a fake token if the user does not exist or someone hit this page directly.
  59.         // This prevents exposing whether or not a user was found with the given email address or not
  60.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  61.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  62.         }
  63.         return $this->render('reset_password/check_email.html.twig', [
  64.             'resetToken' => $resetToken,
  65.         ]);
  66.     }
  67.     /**
  68.      * Validates and process the reset URL that the user clicked in their email.
  69.      */
  70.     #[Route('/{token}'name'app_reset_password')]
  71.     public function reset(MailerInterface $mailerRequest $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorPasswordService $passwordServiceEntityManagerInterface $emstring $token null): Response
  72.     {
  73.         if ($token) {
  74.             // We store the token in session and remove it from the URL, to avoid the URL being
  75.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  76.             $this->storeTokenInSession($token);
  77.             return $this->redirectToRoute('app_reset_password');
  78.         }
  79.         $token $this->getTokenFromSession();
  80.         if (null === $token) {
  81.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  82.         }
  83.         try {
  84.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  85.         } catch (ResetPasswordExceptionInterface $e) {
  86.             $this->addFlash('reset_password_error'sprintf(
  87.                 '%s - %s',
  88.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  89.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  90.             ));
  91.             return $this->redirectToRoute('app_forgot_password_request');
  92.         }
  93.         // The token is valid; allow the user to change their password.
  94.         $form $this->createForm(EditPasswordType::class);
  95.         $form->handleRequest($request);
  96.         $error null;
  97.         if ($form->isSubmitted() && $form->isValid()) {
  98.             // A password reset token should be used only once, remove it.
  99.             if (!$passwordService->checkLastPasswords($user$form->get('plainPassword')->getData())) {
  100.                 // throw new AlreadyUsedPasswordException();
  101.                 $error 'Le mot de passe ne doit pas avoir déjà été utilisé les trois dernières fois.';
  102.             } else {
  103.                 $date = new DateTimeImmutable();
  104.                 $hashedPassword =  $userPasswordHasher->hashPassword(
  105.                     $user,
  106.                     $form->get('plainPassword')->getData()
  107.                 );
  108.                 $user->setPassword($hashedPassword)
  109.                     ->setExpirationPassword($date->modify('+6 months'));
  110.                 $passwordHistory = new PasswordHistory();
  111.                 $passwordHistory->setUser($user);
  112.                 $passwordHistory->setPassword($hashedPassword);
  113.                 $em->persist($user);
  114.                 $em->persist($passwordHistory);
  115.                 $em->flush();
  116.                 $email = (new TemplatedEmail())
  117.                     ->from(new Address($this->getParameter('app.email_domain'), $this->getParameter('app.email_domain_name')))
  118.                     ->to($user->getEmail())
  119.                     ->subject('Mot de passe modifié')
  120.                     ->htmlTemplate('email/password_edited.html.twig')
  121.                     ->context([]);
  122.                 $mailer->send($email);
  123.                 $this->resetPasswordHelper->removeResetRequest($token);
  124.                 // The session is cleaned up after the password has been changed.
  125.                 $this->cleanSessionAfterReset();
  126.                 return $this->redirectToRoute('app_edit_password_confirmation');
  127.             }
  128.         }
  129.         return $this->render('reset_password/reset.html.twig', [
  130.             'resetForm' => $form->createView(),
  131.             'error' => $error
  132.         ]);
  133.     }
  134.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  135.     {
  136.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  137.             'email' => $emailFormData,
  138.         ]);
  139.         // Do not reveal whether a user account was found or not.
  140.         if (!$user) {
  141.             return $this->redirectToRoute('app_check_email');
  142.         }
  143.         try {
  144.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  145.         } catch (ResetPasswordExceptionInterface $e) {
  146.             // If you want to tell the user why a reset email was not sent, uncomment
  147.             // the lines below and change the redirect to 'app_forgot_password_request'.
  148.             // Caution: This may reveal if a user is registered or not.
  149.             //
  150.             // $this->addFlash('reset_password_error', sprintf(
  151.             //     '%s - %s',
  152.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  153.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  154.             // ));
  155.             return $this->redirectToRoute('app_check_email');
  156.         }
  157.         $email = (new TemplatedEmail())
  158.             ->from(new Address($this->getParameter('app.email_domain'), $this->getParameter('app.email_domain_name')))
  159.             ->to($user->getEmail())
  160.             ->subject('Demande de réinitialisation de mot de passe')
  161.             ->htmlTemplate('email/reset_password.html.twig')
  162.             ->context([
  163.                 'resetToken' => $resetToken,
  164.             ]);
  165.         $mailer->send($email);
  166.         // Store the token object in session for retrieval in check-email route.
  167.         $this->setTokenObjectInSession($resetToken);
  168.         return $this->redirectToRoute('app_check_email');
  169.     }
  170. }