src/Controller/ResetPasswordController.php line 51

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Event\User\PasswordResetEmailEvent;
  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\MailerInterface;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  20. use App\Service\DynamicHostService;
  21. #[Route('/reinitialiser-mot-de-passe')]
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     private $resetPasswordHelper;
  26.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, private EventDispatcherInterface $dispatcher,private DynamicHostService $dynamicHostService)
  27.     {
  28.         $this->resetPasswordHelper $resetPasswordHelper;
  29.     }
  30.     /**
  31.      * Display & process form to request a password reset.
  32.      */
  33.     #[Route(''name'app_forgot_password_request')]
  34.     public function request(Request $requestMailerInterface $mailer): Response
  35.     {
  36.         $form $this->createForm(ResetPasswordRequestFormType::class);
  37.         $form->handleRequest($request);
  38.         
  39.         if ($form->isSubmitted() && $form->isValid()) {
  40.             return $this->processSendingPasswordResetEmail(
  41.                 $form->get('email')->getData(),
  42.                 $mailer
  43.             );
  44.         }
  45.         return $this->render('reset_password/request.html.twig', [
  46.             'requestForm' => $form->createView(),
  47.         ]);
  48.     }
  49.     /**
  50.      * Confirmation page after a user has requested a password reset.
  51.      */
  52.     #[Route('/email-envoye'name'app_check_email')]
  53.     public function checkEmail(Request $request): Response
  54.     {
  55.         // Generate a fake token if the user does not exist or someone hit this page directly.
  56.         // This prevents exposing whether or not a user was found with the given email address or not
  57.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  58.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  59.         }
  60.         return $this->render('reset_password/check_email.html.twig', [
  61.             'resetToken' => $resetToken,
  62.             'mail'=>$request->query->get('email'false),
  63.         ]);
  64.     }
  65.     /**
  66.      * Validates and process the reset URL that the user clicked in their email.
  67.      */
  68.     #[Route('/reset/{token}'name'app_reset_password')]
  69.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherInterfacestring $token null): Response
  70.     {
  71.         if ($token) {
  72.             // We store the token in session and remove it from the URL, to avoid the URL being
  73.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  74.             $this->storeTokenInSession($token);
  75.             return $this->redirectToRoute('app_reset_password');
  76.         }
  77.         $token $this->getTokenFromSession();
  78.         if (null === $token) {
  79.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  80.         }
  81.         try {
  82.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  83.             $mdp $user->getPassword();
  84.         } catch (ResetPasswordExceptionInterface $e) {
  85.             $this->addFlash('reset_password_error'sprintf(
  86.                 'There was a problem validating your reset request - %s',
  87.                 $e->getReason()
  88.             ));
  89.             return $this->redirectToRoute('app_forgot_password_request');
  90.         }
  91.         // The token is valid; allow the user to change their password.
  92.         $form $this->createForm(ChangePasswordFormType::class);
  93.         $form->handleRequest($request);
  94.         if ($form->isSubmitted() && $form->isValid()) {
  95.             
  96.             $newPassword =  $form->get('plainPassword')->getData(); 
  97.             if($userPasswordHasherInterface->isPasswordValid($user$form->get('plainPassword')->getData())){
  98.                 return $this->render('reset_password/reset.html.twig', [
  99.                     'resetForm' => $form->createView(),
  100.                     'error'=>"Veuillez saisir un nouveau mot de passe diffĂ©rent de l'ancien."
  101.                 ]);
  102.             }
  103.                 // Encode(hash) the plain password, and set it.
  104.                 $encodedPassword $userPasswordHasherInterface->hashPassword(
  105.                     $user,
  106.                     $newPassword
  107.                 );
  108.             $user->setPassword($encodedPassword);
  109.                 $allUser $this->getDoctrine()->getRepository(User::class)->getUserWithSameMail($user->getEmail()
  110.             );
  111.             //get all child and change password
  112.             foreach ($allUser as $children) {
  113.                 $encodedPassword $userPasswordHasherInterface->hashPassword(
  114.                     $children,
  115.                     $newPassword
  116.                 );
  117.                 $children->setPassword($encodedPassword);
  118.                 $this->getDoctrine()->getManager()->persist($children);
  119.             }
  120.             
  121.             
  122.             $this->getDoctrine()->getManager()->flush();
  123.             // A password reset token should be used only once, remove it.
  124.             $this->resetPasswordHelper->removeResetRequest($token);
  125.             // The session is cleaned up after the password has been changed.
  126.             $this->cleanSessionAfterReset();
  127.             return $this->redirectToRoute('app_login');
  128.         }
  129.         return $this->render('reset_password/reset.html.twig', [
  130.             'resetForm' => $form->createView(),
  131.         ]);
  132.     }
  133.     #[Route('/new-password/{id}'name'app_new_password')]
  134.     public function changePassword(User $user): Response
  135.     {
  136.         return $this->render('reset_password/request-new-password.html.twig', [
  137.             'user'=>$user
  138.         ]);
  139.     }
  140.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  141.     {
  142.         $company $this->dynamicHostService->getCompany();
  143.         $users $this->getDoctrine()->getRepository(User::class)->getUserWithSameMailWithCompany($emailFormData,$company);
  144.         // Do not reveal whether a user account was found or not.
  145.         if (empty($users)) {
  146.             return $this->redirectToRoute('app_check_email');
  147.         }
  148.         try {
  149.             foreach ($users as $userResetToken) {
  150.                 $resetToken $this->resetPasswordHelper->generateResetToken($userResetToken);
  151.                 $userResetToken->setResetToken($resetToken);
  152.                 break;
  153.             }
  154.         } catch (ResetPasswordExceptionInterface $e) {
  155.             // If you want to tell the user why a reset email was not sent, uncomment
  156.             // the lines below and change the redirect to 'app_forgot_password_request'.
  157.             // Caution: This may reveal if a user is registered or not.
  158.             //
  159.             $this->addFlash('reset_password_error'sprintf(
  160.                 'There was a problem handling your password reset request - %s',
  161.                 $e->getReason()
  162.             ));
  163.             return $this->redirectToRoute('app_check_email',["email"=>"error"]);
  164.         }
  165.       
  166.         $event = new PasswordResetEmailEvent($userResetToken);
  167.         $this->dispatcher->dispatch($eventPasswordResetEmailEvent::NAME);
  168.         // $this->setTokenObjectInSession($resetToken);
  169.         // $email = (new TemplatedEmail())
  170.         //     ->from(new Address('caroline.b@my-flow.fr','myFlow'))
  171.         //     ->to($user->getEmail())
  172.         //     ->subject('Votre demande de renouvellement de mot de passe - myFlow')
  173.         //     ->htmlTemplate('reset_password/email.html.twig')
  174.         //     ->context([
  175.         //         'resetToken' => $resetToken,
  176.         //     ])
  177.         // ;
  178.         // $mailer->send($email);
  179.         // Store the token object in session for retrieval in check-email route.
  180.        
  181.         return $this->redirectToRoute('app_check_email',["email"=>"send"]);
  182.     }
  183. }