src/Controller/SecurityController.php line 366

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.      * Mise à jour du mot de passe après lien de réinitialisation (Parent, Partenaire ou Accompagnateur uniquement).
  102.      */
  103.     function Create_New_Password(Request $request)
  104.     {
  105.         $password $request->get('password');
  106.         $userId $request->get('userID');
  107.         if (!$password || !$userId) {
  108.             return new Response('error'Response::HTTP_BAD_REQUEST);
  109.         }
  110.         $user $this->em->getRepository(User::class)->find($userId);
  111.         if ($user === null) {
  112.             return new Response('error'Response::HTTP_NOT_FOUND);
  113.         }
  114.         if (!$user->hasRole('ROLE_PARENT') && !$user->hasRole('ROLE_PARTENAIRE') && !$user->hasRole('ROLE_ACC')) {
  115.             return new Response('error'Response::HTTP_FORBIDDEN);
  116.         }
  117.         $this->userService->updatPassw($user->getId(), $password);
  118.         if ($user->hasRole('ROLE_PARENT') && $user->getActivatemail() === null) {
  119.             $user->setActivatemail(1);
  120.             $this->em->flush();
  121.         }
  122.         return new Response("done");
  123.     }
  124.     /**
  125.      * @Route("/changerPassword",name="changer_Password")
  126.      */
  127.     function changerPassword(Request $request)
  128.     {
  129.         $password $request->get('password');
  130.         $userId $request->get('userID');
  131.         $USerService $this->userService;
  132.         $USerService->updatPassw($userId$password);
  133.         return new response("done");
  134.     }
  135.     /**
  136.      * @Route("/Accompagnateur/request_password",name="request_password", methods={"GET", "POST"})
  137.      */
  138.     function request_password(Request $request): Response
  139.     {
  140.         try {
  141.             // Si c'est une requête GET (accès direct à la page), afficher le formulaire
  142.             if ($request->isMethod('GET')) {
  143.                 return $this->render('security/DemandePassword.html.twig');
  144.             }
  145.             
  146.             // Si c'est une requête POST (soumission du formulaire)
  147.             $code $request->request->get('code');
  148.             
  149.             // Si aucun code n'est fourni, afficher le formulaire avec un message d'erreur
  150.             if (empty($code)) {
  151.                 return $this->render('security/DemandePassword.html.twig', [
  152.                     'error' => 'Veuillez saisir votre code séjour'
  153.                 ]);
  154.             }
  155.             
  156.             $sejour $this->em->getRepository(Sejour::class)->findOneBy(['codeSejour' => $code]);
  157.             if ($sejour == null) {
  158.                 // Code séjour invalide
  159.                 return $this->render('security/DemandePassword.html.twig', [
  160.                     'error' => 'Code séjour introuvable. Veuillez vérifier votre code et réessayer.'
  161.                 ]);
  162.             }
  163.             
  164.             $user $sejour->getIdAcommp();
  165.             
  166.             if ($user == null) {
  167.                 // Aucun accompagnateur associé au séjour
  168.                 return $this->render('security/DemandePassword.html.twig', [
  169.                     'error' => 'Aucun accompagnateur trouvé pour ce séjour. Veuillez contacter le support.'
  170.                 ]);
  171.             }
  172.             
  173.             // Utiliser l'email de réponse (reponseemail) si disponible, sinon l'email principal
  174.             $emailToSend $user->getReponseemail() ?: $user->getEmail();
  175.             
  176.             // Vérifier que l'utilisateur a un email
  177.             if (empty($emailToSend)) {
  178.                 return $this->render('security/DemandePassword.html.twig', [
  179.                     'error' => 'Aucun email associé à ce compte. Veuillez contacter le support.'
  180.                 ]);
  181.             }
  182.             
  183.             // Récupérer le mot de passe non crypté et le code séjour
  184.             $password $user->getPasswordNonCripted();
  185.             $codeSejour $sejour->getCodeSejour();
  186.             
  187.             // Si le mot de passe n'est pas disponible, générer un message d'erreur
  188.             if (empty($password)) {
  189.                 return $this->render('security/DemandePassword.html.twig', [
  190.                     'error' => 'Impossible de récupérer votre mot de passe. Veuillez contacter le support.'
  191.                 ]);
  192.             }
  193.             
  194.             // Envoyer l'email à l'adresse de réponse avec le mot de passe et le code séjour
  195.             $USerService $this->userService;
  196.             
  197.             try {
  198.                 $emailSent $USerService->sendPasswordMail($emailToSend$password$codeSejour);
  199.                 
  200.                 if (!$emailSent) {
  201.                     error_log("❌ Échec envoi email réinitialisation - Email: " $emailToSend);
  202.                     return $this->render('security/DemandePassword.html.twig', [
  203.                         'error' => 'Erreur lors de l\'envoi de l\'email. Veuillez réessayer plus tard ou contacter le support à contact@5sur5sejour.com.'
  204.                     ]);
  205.                 }
  206.                 
  207.                 error_log("✅ Email de réinitialisation envoyé avec succès à: " $emailToSend);
  208.                 
  209.                 // Afficher la page de confirmation
  210.                 return $this->render('security/DemandePasswordValide.html.twig', [
  211.                     'email' => $emailToSend
  212.                 ]);
  213.             } catch (\Exception $emailException) {
  214.                 error_log("❌ Exception lors de l'envoi de l'email: " $emailException->getMessage());
  215.                 error_log("Stack trace email: " $emailException->getTraceAsString());
  216.                 return $this->render('security/DemandePassword.html.twig', [
  217.                     'error' => 'Erreur lors de l\'envoi de l\'email: ' $emailException->getMessage() . '. Veuillez contacter le support.'
  218.                 ]);
  219.             }
  220.         } catch (\Exception $e) {
  221.             error_log("❌ Erreur dans request_password: " $e->getMessage());
  222.             error_log("Fichier: " $e->getFile() . " Ligne: " $e->getLine());
  223.             error_log("Stack trace: " $e->getTraceAsString());
  224.             
  225.             // En mode dev, afficher le message d'erreur complet
  226.             $errorMessage 'Une erreur est survenue. ';
  227.             if ($this->getParameter('kernel.environment') === 'dev') {
  228.                 $errorMessage .= 'Détails: ' $e->getMessage();
  229.             } else {
  230.                 $errorMessage .= 'Veuillez contacter le support si le problème persiste.';
  231.             }
  232.             
  233.             return $this->render('security/DemandePassword.html.twig', [
  234.                 'error' => $errorMessage
  235.             ]);
  236.         }
  237.     }
  238.     /**
  239.      * @Route("/Parent/request_password_Parent",name="request_passwordParent")
  240.      */
  241.     function request_password_parent(Request $request)
  242.     {
  243.         $mail trim((string) ($request->request->get('code'$request->query->get('code'''))));
  244.         if ($mail === '') {
  245.             return $this->render('security/UsernotFound.html.twig');
  246.         }
  247.         $user $this->em->getRepository(User::class)->findOneParentByEmail($mail);
  248.         if ($user === null) {
  249.             return $this->render('security/UsernotFound.html.twig');
  250.         }
  251.         $loginIdentifiant $user->getUsername() ?? $user->getEmail();
  252.         $encript hash("sha256"$loginIdentifiant $user->getId());
  253.         $url_newPass $this->generateUrl('directloginOM_tokenv2', ['token' => str_replace('.'' '$user->getEmail()), 'userHash' => $encript], UrlGeneratorInterface::ABSOLUTE_URL);
  254.         $sent $this->userService->sendPasswordResetLinkMail($user->getEmail(), $url_newPass);
  255.         if (!$sent) {
  256.             return $this->render('security/DemandePasswordParent.html.twig', ['error' => 'L\'envoi de l\'email a échoué. Veuillez réessayer plus tard ou contacter contact@5sur5sejour.com.']);
  257.         }
  258.         return $this->render('security/DemandePasswordValide.html.twig');
  259.     }
  260.     /**
  261.      * @Route("/Partenaire/request_password_Partenaire",name="request_password_parentenaire")
  262.      */
  263.     function request_password_parentenaire(Request $request)
  264.     {
  265.         $mail trim((string) ($request->request->get('code'$request->query->get('code'''))));
  266.         if ($mail === '') {
  267.             return $this->render('security/UsernotFound.html.twig');
  268.         }
  269.         $user $this->em->getRepository(User::class)->findOneBy(['email' => $mail]);
  270.         if ($user === null) {
  271.             return $this->render('security/UsernotFound.html.twig');
  272.         }
  273.         $loginIdentifiant $user->getUsername() ?? $user->getEmail();
  274.         $encript hash("sha256"$loginIdentifiant $user->getId());
  275.         $url_newPass $this->generateUrl('directloginOM_tokenv3', ['token' => str_replace('.'' '$user->getEmail()), 'userHash' => $encript], UrlGeneratorInterface::ABSOLUTE_URL);
  276.         $sent $this->userService->sendPasswordResetLinkMail($user->getEmail(), $url_newPass);
  277.         if (!$sent) {
  278.             return $this->render('security/DemandePasswordPartenaire.html.twig', ['error' => 'L\'envoi de l\'email a échoué. Veuillez réessayer plus tard ou contacter contact@5sur5sejour.com.']);
  279.         }
  280.         return $this->render('security/DemandePasswordValide.html.twig');
  281.     }
  282.     /**
  283.      * @Route("/Parent/reinitialisation-mdp/{token}/{userHash}", name="directloginOM_tokenv2")
  284.      */
  285.     function directloginOM_tokenv2($token$userHash)
  286.     {
  287.         $token str_replace(" ""."$token);
  288.         $user $this->em->getRepository(User::class)->findOneParentByEmail($token);
  289.         if ($user === null) {
  290.             return $this->redirectToRoute("app_back_Parent");
  291.         }
  292.         $loginIdentifiant $user->getUsername() ?? $user->getEmail();
  293.         $expectedHash hash("sha256"$loginIdentifiant $user->getId());
  294.         if ($expectedHash !== $userHash) {
  295.             return $this->redirectToRoute("app_back_Parent");
  296.         }
  297.         return $this->render('security/DemandePasswordParentv.html.twig', ["userToSetPassword" => $user]);
  298.     }
  299.     /**
  300.      * @Route("/directloginOM_token/{token}/{userHash}",name="directloginOM_token")
  301.      */
  302.     function directloginOM($token$userHash)
  303.     {
  304.         try {
  305.             $token str_replace(" ""."$token);
  306.             $user $this->em->getRepository(User::class)->findOneByEmailOrderById($token);
  307.             
  308.             if ($user == null) {
  309.                 error_log("Utilisateur non trouvé pour le token: " $token);
  310.                 return $this->redirectToRoute("app_back_Acommpa");
  311.             }
  312.             
  313.             $loginIdentifiant $user->getUsername() ?? $user->getEmail();
  314.             $expectedHash hash("sha256"$loginIdentifiant $user->getId());
  315.             
  316.             if ($expectedHash !== $userHash) {
  317.                 error_log("Hash invalide pour l'utilisateur: " $user->getEmail());
  318.                 return $this->redirectToRoute("app_back_Acommpa");
  319.             }
  320.             
  321.             return $this->render('security/NewPassword.html.twig', ["userToSetPassword" => $user]);
  322.         } catch (\Exception $e) {
  323.             error_log("Erreur dans directloginOM: " $e->getMessage());
  324.             error_log("Stack trace: " $e->getTraceAsString());
  325.             return $this->redirectToRoute("app_back_Acommpa");
  326.         }
  327.     }
  328.     /**
  329.      * @Route("/Parent/login", name="app_back_Parent")
  330.      */
  331.     public function Parentlogin(AuthenticationUtils $authenticationUtils): Response
  332.     {
  333.         if ($this->getUser()) {
  334.             $this->redirectToRoute('layoutAccueil');
  335.         }
  336.         // get the login error if there is one
  337.         $error $authenticationUtils->getLastAuthenticationError();
  338.         // last username entered by the user
  339.         $lastUsername $authenticationUtils->getLastUsername();
  340.         //name of twing of loging
  341.         return $this->render('Parent/LoginParent.html.twig', ['last_username' => $lastUsername'error' => $error]);
  342.     }
  343.     /**
  344.      * @Route("/Partenaire/login", name="app_login_back_Partenaire")
  345.      */
  346.     public function loginpartenair(AuthenticationUtils $authenticationUtils): Response
  347.     {
  348.         // get the login error if there is one
  349.         $error $authenticationUtils->getLastAuthenticationError();
  350.         // last username entered by the user
  351.         $lastUsername $authenticationUtils->getLastUsername();
  352.         return $this->render('partenaire/authentification.html.twig', [
  353.             'last_username' => $lastUsername,
  354.             'error' => $error
  355.         ]);
  356.     }
  357.     /**
  358.      * @Route("/Partenaire/reinitialisation-mdp/{token}/{userHash}", name="directloginOM_tokenv3")
  359.      */
  360.     function directloginOM_tokenv3($token$userHash)
  361.     {
  362.         $token str_replace(" ""."$token);
  363.         $user $this->em->getRepository(User::class)->findOneBy(['email' => $token]);
  364.         if ($user === null) {
  365.             return $this->redirectToRoute("app_login_back_Partenaire");
  366.         }
  367.         $loginIdentifiant $user->getUsername() ?? $user->getEmail();
  368.         $expectedHash hash("sha256"$loginIdentifiant $user->getId());
  369.         if ($expectedHash !== $userHash) {
  370.             return $this->redirectToRoute("app_login_back_Partenaire");
  371.         }
  372.         return $this->render('security/DemandePasswordvpartenaire.html.twig', ["userToSetPassword" => $user]);
  373.     }
  374.     /**
  375.      * @Route("/forgotPasspatenaire",name="patenaireforget")
  376.      */
  377.     function forgot_Password3()
  378.     {
  379.         return $this->render('security/DemandePasswordPartenaire.html.twig');
  380.     }
  381.     #[Route('/Parent/login_check'name'login_check')]
  382.     public function check(): never
  383.     {
  384.         throw new \LogicException('This code should never be reached');
  385.     }
  386.     
  387. /*     public function mailTesterAction(Request $request)
  388.     {
  389.         
  390.         $user = $this->getUser();
  391.         $sendTo = 'test@gmail.com';
  392.         $loginUrl = $this->emailsCmdService->requestLoginLink($user);
  393.         $extra = [
  394.             "identifiant" => $sendTo,
  395.             "senduser" => $user,
  396.             "roles" => $user->getRoles(),
  397.             "nom" => $user->getNom(),
  398.             "prenom" => $user->getPrenom(),
  399.             "loginLink" => $loginUrl
  400.         ];
  401.         $this->emailsCmdService->sendMail(
  402.             $sendTo, 
  403.             'Immortalisez les souvenirs inoubliables du séjour de votre enfant !', 
  404.             'Album_Sej_Notif',
  405.             $extra
  406.         );
  407.     } */
  408. }