src/Controller/ResetPasswordController.php line 81

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\ResetPasswordRequest;
  5. use Symfony\Component\Mime\Email;
  6. use Symfony\Component\Mime\Address;
  7. use App\Form\ChangePasswordFormType;
  8. use Symfony\Component\Mailer\Mailer;
  9. use Symfony\Component\Mailer\Transport;
  10. // use Doctrine\ORM\EntityManagerInterface;
  11. use App\Form\ResetPasswordRequestFormType;
  12. // use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  13. // use Symfony\Component\HttpFoundation\Request;
  14. // use Symfony\Component\Mailer\MailerInterface;
  15. // use Symfony\Component\HttpFoundation\Response;
  16. // use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. // use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  23. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  24. // https://packagist.org/packages/symfony/mailer
  25. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\Mailer\MailerInterface;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. use Symfony\Component\Validator\Constraints\Date;
  31. use Symfony\Component\HttpFoundation\JsonResponse;
  32. use Symfony\Component\EventDispatcher\EventDispatcher;
  33. use Symfony\Component\Mailer\EventListener\MessageListener;
  34. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  35. use Doctrine\ORM\EntityManagerInterface;
  36. use Twig\Environment as TwigEnvironment;
  37. use Symfony\Bridge\Twig\Mime\BodyRenderer;
  38. use Throwable;
  39. use Twig\Loader\FilesystemLoader;
  40. /**
  41.  * @Route("/reset-password")
  42.  */
  43. class ResetPasswordController extends AbstractController
  44. {
  45.     use ResetPasswordControllerTrait;
  46.     private $resetPasswordHelper;
  47.     private $entityManager;
  48.     private $mailer;
  49.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerMailerInterface $mailer)
  50.     {
  51.         $this->resetPasswordHelper $resetPasswordHelper;
  52.         $this->entityManager $entityManager;
  53.         // $this->mailer = $mailer;
  54.         $loader = new FilesystemLoader('../templates');
  55.         // $twig = new TwigEnvironment();
  56.         $twig = new TwigEnvironment($loader);
  57.         $messageListener = new MessageListener(null, new BodyRenderer($twig));
  58.         $eventDispatcher = new EventDispatcher();
  59.         $eventDispatcher->addSubscriber($messageListener);
  60.         // $transport = Transport::fromDsn('smtp://localhost', $eventDispatcher);
  61.         // $mailer = new Mailer($transport, null, $eventDispatcher);
  62.         $transport Transport::fromDsn('sendmail://default'$eventDispatcher);
  63.         $this->mailer = new Mailer($transportnull$eventDispatcher);
  64.     }
  65.     /**
  66.      * Display & process form to request a password reset.
  67.      *
  68.      * @Route("", name="app_forgot_password_request")
  69.      */
  70.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  71.     {
  72.         $form $this->createForm(ResetPasswordRequestFormType::class);
  73.         $form->handleRequest($request);
  74.         $em $this->getDoctrine()->getManager();
  75.         
  76.         $notif "";
  77.         $resetToken null;
  78.         
  79.         if ($form->isSubmitted() && $form->isValid()) {
  80.             $email $form->get('email')->getData();
  81.             $user $em->getRepository(User::class)->findOneBy([
  82.                 'email' => $email,
  83.             ]);
  84.             try {
  85.                 $resetToken $this->resetPasswordHelper->generateResetToken($user);
  86.             }
  87.             
  88.             catch (Throwable $e) {
  89.                 return $this->redirectToRoute('app_check_email');
  90.             }
  91.             $resetRequest $em->getRepository(ResetPasswordRequest::class)->findOneBy(
  92.                 array(
  93.                     "user" => $user,
  94.                     "id" => "DESC"
  95.                 )
  96.             );
  97.             // var_dump($resetToken->getToken());
  98.             // exit;
  99.             
  100.             if ($user) {
  101.                 $email = (new TemplatedEmail())
  102.                     ->from('passwordreset@multypack.fr')
  103.                     // ->to('fbhatti@bleu-digital.fr')
  104.                     ->to($email)
  105.                     ->subject('Mot de passe oublié MULTYPACK')
  106.                     ->htmlTemplate('reset_password/email.html.twig')
  107.                     ->context([
  108.                         'resetToken' => $resetToken,
  109.                         'resetRequest' => $resetRequest,
  110.                         // 'token' => $resetRequest->getHashedToken(),
  111.                         'token' => $resetToken->getToken(),
  112.                         // 'selector' => $resetRequest->getSelector(),
  113.                         "difference" => 1
  114.                         // "difference" => ((array) date_diff($resetRequest->getExpiresAt(), $resetRequest->getRequestedAt()))["h"]
  115.                     ])
  116.                 ;
  117.                 $this->mailer->send($email);
  118.                 return $this->redirectToRoute("app_check_email");
  119.             }
  120.             $this->setTokenObjectInSession($resetToken);
  121.             return $this->redirectToRoute('login');
  122.             // return $this->processSendingPasswordResetEmail(
  123.             //     $form->get('email')->getData(),
  124.             //     $translator
  125.             // );
  126.         }
  127.         return $this->render('reset_password/request.html.twig', [
  128.             'requestForm' => $form->createView(),
  129.             "notif" => $notif
  130.         ]);
  131.     }
  132.     /**
  133.      * Confirmation page after a user has requested a password reset.
  134.      *
  135.      * @Route("/check-email", name="app_check_email")
  136.      */
  137.     public function checkEmail(): Response
  138.     {
  139.         // Generate a fake token if the user does not exist or someone hit this page directly.
  140.         // This prevents exposing whether or not a user was found with the given email address or not
  141.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  142.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  143.         }
  144.         return $this->render('reset_password/check_email.html.twig', [
  145.             'resetToken' => $resetToken,
  146.         ]);
  147.     }
  148.     /**
  149.      * Validates and process the reset URL that the user clicked in their email.
  150.      *
  151.      * @Route("/reset/{token}", name="app_reset_password")
  152.      */
  153.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  154.     {
  155.         if ($token) {
  156.             // We store the token in session and remove it from the URL, to avoid the URL being
  157.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  158.             $this->storeTokenInSession($token);
  159.             return $this->redirectToRoute('app_reset_password');
  160.         }
  161.         $token $this->getTokenFromSession();
  162.         if (null === $token) {
  163.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  164.         }
  165.         try {
  166.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  167.         } catch (ResetPasswordExceptionInterface $e) {
  168.             $this->addFlash('reset_password_error'sprintf(
  169.                 '%s - %s',
  170.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  171.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  172.             ));
  173.             return $this->redirectToRoute('app_forgot_password_request');
  174.         }
  175.         // The token is valid; allow the user to change their password.
  176.         $form $this->createForm(ChangePasswordFormType::class);
  177.         $form->handleRequest($request);
  178.         if ($form->isSubmitted() && $form->isValid()) {
  179.             // A password reset token should be used only once, remove it.
  180.             $this->resetPasswordHelper->removeResetRequest($token);
  181.             // Encode(hash) the plain password, and set it.
  182.             $encodedPassword $userPasswordHasher->hashPassword(
  183.                 $user,
  184.                 $form->get('plainPassword')->getData()
  185.             );
  186.             $user->setPassword($encodedPassword);
  187.             $this->entityManager->flush();
  188.             // The session is cleaned up after the password has been changed.
  189.             $this->cleanSessionAfterReset();
  190.             return $this->redirectToRoute('login');
  191.         }
  192.         return $this->render('reset_password/reset.html.twig', [
  193.             'resetForm' => $form->createView(),
  194.         ]);
  195.     }
  196.     private function processSendingPasswordResetEmail(string $emailFormDataTranslatorInterface $translator): RedirectResponse
  197.     {
  198.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  199.             'email' => $emailFormData,
  200.         ]);
  201.         // Do not reveal whether a user account was found or not.
  202.         if (!$user) {
  203.             return $this->redirectToRoute('app_check_email');
  204.         }
  205.         try {
  206.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  207.             $email = (new TemplatedEmail())
  208.                 ->from('passwordreset@multypack.fr')
  209.                 // ->to('fbhatti@bleu-digital.fr')
  210.                 ->to('fdieu@bleu-digital.fr')
  211.                 ->subject('Mot de passe oublié MULTYPACK')
  212.                 ->text("test")
  213.                 // ->htmlTemplate('reset_password/email.html.twig')
  214.                 // ->context([
  215.                 //     'resetToken' => $resetToken,
  216.                 // ])
  217.             ;
  218.     
  219.             // décommenter avant d'envoyer en prod
  220.             try {
  221.                 //$mailer->send($email);
  222.                 $this->mailer->send($email);
  223.             } catch (TransportException $e) {
  224.                 \var_dump$e->getDebug() );
  225.             }
  226.         } catch (ResetPasswordExceptionInterface $e) {
  227.             // If you want to tell the user why a reset email was not sent, uncomment
  228.             // the lines below and change the redirect to 'app_forgot_password_request'.
  229.             // Caution: This may reveal if a user is registered or not.
  230.             //
  231.             // $this->addFlash('reset_password_error', sprintf(
  232.             //     '%s - %s',
  233.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  234.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  235.             // ));
  236.             return $this->redirectToRoute('app_check_email');
  237.         }
  238.         // Store the token object in session for retrieval in check-email route.
  239.         $this->setTokenObjectInSession($resetToken);
  240.         return $this->redirectToRoute('app_check_email');
  241.     }
  242. }