src/Controller/ResetPasswordController.php line 52

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Service\CodeService;
  8. use App\Service\MailService;
  9. use App\Service\SmsService;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  20. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  22. #[Route('/reset-password')]
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private ResetPasswordHelperInterface $resetPasswordHelper;
  27.     private SmsService $smsService;
  28.     private CodeService $codeService;
  29.     private UserPasswordHasherInterface $userPasswordHasher;
  30.     private EntityManagerInterface $em;
  31.     public function __construct(private readonly ManagerRegistry $doctrineEntityManagerInterface $emResetPasswordHelperInterface $resetPasswordHelperSmsService $smsServiceCodeService $codeServiceUserPasswordHasherInterface $userPasswordHasher)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->em $em;
  35.         $this->smsService $smsService;
  36.         $this->codeService $codeService;
  37.         $this->userPasswordHasher $userPasswordHasher;
  38.     }
  39.     /**
  40.      * Display & process form to request a password reset.
  41.      * @throws TransportExceptionInterface
  42.      */
  43.     #[Route('/'name'app_forgot_password_request'methods: ['GET''POST'])]
  44.     public function request(Request $requestMailService $mailer): 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(), $form->get('username')->getData(),
  51.                 $mailer);
  52.         }
  53.         return $this->render('reset_password/request.html.twig', [
  54.             'requestForm' => $form->createView(),
  55.         ]);
  56.     }
  57.     /**
  58.      * Confirmation page after a user has requested a password reset.
  59.      */
  60.     #[Route('/check-email'name'app_check_email'methods: ['GET'])]
  61.     public function checkEmail(): Response
  62.     {
  63.         // We prevent users from directly accessing this page
  64.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  65.             return $this->redirectToRoute('app_forgot_password_request');
  66.         }
  67.         return $this->render('reset_password/check_email.html.twig', [
  68.             'resetToken' => $resetToken,
  69.         ]);
  70.     }
  71.     /**
  72.      * Validates and process the reset URL that the user clicked in their email.
  73.      */
  74.     #[Route('/reset/{token}'name'app_reset_password'methods: ['GET''POST'])]
  75.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $token null): Response
  76.     {
  77.         if ($token) {
  78.             // We store the token in session and remove it from the URL, to avoid the URL being
  79.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  80.             $this->storeTokenInSession($token);
  81.             return $this->redirectToRoute('app_reset_password');
  82.         }
  83.         $token $this->getTokenFromSession();
  84.         if (null === $token) {
  85.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  86.         }
  87.         try {
  88.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  89.         } catch (ResetPasswordExceptionInterface $e) {
  90. //            $this->addFlash('reset_password_error', sprintf(
  91. //                'There was a problem validating your reset request - %s',
  92. //                $e->getReason()
  93. //            ));
  94.             return $this->redirectToRoute('app_forgot_password_request');
  95.         }
  96.         // The token is valid; allow the user to change their password.
  97.         $form $this->createForm(ChangePasswordFormType::class);
  98.         $form->handleRequest($request);
  99.         if ($form->isSubmitted() && $form->isValid()) {
  100.             // A password reset token should be used only once, remove it.
  101.             $this->resetPasswordHelper->removeResetRequest($token);
  102.             // Encode the plain password, and set it.
  103.             $encodedPassword $passwordHasher->hashPassword(
  104.                 $user,
  105.                 $form->get('plainPassword')->getData()
  106.             );
  107.             $user->setPassword($encodedPassword);
  108.             $this->doctrine->getManager()->flush();
  109.             // The session is cleaned up after the password has been changed.
  110.             $this->cleanSessionAfterReset();
  111.             return $this->redirectToRoute('app_dashboard');
  112.         }
  113.         return $this->render('reset_password/reset.html.twig', [
  114.             'resetForm' => $form->createView(),
  115.         ]);
  116.     }
  117.     /**
  118.      * @throws TransportExceptionInterface
  119.      */
  120.     private function processSendingPasswordResetEmail(string $emailFormDatastring $usernameFormDataMailService $mailService): RedirectResponse
  121.     {
  122.         $user $this->doctrine->getRepository(User::class)->findOneBy([
  123.             'email' => $emailFormData,
  124.             'username' => $usernameFormData
  125.         ]);
  126.         // Do not reveal whether a user account was found or not.
  127.         if (!$user) {
  128.             $this->addFlash('reset_password_error',
  129.                 'Compte invalid, Veuillez saisir le correct nom d\'utilisateur et son e-mail adresse ');
  130.             return $this->redirectToRoute('app_check_email');
  131.         }
  132.         try {
  133.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  134.         } catch (ResetPasswordExceptionInterface $e) {
  135.             // If you want to tell the user why a reset email was not sent, uncomment
  136.             // the lines below and change the redirect to 'app_forgot_password_request'.
  137.             // Caution: This may reveal if a user is registered or not.
  138.             //
  139.               $this->addFlash('reset_password_error'sprintf(
  140.                  'There was a problem handling your password reset request - %s',
  141.                   $e->getReason()
  142.                ));
  143.             return $this->redirectToRoute('app_check_email');
  144.         }
  145.         try {
  146.             //New password
  147.             $p strtoupper($this->codeService->PasswordCode(5));
  148.             $user->setPassword(
  149.                 $this->userPasswordHasher->hashPassword(
  150.                     $user$p
  151.                 )
  152.             );
  153.             $message 'Votre mot de passe '$user->getName().' est: '.$p;
  154.             $this->smsService->smsService($user->getEntreprise(), $user->getPhone(), $message);
  155.             $em $this->doctrine->getManager();
  156.             $em->flush();
  157.             $mailService->sendTemplatedMail(
  158.                 $user->getEmail(),
  159.                 'Votre demande de rĂ©initialisation de mot de passe',
  160.                 'reset_password/email.html.twig',
  161.                 ['resetToken' => $resetToken]
  162.             );
  163.         }catch (ResetPasswordExceptionInterface $e) {
  164.             $this->addFlash('reset_password_error'sprintf(
  165.                 'There was a problem handling your password reset request - %s',
  166.                 $e->getReason()
  167.             ));
  168.             return $this->redirectToRoute('app_check_email');
  169.         }
  170.         // Store the token object in session for retrieval in check-email route.
  171.         $this->setTokenObjectInSession($resetToken);
  172.         return $this->redirectToRoute('app_check_email');
  173.     }
  174. }