src/Controller/ResetPasswordController.php line 48

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\Service\MailerService;
  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 SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. /**
  21.  * @Route("/gs/reset-password")
  22.  */
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.  
  27.     private ResetPasswordHelperInterface $resetPasswordHelper;
  28.     private EntityManagerInterface $entityManager;
  29.     private $emailConfs;
  30.     private $mailerService;
  31.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerMailerService $mailerService, array $emailFrom)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.         $this->emailConfs $emailFrom;
  36.         $this->mailerService $mailerService;
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      *
  41.      * @Route("", name="app_forgot_password_request")
  42.      */
  43.     public function request(Request $request): Response
  44.     {
  45.         $form $this->createForm(ResetPasswordRequestFormType::class);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) 
  48.         {
  49.             return $this->processSendingPasswordResetEmail(
  50.                 $form->get('email')->getData(),
  51.                 $this->mailerService
  52.             );
  53.         }
  54.         return $this->render('reset_password/request.html.twig', [
  55.             'requestForm' => $form->createView(),
  56.         ]);
  57.     }
  58.     /**
  59.      * Confirmation page after a user has requested a password reset.
  60.      *
  61.      * @Route("/check-email", name="app_check_email")
  62.      */
  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.         return $this->render('reset_password/check_email.html.twig', [
  71.             'resetToken' => $resetToken,
  72.         ]);
  73.     }
  74.     /**
  75.      * Validates and process the reset URL that the user clicked in their email.
  76.      *
  77.      * @Route("/reset/{token}", name="app_reset_password")
  78.      */
  79.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $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('No reset password token found in the URL or in the 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.                 ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  97.                 $e->getReason()
  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(ChangePasswordFormType::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 $userPasswordHasher->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('success'"Votre mot de passe a été modifié");
  117.             return $this->redirectToRoute('app_home');
  118.         }
  119.         return $this->render('reset_password/reset.html.twig', [
  120.             'resetForm' => $form->createView(),
  121.         ]);
  122.     }
  123.     private function processSendingPasswordResetEmail(string $emailFormDataMailerService $mailerService): RedirectResponse
  124.     {
  125.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  126.             'email' => $emailFormData,
  127.         ]);
  128.         // Do not reveal whether a user account was found or not.
  129.         if (!$user) {
  130.             return $this->redirectToRoute('app_check_email');
  131.         }
  132.         try 
  133.         {
  134.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  135.         } 
  136.         catch (ResetPasswordExceptionInterface $e
  137.         {
  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.             //     ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
  145.             //     $e->getReason()
  146.             // ));
  147.             $this->addFlash('reset_password_error'"Erreur lors de l'envoi du mail");
  148.             return $this->redirectToRoute('app_check_email');
  149.         }
  150.         $mailerService->sendPasswordResettingEmail($user$resetToken);
  151.         // Store the token object in session for retrieval in check-email route.
  152.         $this->setTokenObjectInSession($resetToken);
  153.         return $this->redirectToRoute('app_check_email');
  154.     }
  155. }