src/Controller/SecurityController.php line 46

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Repository\UserRepository;
  5. use App\Service\Notification\EmailNotificationService;
  6. use Doctrine\DBAL\Connection;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  14. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  15. class SecurityController extends AbstractController
  16. {
  17.     /**
  18.      * @Route("/connexion", name="app_login")
  19.      */
  20.     public function login(AuthenticationUtils $authenticationUtils): Response
  21.     {
  22.         if ($this->getUser()) {
  23.             return $this->redirectToRoute('app_dashboard');
  24.         }
  25.         return $this->render('security/login.html.twig', [
  26.             'last_username' => $authenticationUtils->getLastUsername(),
  27.             'error' => $authenticationUtils->getLastAuthenticationError(),
  28.         ]);
  29.     }
  30.     /**
  31.      * @Route("/deconnexion", name="app_logout")
  32.      */
  33.     public function logout(): void
  34.     {
  35.         throw new \LogicException('Symfony intercepte cette route via le firewall.');
  36.     }
  37.     /**
  38.      * @Route("/mot-de-passe-oublie", name="app_forgot_password")
  39.      */
  40.     public function forgotPassword(
  41.         Request $request,
  42.         UserRepository $users,
  43.         EntityManagerInterface $em,
  44.         EmailNotificationService $emailNotifications,
  45.         Connection $connection
  46.     ): Response {
  47.         $resetLink = null;
  48.         $submittedEmail = '';
  49.         if ($request->isMethod('POST') && $this->isCsrfTokenValid('forgot-password', (string) $request->request->get('_token'))) {
  50.             $submittedEmail = mb_strtolower(trim((string) $request->request->get('email')));
  51.             if (!filter_var($submittedEmail, FILTER_VALIDATE_EMAIL)) {
  52.                 $this->addFlash('error', 'Adresse e-mail invalide.');
  53.             } else {
  54.                 $user = $users->findOneBy(['email' => $submittedEmail]);
  55.                 if ($user instanceof User) {
  56.                     $token = bin2hex(random_bytes(32));
  57.                     $user->setResetToken($token);
  58.                     $em->flush();
  59.                     $generatedResetLink = $this->generateUrl(
  60.                         'app_reset_password',
  61.                         ['token' => $token],
  62.                         UrlGeneratorInterface::ABSOLUTE_URL
  63.                     );
  64.                     $subject = 'Reinitialisation de votre mot de passe';
  65.                     $content = sprintf(
  66.                         "Bonjour %s,\n\nUne demande de reinitialisation de mot de passe a ete recue pour votre compte.\n\nUtilisez ce lien pour choisir un nouveau mot de passe :\n%s\n\nSi vous n'etes pas a l'origine de cette demande, ignorez ce message.",
  67.                         $user->getFullName() ?: $user->getEmail(),
  68.                         $generatedResetLink
  69.                     );
  70.                     $status = 'en_attente';
  71.                     $error = null;
  72.                     try {
  73.                         $status = $emailNotifications->send((string) $user->getEmail(), $subject, $content, $user->getAgencyId());
  74.                         if ($status === EmailNotificationService::STATUS_LOGGED) {
  75.                             $resetLink = $generatedResetLink;
  76.                         }
  77.                     } catch (\Throwable $exception) {
  78.                         $status = 'echec';
  79.                         $error = $exception->getMessage();
  80.                     }
  81.                     $this->logPasswordResetEmail($connection, $submittedEmail, $subject, $content, $status, $error);
  82.                     if ($error !== null) {
  83.                         $this->addFlash('error', 'Le lien de reinitialisation a ete cree, mais l\'e-mail n a pas pu etre envoye. Verifiez la configuration e-mail.');
  84.                     } else {
  85.                         $this->addFlash('success', 'Si ce compte existe, une procedure de reinitialisation a ete preparee.');
  86.                     }
  87.                 } else {
  88.                     $this->addFlash('success', 'Si ce compte existe, une procedure de reinitialisation a ete preparee.');
  89.                 }
  90.             }
  91.         }
  92.         return $this->render('security/forgot_password.html.twig', [
  93.             'reset_link' => $resetLink,
  94.             'submitted_email' => $submittedEmail,
  95.         ]);
  96.     }
  97.     /**
  98.      * @Route("/mot-de-passe/reinitialiser/{token}", name="app_reset_password")
  99.      */
  100.     public function resetPassword(
  101.         string $token,
  102.         Request $request,
  103.         UserRepository $users,
  104.         EntityManagerInterface $em,
  105.         UserPasswordHasherInterface $hasher
  106.     ): Response {
  107.         $user = $users->findOneBy(['resetToken' => $token]);
  108.         if (!$user instanceof User) {
  109.             throw $this->createNotFoundException('Lien de réinitialisation invalide.');
  110.         }
  111.         if ($request->isMethod('POST') && $this->isCsrfTokenValid('reset-password', (string) $request->request->get('_token'))) {
  112.             $password = (string) $request->request->get('password');
  113.             if (strlen($password) < 8) {
  114.                 $this->addFlash('error', 'Le mot de passe doit contenir au moins 8 caractères.');
  115.             } else {
  116.                 $user->setPassword($hasher->hashPassword($user, $password));
  117.                 $user->setResetToken(null);
  118.                 $user->setIsActive(true);
  119.                 $em->flush();
  120.                 $this->addFlash('success', 'Mot de passe mis à jour. Vous pouvez vous connecter.');
  121.                 return $this->redirectToRoute('app_login');
  122.             }
  123.         }
  124.         return $this->render('security/reset_password.html.twig');
  125.     }
  126.     /**
  127.      * @Route("/activation/{token}", name="app_activate_account")
  128.      */
  129.     public function activate(
  130.         string $token,
  131.         Request $request,
  132.         UserRepository $users,
  133.         EntityManagerInterface $em,
  134.         UserPasswordHasherInterface $hasher
  135.     ): Response {
  136.         $user = $users->findOneBy(['activationToken' => $token]);
  137.         if (!$user instanceof User) {
  138.             throw $this->createNotFoundException('Lien d’activation invalide.');
  139.         }
  140.         if ($request->isMethod('POST') && $this->isCsrfTokenValid('activate-account', (string) $request->request->get('_token'))) {
  141.             $password = (string) $request->request->get('password');
  142.             if (strlen($password) < 8) {
  143.                 $this->addFlash('error', 'Le mot de passe doit contenir au moins 8 caractères.');
  144.             } else {
  145.                 $user->setPassword($hasher->hashPassword($user, $password));
  146.                 $user->setActivationToken(null);
  147.                 $user->setIsActive(true);
  148.                 $em->flush();
  149.                 $this->addFlash('success', 'Compte activé. Vous pouvez vous connecter.');
  150.                 return $this->redirectToRoute('app_login');
  151.             }
  152.         }
  153.         return $this->render('security/activate.html.twig', ['user' => $user]);
  154.     }
  155.     /**
  156.      * @Route("/mot-de-passe/changer", name="app_change_password")
  157.      */
  158.     public function changePassword(Request $request, EntityManagerInterface $em, UserPasswordHasherInterface $hasher): Response
  159.     {
  160.         $user = $this->getUser();
  161.         if (!$user instanceof User) {
  162.             return $this->redirectToRoute('app_login');
  163.         }
  164.         if ($request->isMethod('POST') && $this->isCsrfTokenValid('change-password', (string) $request->request->get('_token'))) {
  165.             $password = (string) $request->request->get('password');
  166.             if (strlen($password) < 8) {
  167.                 $this->addFlash('error', 'Le mot de passe doit contenir au moins 8 caractères.');
  168.             } else {
  169.                 $user->setPassword($hasher->hashPassword($user, $password));
  170.                 $em->flush();
  171.                 $this->addFlash('success', 'Mot de passe modifié.');
  172.             }
  173.         }
  174.         return $this->render('security/change_password.html.twig');
  175.     }
  176.     private function logPasswordResetEmail(
  177.         Connection $connection,
  178.         string $recipient,
  179.         string $subject,
  180.         string $content,
  181.         string $status,
  182.         ?string $error
  183.     ): void {
  184.         $connection->insert('notification_log', [
  185.             'recipient' => $recipient,
  186.             'channel' => 'email',
  187.             'subject' => $subject,
  188.             'content' => $content,
  189.             'status' => $status,
  190.             'error_message' => $error,
  191.             'sent_at' => $this->now(),
  192.         ]);
  193.     }
  194.     private function now(): string
  195.     {
  196.         return (new \DateTimeImmutable('now', new \DateTimeZone('Africa/Abidjan')))->format('Y-m-d H:i:s');
  197.     }
  198.     /**
  199.      * @Route("/espace", name="app_dashboard")
  200.      */
  201.     public function dashboardRedirect(): Response
  202.     {
  203.         $this->denyAccessUnlessGranted('ROLE_USER');
  204.         if ($this->isGranted('ROLE_CLIENT')) {
  205.             return $this->redirectToRoute('client_dashboard');
  206.         }
  207.         return $this->redirectToRoute('admin_dashboard');
  208.     }
  209. }