src/Controller/ResetPasswordController.php line 42

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 PHPMailer\PHPMailer\PHPMailer;
  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\Mailer\Transport\SendmailTransport;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. /**
  21.  * @Route("/reset-password")
  22.  */
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $resetPasswordHelper;
  27.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  28.     {
  29.         $this->resetPasswordHelper $resetPasswordHelper;
  30.     }
  31.     /**
  32.      * Display & process form to request a password reset.
  33.      *
  34.      * @Route("", name="app_forgot_password_request")
  35.      */
  36.     public function request(Request $requestMailerInterface $mailer): Response
  37.     {
  38.         $form $this->createForm(ResetPasswordRequestFormType::class);
  39.         $form->handleRequest($request);
  40.         if ($form->isSubmitted() && $form->isValid()) {
  41.             return $this->processSendingPasswordResetEmail(
  42.                 $form->get('email')->getData(),
  43.                 $mailer
  44.             );
  45.         }
  46.         /*if ( $request->get('_nu') ){
  47.             $this->addFlash('reset_password_error', 'Cette adresse email n\'existe pas');
  48.         }*/
  49.         return $this->render('reset_password/request.html.twig', [
  50.             'requestForm' => $form->createView(),
  51.         ]);
  52.     }
  53.     /**
  54.      * Confirmation page after a user has requested a password reset.
  55.      *
  56.      * @Route("/check-email", name="app_check_email")
  57.      */
  58.     public function checkEmail(): Response
  59.     {
  60.         // We prevent users from directly accessing this page
  61.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  62.             return $this->redirectToRoute('app_forgot_password_request', ['_nu' => md5(time())]);
  63.         }
  64.         return $this->render('reset_password/check_email.html.twig', [
  65.             'resetToken' => $resetToken,
  66.         ]);
  67.     }
  68.     /**
  69.      * Validates and process the reset URL that the user clicked in their email.
  70.      *
  71.      * @Route("/reset/{token}", name="app_reset_password")
  72.      */
  73.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  74.     {
  75.         if ($token) {
  76.             // We store the token in session and remove it from the URL, to avoid the URL being
  77.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  78.             $this->storeTokenInSession($token);
  79.             return $this->redirectToRoute('app_reset_password');
  80.         }
  81.         $token $this->getTokenFromSession();
  82.         if (null === $token) {
  83.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  84.         }
  85.         try {
  86.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  87.         } catch (ResetPasswordExceptionInterface $e) {
  88.             $this->addFlash('reset_password_error'sprintf(
  89.                 'There was a problem validating your reset request - %s',
  90.                 $e->getReason()
  91.             ));
  92.             return $this->redirectToRoute('app_forgot_password_request');
  93.         }
  94.         // The token is valid; allow the user to change their password.
  95.         $form $this->createForm(ChangePasswordFormType::class);
  96.         $form->handleRequest($request);
  97.         if ($form->isSubmitted() && $form->isValid()) {
  98.             // A password reset token should be used only once, remove it.
  99.             $this->resetPasswordHelper->removeResetRequest($token);
  100.             // Encode the plain password, and set it.
  101.             $encodedPassword $passwordEncoder->encodePassword(
  102.                 $user,
  103.                 $form->get('plainPassword')->getData()
  104.             );
  105.             $user->setPassword($encodedPassword);
  106.             $this->getDoctrine()->getManager()->flush();
  107.             // The session is cleaned up after the password has been changed.
  108.             $this->cleanSessionAfterReset();
  109.             return $this->redirectToRoute('app_login');
  110.         }
  111.         return $this->render('reset_password/reset.html.twig', [
  112.             'resetForm' => $form->createView(),
  113.         ]);
  114.     }
  115.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  116.     {
  117.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  118.             'email' => $emailFormData,
  119.         ]);
  120.         // Do not reveal whether a user account was found or not.
  121.         if (!$user) {
  122.             $this->addFlash('reset_password_error''Cette adresse email n\'existe pas');
  123.             return $this->redirectToRoute('app_check_email');
  124.         }
  125.         try {
  126.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  127.         } catch (ResetPasswordExceptionInterface $e) {
  128.             // If you want to tell the user why a reset email was not sent, uncomment
  129.             // the lines below and change the redirect to 'app_forgot_password_request'.
  130.             // Caution: This may reveal if a user is registered or not.
  131.             //
  132.             // $this->addFlash('reset_password_error', sprintf(
  133.             //     'There was a problem handling your password reset request - %s',
  134.             //     $e->getReason()
  135.             // ));
  136.             $this->addFlash('reset_password_error'$e->getReason());
  137.             return $this->redirectToRoute('app_check_email');
  138.         }
  139.         /*$transport = new SendmailTransport();
  140.         $email = (new TemplatedEmail())
  141.             ->from(new Address('contact@yziprod.fr', 'Yziapp'))
  142.             ->to($user->getEmail())
  143.             ->subject('RĂ©initialisation de votre mot de passe')
  144.             ->html($this->get('twig')->render('reset_password/email.html.twig', ['resetToken' => $resetToken]))
  145.             /*->htmlTemplate('reset_password/email.html.twig')
  146.             ->context([
  147.                 'resetToken' => $resetToken,
  148.             ])*/
  149.         ;/*
  150.         $transport->send($email);*/
  151.         $phpMailer = new PHPMailer();
  152.         $phpMailer->SMTPAuth   TRUE;
  153.         $phpMailer->SMTPSecure "tls";
  154.         $phpMailer->Port       587;
  155.         $phpMailer->Host       "smtp.gmail.com";
  156.         $phpMailer->Username   "yziapp@yziprod.fr";
  157.         $phpMailer->Password   "1983Jomo1983**";
  158.         $phpMailer->IsHTML(true);
  159.         $phpMailer->AddAddress($user->getEmail(), $user->getFullName());
  160.         $phpMailer->SetFrom('contact@yziprod.fr''Yziapp');
  161.         $phpMailer->Subject "RĂ©initialisation de votre mot de passe";
  162.         $content $this->get('twig')->render('reset_password/email.html.twig', ['resetToken' => $resetToken]);
  163.         $phpMailer->MsgHTML($content);
  164.         $phpMailer->send();
  165.         // Store the token object in session for retrieval in check-email route.
  166.         $this->setTokenObjectInSession($resetToken);
  167.         return $this->redirectToRoute('app_check_email');
  168.     }
  169. }