src/Controller/ResetPasswordController.php line 46

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\Repository\CategorieElearningRepository;
  7. use App\Repository\SettingRepository;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  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\Contracts\Translation\TranslatorInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  23. #[Route('/reset-password')]
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $fromAddress;
  28.     public function __construct(
  29.         private ResetPasswordHelperInterface $resetPasswordHelper,
  30.         private EntityManagerInterface $entityManager,
  31.         private  SettingRepository $settingRepository,
  32.         ParameterBagInterface $parameterBag  // Injection du service ParameterBagInterface
  33.     ) {
  34.         $this->fromAddress $parameterBag->get('mailer_from_address');
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      */
  39.     #[Route(''name'app_forgot_password_request')]
  40.     public function request(CategorieElearningRepository $categorieElearningRepository,Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  41.     {
  42.         $form $this->createForm(ResetPasswordRequestFormType::class);
  43.         $form->handleRequest($request);
  44.         if ($form->isSubmitted() && $form->isValid()) {
  45.             return $this->processSendingPasswordResetEmail(
  46.                 $form->get('email')->getData(),
  47.                 $mailer,
  48.                 $translator
  49.             );
  50.         }
  51.         return $this->render('reset_password/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.             'setting'=>$this->settingRepository->find(1),
  54.             'categories'=>$categorieElearningRepository->findAll(),
  55.         ]);
  56.     }
  57.     /**
  58.      * Confirmation page after a user has requested a password reset.
  59.      */
  60.     #[Route('/check-email'name'app_check_email')]
  61.     public function checkEmail(CategorieElearningRepository $categorieElearningRepository): Response
  62.     {
  63.         // Generate a fake token if the user does not exist or someone hit this page directly.
  64.         // This prevents exposing whether or not a user was found with the given email address or not
  65.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  66.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  67.         }
  68.         return $this->render('reset_password/check_email.html.twig', [
  69.             'resetToken' => $resetToken'setting'=>$this->settingRepository->find(1),
  70.             'categories'=>$categorieElearningRepository->findAll(),
  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(CategorieElearningRepository $categorieElearningRepository,Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $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 $passwordHasher->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('app_home');
  115.         }
  116.         return $this->render('reset_password/reset.html.twig', [
  117.             'resetForm' => $form->createView(),
  118.             'setting'=>$this->settingRepository->find(1),
  119.             'categories'=>$categorieElearningRepository->findAll(),
  120.         ]);
  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('app_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('app_check_email');
  144.         }
  145.         $email = (new TemplatedEmail())
  146. //            ->from(new Address('sip-academy@smart-it-partner.com', 'Sip Academy'))
  147.             ->from(new Address($this->fromAddress'Sip Academy'))  // Utilisation de Address pour inclure l'email et le nom
  148.             ->to($user->getEmail())
  149.             ->subject('RĂ©initialisation de mot de passe')
  150.             ->htmlTemplate('reset_password/email.html.twig')
  151.             ->context([
  152.                 'resetToken' => $resetToken,'setting'=>$this->settingRepository->find(1)
  153.             ])
  154.         ;
  155.         $mailer->send($email);
  156.         // Store the token object in session for retrieval in check-email route.
  157.         $this->setTokenObjectInSession($resetToken);
  158.         return $this->redirectToRoute('app_check_email');
  159.     }
  160. }