src/Controller/ResetPasswordController.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use Doctrine\ORM\EntityManagerInterface;
  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\MailerInterface;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. #[Route('/mot-de-passe-oublie')]
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     public function __construct(
  26.         private ResetPasswordHelperInterface $resetPasswordHelper,
  27.         private EntityManagerInterface $entityManager
  28.     ) {
  29.     }
  30.     /**
  31.      * Display & process form to request a password reset.
  32.      */
  33.     #[Route('/', name: 'app_forgot_password_request')]
  34.     public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): Response
  35.     {
  36.         $form = $this->createForm(ResetPasswordRequestFormType::class);
  37.         $form->handleRequest($request);
  38.         if ($form->isSubmitted() && $form->isValid()) {
  39.             $user = $this->entityManager->getRepository(User::class)->findOneBy([
  40.                 'email' => $form->get('email')->getData(),
  41.             ]);
  42.             if(!$user) {
  43.                 $this->addFlash(
  44.                     'reset_password_ckeckMail_warning',
  45.                     "Aucun compte correspondant à cette adresse email n'a été trouvé."
  46.                 );
  47.             } else {
  48.                 return $this->processSendingPasswordResetEmail(
  49.                     $form->get('email')->getData(),
  50.                     $mailer,
  51.                     $translator
  52.                 );
  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('/verifier-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. //
  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('/modifier/{token}', name: 'app_reset_password')]
  79.     public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, string $token = null): Response
  80.     {
  81.         if ($token) {
  82.             // We store the token in session and remove it from the URL, to avoid the URL being
  83.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  84.             $this->storeTokenInSession($token);
  85.             return $this->redirectToRoute('app_reset_password');
  86.         }
  87.         $token = $this->getTokenFromSession();
  88.         if (null === $token) {
  89.             throw $this->createNotFoundException("Aucun jeton de réinitialisation du mot de passe trouvé dans l'URL ou dans la session.");
  90.         }
  91.         try {
  92.             $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  93.         } catch (ResetPasswordExceptionInterface $e) {
  94.             $this->addFlash('reset_password_error', sprintf(
  95.                 '%s - %s',
  96.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  97.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  98.             ));
  99.             return $this->redirectToRoute('app_forgot_password_request');
  100.         }
  101.         // The token is valid; allow the user to change their password.
  102.         $form = $this->createForm(ResetPasswordFormType::class);
  103.         $form->handleRequest($request);
  104.         if ($form->isSubmitted() && $form->isValid()) {
  105.             // A password reset token should be used only once, remove it.
  106.             $this->resetPasswordHelper->removeResetRequest($token);
  107.             // Encode(hash) the plain password, and set it.
  108.             $encodedPassword = $passwordHasher->hashPassword(
  109.                 $user,
  110.                 $form->get('plainPassword')->getData()
  111.             );
  112.             $user->setPassword($encodedPassword);
  113.             $this->entityManager->flush();
  114.             // The session is cleaned up after the password has been changed.
  115.             $this->cleanSessionAfterReset();
  116.             $this->addFlash(
  117.                 'success',
  118.                 "Votre mot de passe a été réinitialisé avec succès."
  119.             );
  120.             return $this->redirectToRoute('app_login');
  121.         }
  122.         return $this->render('reset_password/reset.html.twig', [
  123.             'resetForm' => $form->createView(),
  124.         ]);
  125.     }
  126.     private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse
  127.     {
  128.         $user = $this->entityManager->getRepository(User::class)->findOneBy([
  129.             'email' => $emailFormData,
  130.         ]);
  131.         // Do not reveal whether a user account was found or not.
  132.         if (!$user) {
  133.             return $this->redirectToRoute('app_forgot_password_request');
  134.         }
  135.         try {
  136.             $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  137.         } catch (ResetPasswordExceptionInterface $e) {
  138.             // If you want to tell the user why a reset email was not sent, uncomment
  139.             // the lines below and change the redirect to 'app_forgot_password_request'.
  140.             // Caution: This may reveal if a user is registered or not.
  141.             //
  142.             // $this->addFlash('reset_password_error', sprintf(
  143.             //     '%s - %s',
  144.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  145.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  146.             // ));
  147.             return $this->redirectToRoute('app_forgot_password_request');
  148.         }
  149.         $email = (new TemplatedEmail())
  150.             ->from(new Address('contact@decizioconsulting.com', 'Decizio APP'))
  151.             ->to($user->getEmail())
  152.             ->subject('Votre demande de réinitialisation de mot de passe')
  153.             ->htmlTemplate('reset_password/email.html.twig')
  154.             ->context([
  155.                 'resetToken' => $resetToken,
  156.             ])
  157.         ;
  158.         $mailer->send($email);
  159.         // Store the token object in session for retrieval in check-email route.
  160.         $this->setTokenObjectInSession($resetToken);
  161.         $this->addFlash(
  162.             'reset_password_sendinMail_succes',
  163.             "Un message vient d'être envoyé contenant un lien que vous pouvez utiliser pour réinitialiser votre mot de passe."
  164.         );
  165.         return $this->redirectToRoute('app_forgot_password_request');
  166.     }
  167. }