src/Controller/ResetPasswordController.php line 42

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Informationeps;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  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\Exception\TransportExceptionInterface;
  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("/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.       //  dd("fffff");
  39.         $form $this->createForm(ResetPasswordRequestFormType::class);
  40.         $form->handleRequest($request);
  41.         if ($form->isSubmitted() && $form->isValid()) {
  42.             return $this->processSendingPasswordResetEmail(
  43.                 $form->get('email')->getData(),
  44.                 $mailer
  45.             );
  46.         }
  47.         return $this->render('admin/reset_password/request.html.twig', [
  48.             'requestForm' => $form->createView(),
  49.         ]);
  50.     }
  51.     /**
  52.      * Confirmation page after a user has requested a password reset.
  53.      *
  54.      * @Route("/check-email", name="app_check_email")
  55.      */
  56.     public function checkEmail(): Response
  57.     {
  58.         // Generate a fake token if the user does not exist or someone hit this page directly.
  59.         // This prevents exposing whether or not a user was found with the given email address or not
  60.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  61.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  62.         }
  63.         //dd($resetToken);
  64.         $eps $this->getDoctrine()->getRepository(Informationeps::class)->find(1);
  65.         return $this->render('admin/reset_password/check_email.html.twig', [
  66.             'resetToken' => $resetToken,
  67.             'eps'=>$eps
  68.         ]);
  69.     }
  70.     /**
  71.      * Validates and process the reset URL that the user clicked in their email.
  72.      *
  73.      * @Route("/reset/{token}", name="app_reset_password")
  74.      */
  75.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherInterfacestring $token null): Response
  76.     {
  77.         if ($token) {
  78.             // We store the token in session and remove it from the URL, to avoid the URL being
  79.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  80.             $this->storeTokenInSession($token);
  81.             return $this->redirectToRoute('app_reset_password');
  82.         }
  83.         $token $this->getTokenFromSession();
  84.         if (null === $token) {
  85.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  86.         }
  87.         try {
  88.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  89.         } catch (ResetPasswordExceptionInterface $e) {
  90.             $this->addFlash('reset_password_error'sprintf(
  91.                 'There was a problem validating your reset request - %s',
  92.                 $e->getReason()
  93.             ));
  94.             return $this->redirectToRoute('app_forgot_password_request');
  95.         }
  96.         // The token is valid; allow the user to change their password.
  97.         $form $this->createForm(ChangePasswordFormType::class);
  98.         $form->handleRequest($request);
  99.         if ($form->isSubmitted() && $form->isValid()) {
  100.             // A password reset token should be used only once, remove it.
  101.             $this->resetPasswordHelper->removeResetRequest($token);
  102.             // Encode(hash) the plain password, and set it.
  103.             $encodedPassword $userPasswordHasherInterface->hashPassword(
  104.                 $user,
  105.                 $form->get('plainPassword')->getData()
  106.             );
  107.             $user->setPassword($encodedPassword);
  108.             $this->getDoctrine()->getManager()->flush();
  109.             // The session is cleaned up after the password has been changed.
  110.             $this->cleanSessionAfterReset();
  111.             return $this->redirectToRoute('app_home_admin');
  112.         }
  113.         return $this->render('admin/reset_password/reset.html.twig', [
  114.             'resetForm' => $form->createView(),
  115.         ]);
  116.     }
  117.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  118.     {
  119.         // get eps information
  120.         //$eps = $this->getDoctrine()->getRepository(Informationeps::class)->find(1);
  121.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  122.             'email' => $emailFormData,
  123.         ]);
  124.         
  125.         // Do not reveal whether a user account was found or not.
  126.         if (!$user) {
  127.             return $this->redirectToRoute('app_check_email');
  128.         }
  129.         
  130.         try {
  131.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  132.             //dd($resetToken);
  133.         } catch (ResetPasswordExceptionInterface $e) {
  134.             // If you want to tell the user why a reset email was not sent, uncomment
  135.             // the lines below and change the redirect to 'app_forgot_password_request'.
  136.             // Caution: This may reveal if a user is registered or not.
  137.             //
  138.             // $this->addFlash('reset_password_error', sprintf(
  139.             //     'There was a problem handling your password reset request - %s',
  140.             //     $e->getReason()
  141.             // ));
  142.             
  143.             return $this->redirectToRoute('app_check_email');
  144.         }
  145.         $email = (new TemplatedEmail())
  146.             ->from(new Address('eps@setit.fr''EPS'))
  147.             ->to($user->getEmail())
  148.             ->subject('RĂ©initialisation de votre mot de passe')
  149.             ->htmlTemplate('admin/reset_password/email.html.twig')
  150.             ->context([
  151.                 'resetToken' => $resetToken,
  152.             ])
  153.         ;
  154.         try{
  155.             $mailer->send($email);
  156.         } catch (TransportExceptionInterface $e) {
  157.             return dd($e);
  158.         }
  159.         // Store the token object in session for retrieval in check-email route.
  160.         $this->setTokenObjectInSession($resetToken);
  161.         
  162.         return $this->redirectToRoute('app_check_email');
  163.     }
  164. }