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 Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private ResetPasswordHelperInterface $resetPasswordHelper;
  28.     private EntityManagerInterface $entityManager;
  29.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  30.     {
  31.         $this->resetPasswordHelper $resetPasswordHelper;
  32.         $this->entityManager $entityManager;
  33.     }
  34.     /**
  35.      * Display & process form to request a password reset.
  36.      *
  37.      * @Route("", name="app_forgot_password_request")
  38.      */
  39.     public function request(AuthenticationUtils $authenticationUtilsRequest $requestMailerInterface $mailerTranslatorInterface $translator): Response
  40.     {
  41.         $form $this->createForm(ResetPasswordRequestFormType::class);
  42.         $form->handleRequest($request);
  43.         if ($form->isSubmitted() && $form->isValid()) {
  44.             return $this->processSendingPasswordResetEmail(
  45.                 $form->get('email')->getData(),
  46.                 $mailer,
  47.                 $translator
  48.             );
  49.         }
  50.         // Dernier email saisi
  51.         $lastUsername $authenticationUtils->getLastUsername();
  52.         return $this->render('reset_password/request.html.twig', [
  53.             'requestForm' => $form->createView(),
  54.             'last_username' => $lastUsername,
  55.         ]);
  56.     }
  57.     /**
  58.      * Confirmation page after a user has requested a password reset.
  59.      *
  60.      * @Route("/check-email", name="app_check_email")
  61.      */
  62.     public function checkEmail(): Response
  63.     {
  64.         // Generate a fake token if the user does not exist or someone hit this page directly.
  65.         // This prevents exposing whether or not a user was found with the given email address or not
  66.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  67.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  68.         }
  69.         return $this->render('reset_password/check_email.html.twig', [
  70.             'resetToken' => $resetToken,
  71.         ]);
  72.     }
  73.     /**
  74.      * Validates and processes the reset URL that the user clicked in their email.
  75.      *
  76.      * @Route("/reset/{token}", name="app_reset_password_token")
  77.      */
  78.     public function resetWithToken(Request $requeststring $token): RedirectResponse
  79.     {
  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.     /**
  86.      * Displays and processes the password reset form when no token is in the URL.
  87.      *
  88.      * @Route("/reset", name="app_reset_password")
  89.      */
  90.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorMailerInterface $mailer): Response
  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('reset_password_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.         $form $this->createForm(ChangePasswordFormType::class);
  107.         $form->handleRequest($request);
  108.         if ($form->isSubmitted() && $form->isValid()) {
  109.             $this->resetPasswordHelper->removeResetRequest($token);
  110.             $encodedPassword $userPasswordHasher->hashPassword(
  111.                 $user,
  112.                 $form->get('plainPassword')->getData()
  113.             );
  114.             $user->setPassword($encodedPassword);
  115.             $this->entityManager->flush();
  116.             $email = (new TemplatedEmail())
  117.                 ->from(new Address('moussa@halogari.yt''HaloGari'))
  118.                 ->to($user->getEmail())
  119.                 ->subject('Votre mot de passe a été modifié')
  120.                 ->htmlTemplate('emails/password_reset_success.html.twig')
  121.                 ->context(['user' => $user])
  122.                 ->embedFromPath($this->getParameter('kernel.project_dir') . '/public/images/logo.png''logo_halogari');
  123.             try {
  124.                 $mailer->send($email);
  125.             } catch (\Throwable $e) {
  126.                 $e->getMessage();
  127.             }
  128.             $this->cleanSessionAfterReset();
  129.             $this->addFlash('success''Votre mot de passe a bien été modifié.');
  130.             return $this->redirectToRoute('app_login');
  131.         }
  132.         return $this->render('reset_password/reset.html.twig', [
  133.             'resetForm' => $form->createView(),
  134.         ]);
  135.     }
  136.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  137.     {
  138.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  139.             'email' => $emailFormData,
  140.         ]);
  141.         // Do not reveal whether a user account was found or not.
  142.         if (!$user) {
  143.             return $this->redirectToRoute('app_check_email');
  144.         }
  145.         try {
  146.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  147.         } catch (ResetPasswordExceptionInterface $e) {
  148.             // If you want to tell the user why a reset email was not sent, uncomment
  149.             // the lines below and change the redirect to 'app_forgot_password_request'.
  150.             // Caution: This may reveal if a user is registered or not.
  151.             //
  152.             // $this->addFlash('reset_password_error', sprintf(
  153.             //     '%s - %s',
  154.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  155.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  156.             // ));
  157.             return $this->redirectToRoute('app_check_email');
  158.         }
  159.         $email = (new TemplatedEmail())
  160.             ->from(new Address('moussa@halogari.yt''HaloGari'))
  161.             ->to($user->getEmail())
  162.             ->subject('Réinitialisation de votre mot de passe')
  163.             ->htmlTemplate('emails/reset_password.html.twig')
  164.             ->context([
  165.                 'resetToken' => $resetToken,
  166.             ])
  167.             ->embedFromPath($this->getParameter('kernel.project_dir') . '/public/images/logo.png''logo_halogari');
  168.         ;
  169.         try {
  170.             $mailer->send($email);
  171.         } catch (\Throwable $e) {
  172.             $e->getMessage();
  173.         }
  174.         // Store the token object in session for retrieval in check-email route.
  175.         $this->setTokenObjectInSession($resetToken);
  176.         return $this->redirectToRoute('app_check_email');
  177.     }
  178. }