src/Controller/ResetPasswordController.php line 44

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\Mime\Email;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  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. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $resetPasswordHelper;
  27.     private $entityManager;
  28.     private $router;
  29.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerUrlGeneratorInterface $router)
  30.     {
  31.         $this->resetPasswordHelper $resetPasswordHelper;
  32.         $this->entityManager $entityManager;
  33.         $this->router $router;
  34.     }
  35.     /**
  36.      * @Route("/forgot", name="forgot", methods={"GET", "POST"})
  37.      */
  38.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  39.     {
  40.         $form $this->createForm(ResetPasswordRequestFormType::class);
  41.         $form->handleRequest($request);
  42.         if ($form->isSubmitted() && $form->isValid()) {
  43.             return $this->processSendingPasswordResetEmail(
  44.                 $form->get('email')->getData(),
  45.                 $mailer,
  46.                 $translator,
  47.                 $request
  48.             );
  49.         }
  50.         return $this->render('reset_password/request.html.twig', [
  51.             'requestForm' => $form->createView(),
  52.         ]);
  53.     }
  54.     /**
  55.      * @Route("/check-email", name="app_check_email", methods={"GET"})
  56.      *  Confirmation page after a user has requested a password reset.
  57.      */
  58.     public function checkEmail(Request $request=null): Response
  59.     {
  60.         $referer = (string) $request->headers->get('referer'); // get the referer, it can be empty!
  61.         if(!empty($referer)) { //dirty fix :
  62.             //Quand on fait un password oublié, le premier login qui suit renvoie vers la page checkemail
  63.             //je ne trouve pas la raison donc redirection forcée vers home.
  64.             $refererPathInfo Request::create($referer)->getPathInfo();
  65.             $refererPathInfo str_replace($request->getScriptName(), ''$refererPathInfo);
  66.             $routeInfos =  $this->router->match($refererPathInfo);
  67.             $refererRoute $routeInfos['_route'] ?? '';
  68.             if ($refererRoute === 'login') {
  69.                 return $this->redirectToRoute('home');
  70.             }
  71.         }
  72.         // Generate a fake token if the user does not exist or someone hit this page directly.
  73.         // This prevents exposing whether or not a user was found with the given email address or not
  74.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  75.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  76.         }
  77.         return $this->render('reset_password/check_email.html.twig', [
  78.             'resetToken' => $resetToken,
  79.         ]);
  80.     }
  81.     /**
  82.      * @Route("/reset/{token}", name="app_reset_password", methods={"GET", "POST"})
  83.      */
  84.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  85.     {
  86.         if ($token) {
  87.             // We store the token in session and remove it from the URL, to avoid the URL being
  88.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  89.             $this->storeTokenInSession($token);
  90.             return $this->redirectToRoute('app_reset_password');
  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('forgot');
  105.         }
  106.         // The token is valid; allow the user to change their password.
  107.         $form $this->createForm(ChangePasswordFormType::class);
  108.         $form->handleRequest($request);
  109.         if ($form->isSubmitted() && $form->isValid()) {
  110.             // A password reset token should be used only once, remove it.
  111.             $this->resetPasswordHelper->removeResetRequest($token);
  112.             // Encode(hash) the plain password, and set it.
  113.             $encodedPassword $userPasswordHasher->hashPassword(
  114.                 $user,
  115.                 $form->get('plainPassword')->getData()
  116.             );
  117.             $user->setPassword($encodedPassword);
  118.             $this->entityManager->flush();
  119.             // The session is cleaned up after the password has been changed.
  120.             $this->cleanSessionAfterReset();
  121.             return $this->redirectToRoute('login');
  122.         }
  123.         return $this->render('reset_password/reset.html.twig', [
  124.             'resetForm' => $form->createView(),
  125.         ]);
  126.     }
  127.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translatorRequest $request): RedirectResponse
  128.     {
  129.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  130.             'email' => $emailFormData,
  131.         ]);
  132.         // Do not reveal whether a user account was found or not.
  133.         if (!$user) {
  134.             return $this->redirectToRoute('app_check_email');
  135.         }
  136.         try {
  137.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  138.             //Si null ==> user déjà demandé de reset
  139.             //le helper est dans vendor/symfonycasts/reset-password-bundle/src/ResetPasswordHelper.php
  140.             //Table :  reset_password_request
  141.         } catch (ResetPasswordExceptionInterface $e) {
  142.             // If you want to tell the user why a reset email was not sent, uncomment
  143.             // the lines below and change the redirect to 'app_forgot_password_request'.
  144.             // Caution: This may reveal if a user is registered or not.
  145.             //
  146.              $this->addFlash('reset_password_error'sprintf(
  147.                  '%s - %s',
  148.                  $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  149.                  $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  150.              ));
  151.             //return $this->redirectToRoute('app_check_email');
  152.             return $this->redirectToRoute('forgot');
  153.         }
  154.         $mailerService = new MailerService();
  155.         $mailer $mailerService->getMailer();
  156.         $linkReset $request->getSchemeAndHttpHost().$this->generateUrl('app_reset_password',['token' => $resetToken->getToken()]);
  157.         $hrefLink "<a href='".$linkReset."'>Cliquez pour créer un nouveau mot de passe</a>";
  158.         $htmlBody "<h1>Vous avez demandé à réinitialiser votre mot de passe</h1>";
  159.         $htmlBody.= "<br />";
  160.         $htmlBody.= $hrefLink;
  161.         $textBody "Vous avez demandé à réinitialiser votre mot de passe\r\n";
  162.         $textBody.= "Allez sur ce lien pour générer un nouveau mot de passe \r\n";
  163.         $textBody.= $linkReset;
  164.         try {
  165.             $email = (new Email())
  166.                 ->from('studiana@studio-anatole.com')
  167.                 ->to($user->getEmail())
  168.                 ->subject('Réinitialisation du mot de passe')
  169.                 ->text($textBody)
  170.                 ->html($htmlBody);
  171.             $toto $mailer->send($email);
  172.             $this->addFlash('reset_password_success'"Vous allez recevoir un email de réinitialisation");
  173.         } catch (\Exception $e) {
  174.             dd($e);
  175.         }
  176. /*
  177.         $email = (new TemplatedEmail())
  178.             ->from(new Address('studiana@studio-anatole.fr', 'Studiana'))
  179.             ->to($user->getEmail())
  180.             ->subject('Your password reset request')
  181.             ->htmlTemplate('reset_password/email.html.twig')
  182.             ->context([
  183.                 'resetToken' => $resetToken,
  184.             ])
  185.         ;
  186.         $newMailer = $mailerService->getMailer();
  187.        // dd($email);
  188.         try {
  189.             $newMailer->send($email);
  190. //            $mailer->send($email);
  191.         } catch (\Exception $e){
  192.             dd($e);
  193.             // some error prevented the email sending; display an
  194.             // error message or try to resend the message
  195.         }
  196. */
  197.         // Store the token object in session for retrieval in check-email route.
  198.         $this->setTokenObjectInSession($resetToken);
  199.         return $this->redirectToRoute('app_check_email');
  200.     }
  201. }