src/Controller/SecurityController.php line 361

Open in your IDE?
  1. <?php
  2. // src/Controller/SecurityController.php
  3. namespace App\Controller;
  4. use App\Entity\Fonctions;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use App\Entity\User;
  10. use App\Entity\Sejour;
  11. use App\Service\EmailsCmdService;
  12. use App\Service\UserService;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. class SecurityController extends AbstractController
  17. {
  18.     private $em;
  19.     private $userService;
  20.     private $emailsCmdService;
  21.     public function __construct(EntityManagerInterface $emUserService $userServiceEmailsCmdService $emailsCmdService)
  22.     {
  23.         $this->em $em;
  24.         $this->userService $userService;
  25.         $this->emailsCmdService $emailsCmdService;
  26.     }
  27.     /**
  28.      * @Route("/LoginAdmin", name="app_login")
  29.      */
  30.     public function login(AuthenticationUtils $authenticationUtils): Response
  31.     {
  32.         // get the login error if there is one
  33.         $error $authenticationUtils->getLastAuthenticationError();
  34.         // last username entered by the user
  35.         $lastUsername $authenticationUtils->getLastUsername();
  36.         return $this->render('security/login.html.twig', [
  37.             'last_username' => $lastUsername,
  38.             'error' => $error
  39.         ]);
  40.     }
  41.     /**
  42.      * @Route("/logout", name="app_logout")
  43.      */
  44.     public function logout()
  45.     {
  46.         throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
  47.     }
  48.     /**
  49.      * @Route("/Parent/logout", name="app_logout_parent")
  50.      */
  51.     public function logoutParent()
  52.     {
  53.         throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
  54.     }
  55.     /**
  56.      * @Route("/Accompagnateur/logout", name="app_logout_Accompagnateur")
  57.      */
  58.     public function logoutAcompa()
  59.     {
  60.         throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
  61.     }
  62.     /**
  63.      * @Route("/Partenaire/logout", name="app_logout_Partenaire")
  64.      */
  65.     public function logoutPartenaire()
  66.     {
  67.         throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
  68.     }
  69.     /**
  70.      * @Route("/Accompagnateur/login", name="app_back_Acommpa", methods={"GET", "POST"})
  71.      */
  72.     public function Acommpalogin(AuthenticationUtils $authenticationUtils): Response
  73.     {
  74.         // Si l'utilisateur est déjà connecté, rediriger vers la page du séjour
  75.         if ($this->getUser()) {
  76.             return $this->redirectToRoute('DetailsSejourAcc');
  77.         }
  78.         // get the login error if there is one
  79.         $error $authenticationUtils->getLastAuthenticationError();
  80.         // last username entered by the user
  81.         $lastUsername $authenticationUtils->getLastUsername();
  82.         $listeFonctions $this->em->getRepository(Fonctions::class)->findBy(array('statut' => 2));
  83.         return $this->render('Accompagnateur/LoginAccompagnateur.html.twig', ['listeFonctions' => $listeFonctions'last_username' => $lastUsername'error' => $error]);
  84.     }
  85.     /**
  86.      * @Route("/ForgotPass",name="forgotPass")
  87.      */
  88.     function forgot_Password()
  89.     {
  90.         return $this->render('security/DemandePassword.html.twig');
  91.     }
  92.     /**
  93.      * @Route("/forgotPassparent",name="forgotPassparent")
  94.      */
  95.     function forgot_Password2()
  96.     {
  97.         return $this->render('security/DemandePasswordParent.html.twig');
  98.     }
  99.     /**
  100.      * @Route("/Accompagnateur/NewPassword",name="New_Password")
  101.      */
  102.     function Create_New_Password(Request $request)
  103.     {
  104.         $password $request->get('password');
  105.         $userId $request->get('userID');
  106.         $USerService $this->userService;
  107.         $user $this->getDoctrine()
  108.             ->getRepository(User::class)->find($userId);
  109.         $USerService->updatPassw($user$password);
  110.         return new response("done");
  111.     }
  112.     /**
  113.      * @Route("/changerPassword",name="changer_Password")
  114.      */
  115.     function changerPassword(Request $request)
  116.     {
  117.         $password $request->get('password');
  118.         $userId $request->get('userID');
  119.         $USerService $this->userService;
  120.         $USerService->updatPassw($userId$password);
  121.         return new response("done");
  122.     }
  123.     /**
  124.      * @Route("/Accompagnateur/request_password",name="request_password", methods={"GET", "POST"})
  125.      */
  126.     function request_password(Request $request): Response
  127.     {
  128.         try {
  129.             // Si c'est une requête GET (accès direct à la page), afficher le formulaire
  130.             if ($request->isMethod('GET')) {
  131.                 return $this->render('security/DemandePassword.html.twig');
  132.             }
  133.             
  134.             // Si c'est une requête POST (soumission du formulaire)
  135.             $code $request->request->get('code');
  136.             
  137.             // Si aucun code n'est fourni, afficher le formulaire avec un message d'erreur
  138.             if (empty($code)) {
  139.                 return $this->render('security/DemandePassword.html.twig', [
  140.                     'error' => 'Veuillez saisir votre code séjour'
  141.                 ]);
  142.             }
  143.             
  144.             $sejour $this->em->getRepository(Sejour::class)->findOneBy(['codeSejour' => $code]);
  145.             if ($sejour == null) {
  146.                 // Code séjour invalide
  147.                 return $this->render('security/DemandePassword.html.twig', [
  148.                     'error' => 'Code séjour introuvable. Veuillez vérifier votre code et réessayer.'
  149.                 ]);
  150.             }
  151.             
  152.             $user $sejour->getIdAcommp();
  153.             
  154.             if ($user == null) {
  155.                 // Aucun accompagnateur associé au séjour
  156.                 return $this->render('security/DemandePassword.html.twig', [
  157.                     'error' => 'Aucun accompagnateur trouvé pour ce séjour. Veuillez contacter le support.'
  158.                 ]);
  159.             }
  160.             
  161.             // Utiliser l'email de réponse (reponseemail) si disponible, sinon l'email principal
  162.             $emailToSend $user->getReponseemail() ?: $user->getEmail();
  163.             
  164.             // Vérifier que l'utilisateur a un email
  165.             if (empty($emailToSend)) {
  166.                 return $this->render('security/DemandePassword.html.twig', [
  167.                     'error' => 'Aucun email associé à ce compte. Veuillez contacter le support.'
  168.                 ]);
  169.             }
  170.             
  171.             // Récupérer le mot de passe non crypté et le code séjour
  172.             $password $user->getPasswordNonCripted();
  173.             $codeSejour $sejour->getCodeSejour();
  174.             
  175.             // Si le mot de passe n'est pas disponible, générer un message d'erreur
  176.             if (empty($password)) {
  177.                 return $this->render('security/DemandePassword.html.twig', [
  178.                     'error' => 'Impossible de récupérer votre mot de passe. Veuillez contacter le support.'
  179.                 ]);
  180.             }
  181.             
  182.             // Envoyer l'email à l'adresse de réponse avec le mot de passe et le code séjour
  183.             $USerService $this->userService;
  184.             
  185.             try {
  186.                 $emailSent $USerService->sendPasswordMail($emailToSend$password$codeSejour);
  187.                 
  188.                 if (!$emailSent) {
  189.                     error_log("❌ Échec envoi email réinitialisation - Email: " $emailToSend);
  190.                     return $this->render('security/DemandePassword.html.twig', [
  191.                         'error' => 'Erreur lors de l\'envoi de l\'email. Veuillez réessayer plus tard ou contacter le support à contact@5sur5sejour.com.'
  192.                     ]);
  193.                 }
  194.                 
  195.                 error_log("✅ Email de réinitialisation envoyé avec succès à: " $emailToSend);
  196.                 
  197.                 // Afficher la page de confirmation
  198.                 return $this->render('security/DemandePasswordValide.html.twig', [
  199.                     'email' => $emailToSend
  200.                 ]);
  201.             } catch (\Exception $emailException) {
  202.                 error_log("❌ Exception lors de l'envoi de l'email: " $emailException->getMessage());
  203.                 error_log("Stack trace email: " $emailException->getTraceAsString());
  204.                 return $this->render('security/DemandePassword.html.twig', [
  205.                     'error' => 'Erreur lors de l\'envoi de l\'email: ' $emailException->getMessage() . '. Veuillez contacter le support.'
  206.                 ]);
  207.             }
  208.         } catch (\Exception $e) {
  209.             error_log("❌ Erreur dans request_password: " $e->getMessage());
  210.             error_log("Fichier: " $e->getFile() . " Ligne: " $e->getLine());
  211.             error_log("Stack trace: " $e->getTraceAsString());
  212.             
  213.             // En mode dev, afficher le message d'erreur complet
  214.             $errorMessage 'Une erreur est survenue. ';
  215.             if ($this->getParameter('kernel.environment') === 'dev') {
  216.                 $errorMessage .= 'Détails: ' $e->getMessage();
  217.             } else {
  218.                 $errorMessage .= 'Veuillez contacter le support si le problème persiste.';
  219.             }
  220.             
  221.             return $this->render('security/DemandePassword.html.twig', [
  222.                 'error' => $errorMessage
  223.             ]);
  224.         }
  225.     }
  226.     /**
  227.      * @Route("/Parent/request_password_Parent",name="request_passwordParent")
  228.      */
  229.     function request_password_parent(Request $request)
  230.     {
  231.         $mail $request->get('code');
  232.         $user $this->em->getRepository(User::class)->findOneBy(['email' => $mail]);
  233.         if ($user == null) {
  234.             return $this->render('security/UsernotFound.html.twig');
  235.         } else {
  236.             $encript hash("sha256"$user->getUsername() . $user->getId());
  237.             $url_newPass $this->generateUrl('directloginOM_tokenv2', array("token" => str_replace("."" "$user->getEmail()), 'userHash' => $encript), UrlGeneratorInterface::ABSOLUTE_URL);
  238.             $USerService $this->userService;
  239.             $USerService->sendPasswordMail($user->getEmail(), $url_newPass);
  240.             // dd($USerService->sendPasswordMail($user->getEmail(),$url_newPass));
  241.             //dd($user->getEmail().' '.$url_newPass);
  242.             return $this->render('security/DemandePasswordValide.html.twig');
  243.         }
  244.     }
  245.     /**
  246.      * @Route("/Partenaire/request_password_Partenaire",name="request_password_parentenaire")
  247.      */
  248.     function request_password_parentenaire(Request $request)
  249.     {
  250.         ini_set("max_execution_time", -1);
  251.         ini_set('memory_limit''-1');
  252.         $mail $request->get('code');
  253.         $user $this->em->getRepository(User::class)->findOneBy(['email' => $mail]);
  254.         if ($user == null) {
  255.             return $this->render('security/UsernotFound.html.twig');
  256.         } else {
  257.             $encript hash("sha256"$user->getUsername() . $user->getId());
  258.             $url_newPass $this->generateUrl('directloginOM_tokenv3', array("token" => str_replace("."" "$user->getEmail()), 'userHash' => $encript), UrlGeneratorInterface::ABSOLUTE_URL);
  259.             $USerService $this->userService;
  260.             $USerService->sendPasswordMail($user->getEmail(), $url_newPass);
  261.             // dd($USerService->sendPasswordMail($user->getEmail(),$url_newPass));
  262.             //dd($user->getEmail().' '.$url_newPass);
  263.             return $this->render('security/DemandePasswordValide.html.twig');
  264.         }
  265.     }
  266.     /**
  267.      * @Route("/directloginOM_tokenv2/{token}/{userHash}",name="directloginOM_tokenv2")
  268.      */
  269.     function directloginOM_tokenv2($token$userHash)
  270.     {
  271.         $token str_replace(" ""."$token);
  272.         $user $this->getDoctrine()
  273.             ->getRepository(User::class)->findOneBy(array('email' => $token));
  274.         if ((hash("sha256"$user->getUsername() . $user->getId()) == $userHash)) {
  275.             return $this->render('security/DemandePasswordParentv.html.twig', ["userToSetPassword" => $user]);
  276.         } else {
  277.             return $this->redirectToRoute("app_back_Parent");
  278.         }
  279.     }
  280.     /**
  281.      * @Route("/directloginOM_token/{token}/{userHash}",name="directloginOM_token")
  282.      */
  283.     function directloginOM($token$userHash)
  284.     {
  285.         try {
  286.             $token str_replace(" ""."$token);
  287.             $user $this->em->getRepository(User::class)->findOneBy(array('email' => $token));
  288.             
  289.             if ($user == null) {
  290.                 error_log("Utilisateur non trouvé pour le token: " $token);
  291.                 return $this->redirectToRoute("app_back_Acommpa");
  292.             }
  293.             
  294.             $expectedHash hash("sha256"$user->getUsername() . $user->getId());
  295.             
  296.             if ($expectedHash !== $userHash) {
  297.                 error_log("Hash invalide pour l'utilisateur: " $user->getEmail());
  298.                 return $this->redirectToRoute("app_back_Acommpa");
  299.             }
  300.             
  301.             return $this->render('security/NewPassword.html.twig', ["userToSetPassword" => $user]);
  302.         } catch (\Exception $e) {
  303.             error_log("Erreur dans directloginOM: " $e->getMessage());
  304.             error_log("Stack trace: " $e->getTraceAsString());
  305.             return $this->redirectToRoute("app_back_Acommpa");
  306.         }
  307.     }
  308.     /**
  309.      * @Route("/Parent/login", name="app_back_Parent")
  310.      */
  311.     public function Parentlogin(AuthenticationUtils $authenticationUtils): Response
  312.     {
  313.         if ($this->getUser()) {
  314.             $this->redirectToRoute('layoutAccueil');
  315.         }
  316.         // get the login error if there is one
  317.         $error $authenticationUtils->getLastAuthenticationError();
  318.         // last username entered by the user
  319.         $lastUsername $authenticationUtils->getLastUsername();
  320.         //name of twing of loging
  321.         return $this->render('Parent/LoginParent.html.twig', ['last_username' => $lastUsername'error' => $error]);
  322.     }
  323.     /**
  324.      * @Route("/Partenaire/login", name="app_login_back_Partenaire")
  325.      */
  326.     public function loginpartenair(AuthenticationUtils $authenticationUtils): Response
  327.     {
  328.         // get the login error if there is one
  329.         $error $authenticationUtils->getLastAuthenticationError();
  330.         // last username entered by the user
  331.         $lastUsername $authenticationUtils->getLastUsername();
  332.         return $this->render('partenaire/authentification.html.twig', [
  333.             'last_username' => $lastUsername,
  334.             'error' => $error
  335.         ]);
  336.     }
  337.     /**
  338.      * @Route("/directloginOM_tokenv3/{token}/{userHash}",name="directloginOM_tokenv3")
  339.      */
  340.     function directloginOM_tokenv3($token$userHash)
  341.     {
  342.         $token str_replace(" ""."$token);
  343.         $user $this->getDoctrine()
  344.             ->getRepository(User::class)->findOneBy(array('email' => $token));
  345.         //               dd($user);
  346.         if ((hash("sha256"$user->getUsername() . $user->getId()) == $userHash)) {
  347.             return $this->render('security/DemandePasswordvpartenaire.html.twig', ["userToSetPassword" => $user]);
  348.         } else {
  349.             return $this->redirectToRoute("app_login_back_Partenaire");
  350.         }
  351.     }
  352.     /**
  353.      * @Route("/forgotPasspatenaire",name="patenaireforget")
  354.      */
  355.     function forgot_Password3()
  356.     {
  357.         return $this->render('security/DemandePasswordPartenaire.html.twig');
  358.     }
  359.     #[Route('/Parent/login_check'name'login_check')]
  360.     public function check(): never
  361.     {
  362.         throw new \LogicException('This code should never be reached');
  363.     }
  364.     
  365. /*     public function mailTesterAction(Request $request)
  366.     {
  367.         
  368.         $user = $this->getUser();
  369.         $sendTo = 'test@gmail.com';
  370.         $loginUrl = $this->emailsCmdService->requestLoginLink($user);
  371.         $extra = [
  372.             "identifiant" => $sendTo,
  373.             "senduser" => $user,
  374.             "roles" => $user->getRoles(),
  375.             "nom" => $user->getNom(),
  376.             "prenom" => $user->getPrenom(),
  377.             "loginLink" => $loginUrl
  378.         ];
  379.         $this->emailsCmdService->sendMail(
  380.             $sendTo, 
  381.             'Immortalisez les souvenirs inoubliables du séjour de votre enfant !', 
  382.             'Album_Sej_Notif',
  383.             $extra
  384.         );
  385.     } */
  386. }