src/Controller/ResetPasswordController.php line 53

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller;
  4. use App\Entity\Admin;
  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 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 ResetPasswordHelperInterface $resetPasswordHelper;
  28.     private SmsService $smsService;
  29.     private CodeService $codeService;
  30.     private UserPasswordHasherInterface $userPasswordHasher;
  31.     private EntityManagerInterface $em;
  32.     public function __construct(private readonly ManagerRegistry $doctrineEntityManagerInterface $emResetPasswordHelperInterface $resetPasswordHelperSmsService $smsServiceCodeService $codeServiceUserPasswordHasherInterface $userPasswordHasher)
  33.     {
  34.         $this->resetPasswordHelper $resetPasswordHelper;
  35.         $this->em $em;
  36.         $this->smsService $smsService;
  37.         $this->codeService $codeService;
  38.         $this->userPasswordHasher $userPasswordHasher;
  39.     }
  40.     /**
  41.      * Display & process form to request a password reset.
  42.      * @throws TransportExceptionInterface
  43.      */
  44.     #[Route('/'name'app_forgot_password_request'methods: ['GET''POST'])]
  45.     public function request(Request $requestMailService $mailer): Response
  46.     {
  47.         $form $this->createForm(ResetPasswordRequestFormType::class);
  48.         $form->handleRequest($request);
  49.         if ($form->isSubmitted() && $form->isValid()) {
  50.             return $this->processSendingPasswordResetEmail(
  51.                 $form->get('email')->getData(), $form->get('username')->getData(),
  52.                 $mailer
  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('/check-email'name'app_check_email'methods: ['GET'])]
  63.     public function checkEmail(): Response
  64.     {
  65.         // We prevent users from directly accessing this page
  66.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  67.             return $this->redirectToRoute('app_forgot_password_request');
  68.         }
  69.         return $this->render('reset_password/check_email.html.twig', [
  70.             'resetToken' => $resetToken,
  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'methods: ['GET''POST'])]
  77.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $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.                 'There was a problem validating your reset request - %s',
  94.                 $e->getReason()
  95.             ));
  96.             return $this->redirectToRoute('app_forgot_password_request');
  97.         }
  98.         $this->em->initializeObject($user);     // forces hydration
  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 the plain password, and set it.
  106.             $encodedPassword $passwordHasher->hashPassword(
  107.                 $user,
  108.                 $form->get('plainPassword')->getData()
  109.             );
  110.             $user->setPassword($encodedPassword);
  111.             $this->doctrine->getManager()->flush();
  112.             // The session is cleaned up after the password has been changed.
  113.             $this->cleanSessionAfterReset();
  114.             return $this->redirectToRoute('app_dashboard');
  115.         }
  116.         return $this->render('reset_password/reset.html.twig', [
  117.             'resetForm' => $form->createView(),
  118.         ]);
  119.     }
  120.     /**
  121.      * @throws TransportExceptionInterface
  122.      */
  123.     private function processSendingPasswordResetEmail(string $emailFormDatastring $usernameFormDataMailService $mailService): RedirectResponse
  124.     {
  125.         $user $this->em->getRepository(Admin::class)->findOneBy(['email' => $emailFormData'username' => $usernameFormData]);
  126.         $this->em->initializeObject($user);     // forces hydration
  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.                'There was a problem handling your password reset request - %s',
  140.                 $e->getReason()
  141.              ));
  142.             return $this->redirectToRoute('app_check_email');
  143.         }
  144.         try {
  145.             //New password
  146.             $p strtoupper($this->codeService->PasswordCode(5));
  147.             $user->setPassword(
  148.                 $this->userPasswordHasher->hashPassword(
  149.                     $user$p
  150.                 )
  151.             );
  152.             $message 'Votre mot de passe '$user->getName().' est: '.$p;
  153.             $this->smsService->smsService($user->getPhone(), $message);
  154.             $em $this->doctrine->getManager();
  155.             $em->flush();
  156.             $mailService->sendTemplatedMail(
  157.                 $user->getEmail(),
  158.                 'Votre demande de rĂ©initialisation de mot de passe du compte administrateur',
  159.                 'reset_password/email.html.twig',
  160.                 ['resetToken' => $resetToken]
  161.             );
  162.         }catch (ResetPasswordExceptionInterface $e) {
  163.             $this->addFlash('reset_password_error'sprintf(
  164.                 'There was a problem handling your password reset request - %s',
  165.                 $e->getReason()
  166.             ));
  167.             return $this->redirectToRoute('app_check_email');
  168.         }
  169.         // Store the token object in session for retrieval in check-email route.
  170.         $this->setTokenObjectInSession($resetToken);
  171.         return $this->redirectToRoute('app_check_email');
  172.     }
  173. }