src/Controller/ResetPasswordController.php line 50

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Applicants;
  4. use App\Entity\Provider;
  5. use App\Features\Core\ILogger;
  6. use App\Form\ChangePasswordFormType;
  7. use App\Form\ResetPasswordRequestFormType;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  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\Exception\TooManyPasswordRequestsException;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. #[Route([
  25.     "fr" => "/reinitialiser-mot-de-passe",
  26.     "en" => '/reset-password',
  27. ])]
  28. class ResetPasswordController extends AbstractController
  29. {
  30.     use ResetPasswordControllerTrait;
  31.     private $resetPasswordHelper;
  32.     private $entityManager;
  33.     private string $mailFrom;
  34.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerstring $mailFrom)
  35.     {
  36.         $this->resetPasswordHelper $resetPasswordHelper;
  37.         $this->entityManager $entityManager;
  38.         $this->mailFrom $mailFrom;
  39.     }
  40.     /**
  41.      * Display & process form to request a password reset.
  42.      */
  43.     #[Route(''name'app_forgot_password_request')]
  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([
  63.         "fr" => "/confirmation",
  64.         "en" => '/check-email',
  65.     ], name'app_check_email')]
  66.     public function checkEmail(): Response
  67.     {
  68.         // Generate a fake token if the user does not exist or someone hit this page directly.
  69.         // This prevents exposing whether or not a user was found with the given email address or not
  70.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  71.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  72.         }
  73.         return $this->render('reset_password/check_email.html.twig', [
  74.             'resetToken' => $resetToken,
  75.         ]);
  76.     }
  77.     /**
  78.      * Validates and process the reset URL that the user clicked in their email.
  79.      */
  80.     #[Route([
  81.         "fr" => "/changer/{token}",
  82.         "en" => '/reset/{token}',
  83.     ], name'app_reset_password')]
  84.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorILogger $loggerstring $token null): Response
  85.     {
  86.         if ($token) {
  87.             // We store the token in session and remove it from the URL, to avoid the URL being
  88.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  89.             $this->storeTokenInSession($token);
  90.             return $this->redirectToRoute('app_reset_password');
  91.         }
  92.         $token $this->getTokenFromSession();
  93.         if (null === $token) {
  94.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  95.         }
  96.         try {
  97.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  98.         } catch (ResetPasswordExceptionInterface $e) {
  99.             $this->addFlash('error'sprintf(
  100.                 '%s - %s',
  101.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  102.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  103.             ));
  104.             return $this->redirectToRoute('app_forgot_password_request');
  105.         }
  106.         // The token is valid; allow the user to change their password.
  107.         $form $this->createForm(ChangePasswordFormType::class);
  108.         $form->handleRequest($request);
  109.         if ($form->isSubmitted()) {
  110.             if($form->isValid()){
  111.                 // A password reset token should be used only once, remove it.
  112.                 $this->resetPasswordHelper->removeResetRequest($token);
  113.                 // Encode(hash) the plain password, and set it.
  114.                 $encodedPassword $userPasswordHasher->hashPassword(
  115.                     $user,
  116.                     $form->get('plainPassword')->getData()
  117.                 );
  118.                 $user->setHashPassword($encodedPassword);
  119.                 $this->entityManager->flush();
  120.                 // The session is cleaned up after the password has been changed.
  121.                 $this->cleanSessionAfterReset();
  122.                 $logger->log($user"Mot de passe modifié""Vous avez modifié votre mot de passe"$user);
  123.                 $this->addFlash('notice'"Votre mot de passe a été modifié avec succès.");
  124.                 return $this->redirectToRoute('applicant_login');
  125.             }else{
  126.                 $this->addFlash('error'"Veuillez remplir des mots de passe valides.");
  127.             }
  128.         }
  129.         return $this->render('reset_password/reset.html.twig', [
  130.             'resetForm' => $form->createView(),
  131.         ]);
  132.     }
  133.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  134.     {
  135.         $user $this->entityManager->getRepository(Applicants::class)->findOneBy([
  136.             'email' => $emailFormData,
  137.         ]);
  138.         // Do not reveal whether a user account was found or not.
  139.         if (!$user) {
  140.             return $this->redirectToRoute('app_check_email');
  141.         }
  142.         try {
  143.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  144.         } catch (ResetPasswordExceptionInterface $e) {
  145.             if($e instanceof TooManyPasswordRequestsException){
  146.                 $this->addFlash('error'"Vous avez déjà fait une demande de réinitialisation de votre mot de passe. Veuillez réessayer à ".$e->getAvailableAt()->format('d M Y H:i:s')." .");
  147.             }else{
  148.                 $this->addFlash('error'"Un problème est survenu. Veuillez réessayer plus tard.");
  149.             }
  150.             return $this->redirectToRoute('app_forgot_password_request');
  151.         }
  152.         $email = (new TemplatedEmail())
  153.             ->from(new Address($this->mailFrom'NSIA BANQUE Bénin'))
  154.             ->to($user->getEmail())
  155.             ->subject("Réinitialisation de mot de passe")
  156.             ->htmlTemplate('reset_password/email.html.twig')
  157.             ->context([
  158.                 'resetToken' => $resetToken,
  159.             ])
  160.         ;
  161.         try {
  162.             $mailer->send($email);
  163.         } catch (TransportExceptionInterface $e) {
  164.             $this->setTokenObjectInSession($resetToken);
  165.             $this->addFlash('error'"Un problème est survenu lors de l'envoi de l'email. Veuillez réessayer.");
  166.             return $this->redirectToRoute('app_forgot_password_request');
  167.         }
  168.         return $this->redirectToRoute('app_check_email');
  169.     }
  170. }