src/Controller/SecurityController.php line 122

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Notification\ContactNotification;
  5. use App\Utils\FormValidator;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  13. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  14. use Symfony\Component\Security\Core\User\UserInterface;
  15. use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
  16. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  17. class SecurityController extends AbstractController
  18. {
  19.     #[Route(path'/'name'homepage')]
  20.     public function home()
  21.     {
  22.         return $this->render('security/homepage.html.twig', []);
  23.     }
  24.     #[Route(path'/login/{message}/{sendTokenActiveAccount}'name'app_login')]
  25.     public function login(AuthenticationUtils $authenticationUtilsstring $message nullbool $sendTokenActiveAccount false): Response
  26.     {
  27.         // if ($this->getUser()) {
  28.         //     return $this->redirectToRoute('target_path');
  29.         // }
  30.         if ($message) {
  31.             $this->addFlash('info'$message);
  32.         }
  33.         // get the login error if there is one
  34.         $error $authenticationUtils->getLastAuthenticationError();
  35.         // last username entered by the user
  36.         $lastUsername $authenticationUtils->getLastUsername();
  37.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error'sendTokenActiveAccount' => $sendTokenActiveAccount]);
  38.     }
  39.     #[Route(path'/logout/{message}/{sendTokenActiveAccount}'name'app_logout')]
  40.     public function logout(string $message nullbool $sendTokenActiveAccount false): Response
  41.     {
  42.         return $this->redirectToRoute('app_login', ['message' => $message'sendTokenActiveAccount' => $sendTokenActiveAccount]);
  43.     }
  44.     #[Route(path'/register/{accountUrl}'name'app_register')]
  45.     public function register(
  46.         Request                     $request,
  47.         UserPasswordHasherInterface $passwordHasher,
  48.         TokenGeneratorInterface     $tokenGenerator,
  49.         ContactNotification         $contactNotification,
  50.         FormValidator               $formValidator,
  51.         EntityManagerInterface      $entityManager,
  52.         string                      $accountUrl
  53.     ): Response
  54.     {
  55.         if ($request->isMethod('POST')) {
  56.             if ($this->isCsrfTokenValid('register'$request->get('_token'))) {
  57.                 $email $request->request->get('email');
  58.                 $password $request->request->get('password');
  59.                 $account $request->request->get('account');
  60.                 $emailIsUnique $formValidator->isEmailUnique($email);
  61.                 $passwordIsSecure $formValidator->isSecurePassword($password);
  62.                 if (!$emailIsUnique) {
  63.                     $this->addFlash('danger'"Cette adresse email est déjà utilisée.");
  64.                 }
  65.                 if (!$passwordIsSecure) {
  66.                     $this->addFlash('danger'"Le mot de passe n'est pas suffisamment fort.");
  67.                 }
  68.                 //si l'email fournit est bien unique et si le mot de passe est sécurisé
  69.                 if ($emailIsUnique && $passwordIsSecure) {
  70.                     $token $tokenGenerator->generateToken(); //création du token pour activer le compte
  71.                     $user = new User();
  72.                     //si l'utilisateur s'inscrit en tant que facturier
  73.                     if ($account === 'facturier') {
  74.                         $user->setRoles([User::ROLE_FACTURIER]);
  75.                     } else {
  76.                         $user->setRoles([User::ROLE_PROFESSIONAL]);
  77.                     }
  78.                     $user->setPassword($passwordHasher->hashPassword($user$password));
  79.                     $user->setEmail($email);
  80.                     $user->setIsProfessional(1);
  81.                     $user->setActive(0);
  82.                     $user->setNameUser($request->request->get('email'));
  83.                     $user->setResetToken($token);
  84.                     $entityManager->persist($user);
  85.                     $entityManager->flush();
  86.                     $url $this->generateUrl('app_active_account', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  87.                     $contactNotification->sendTokenActiveAccountByEmail($url$email);
  88.                     $this->addFlash('info''Enregistrement réalisé avec succès ! Vous devez activer votre compte via le lien que vous allez recevoir par mail avant de pouvoir vous connectez.');
  89.                     return $this->redirectToRoute('app_login');
  90.                 }
  91.             }
  92.         }
  93.         return $this->render('security/register.html.twig', ['accountUrl' => $accountUrl]);
  94.     }
  95.     #[Route(path'/forgotten_password'name'app_forgotten_password')]
  96.     public function forgottenPassword(
  97.         Request                 $request,
  98.         TokenGeneratorInterface $tokenGenerator,
  99.         ContactNotification     $contactNotification,
  100.         EntityManagerInterface  $entityManager
  101.     ): Response
  102.     {
  103.         if ($request->isMethod('POST')) {
  104.             $email $request->request->get('email');
  105.             $user $entityManager->getRepository(User::class)->findOneByEmail($email);
  106.             /* @var $user User */
  107.             if ($user === null) {
  108.                 $this->addFlash('danger''Email Inconnu');
  109.                 return $this->redirectToRoute('app_forgotten_password');
  110.             }
  111.             $token $tokenGenerator->generateToken();
  112.             try {
  113.                 $user->setResetToken($token);
  114.                 $user->setUpdatedAt(new \DateTime('now'));
  115.                 $entityManager->flush();
  116.             } catch (\Exception $e) {
  117.                 $this->addFlash('warning'$e->getMessage());
  118.                 return $this->redirectToRoute('app_forgotten_password');
  119.             }
  120.             $url $this->generateUrl('app_reset_password', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  121.             $contactNotification->sendTokenPasswordByEmail($url$user->getEmail());
  122.             $this->addFlash('info''Mail envoyé.');
  123.             return $this->redirectToRoute('app_login');
  124.         }
  125.         return $this->render('security/forgotten_password.html.twig');
  126.     }
  127.     #[Route(path'/reset_password/{token}'name'app_reset_password')]
  128.     public function resetPassword(Request $requeststring $tokenUserPasswordHasherInterface $passwordHasherFormValidator $formValidatorEntityManagerInterface $entityManager)
  129.     {
  130.         if ($request->isMethod('POST')) {
  131.             $user $entityManager->getRepository(User::class)->findOneByResetToken($token);
  132.             /* @var $user User */
  133.             if ($user === null) {
  134.                 $this->addFlash('danger''Token Inconnu');
  135.                 return $this->redirectToRoute('app_forgotten_password');
  136.             }
  137.             $passwordIsSecure $formValidator->isSecurePassword($request->request->get('password'));
  138.             if (!$passwordIsSecure) {
  139.                 $this->addFlash('danger'"Le mot de passe n'est pas suffisamment fort.");
  140.                 return $this->render('security/reset_password.html.twig', ['token' => $token]);
  141.             }
  142.             $user->setResetToken('');
  143.             $user->setPassword($passwordHasher->hashPassword($user$request->request->get('password')));
  144.             $user->setUpdatedAt(new \DateTime('now'));
  145.             $entityManager->flush();
  146.             $this->addFlash('info''Mot de passe mis à jour');
  147.             return $this->redirectToRoute('app_login');
  148.         } else {
  149.             return $this->render('security/reset_password.html.twig', ['token' => $token]);
  150.         }
  151.     }
  152.     #[Route(path'/changePassword'name'app_change_password')]
  153.     public function changePassword(Request $requestUserPasswordHasherInterface $passwordHasher, ?UserInterface $userFormValidator $formValidatorEntityManagerInterface $entityManager)
  154.     {
  155.         if (!$user) {
  156.             return $this->redirectToRoute('app_login');
  157.         }
  158.         if ($user->getIsFirstConnexion() && $user->getIsProfessional() == 0) { //si c'est la première connexion d'un patient
  159.             $this->addFlash('info'"Bonjour, pour une question de sécurité, nous vous invitons à choisir et modifier votre mot de passe.");
  160.         }
  161.         if ($request->isMethod('POST') && $this->isCsrfTokenValid('change_password'$request->request->get('_token'))) {
  162.             $oldPassword $request->request->get('_old_password');
  163.             $password $request->request->get('_password');
  164.             $confirmPassword $request->request->get('_confirm_password');
  165.             // Si l'ancien mot de passe est bon
  166.             if ($passwordHasher->isPasswordValid($user$oldPassword)) {
  167.                 if ($password === $confirmPassword) {
  168.                     $passwordIsSecure $formValidator->isSecurePassword($password);
  169.                     if (!$passwordIsSecure) {
  170.                         $this->addFlash('danger'"Le mot de passe n'est pas suffisamment fort.");
  171.                         return $this->render('security/change_password.html.twig');
  172.                     }
  173.                     if ($user->getIsFirstConnexion()) { //si c'est la première connexion de l'utilisater
  174.                         $user->setIsFirstConnexion(0);
  175.                     }
  176.                     $user->setPassword($passwordHasher->hashPassword($user$password));
  177.                     $user->setUpdatedAt(new \DateTime('now'));
  178.                     $entityManager->persist($user);
  179.                     $entityManager->flush();
  180.                     $this->addFlash('info''Votre mot de passe a bien été changé !');
  181.                     return $this->redirectToRoute('profil');
  182.                 } else {
  183.                     $this->addFlash('danger'"Les mots de passes ne sont pas identiques.");
  184.                     return $this->render('security/change_password.html.twig');
  185.                 }
  186.             } else {
  187.                 $this->addFlash('danger'"Ce n'est pas le bon mot de passe.");
  188.                 return $this->render('security/change_password.html.twig');
  189.             }
  190.         }
  191.         return $this->render('security/change_password.html.twig', array());
  192.     }
  193.     #[Route(path'/active-account/{token}'name'app_active_account')]
  194.     public function activeAccount(string $tokenEntityManagerInterface $entityManager)
  195.     {
  196.         $user $entityManager->getRepository(User::class)->findOneByResetToken($token);
  197.         if ($user === null) {
  198.             $this->addFlash('danger''Token Inconnu');
  199.             return $this->redirectToRoute('app_logout');
  200.         }
  201.         $user->setResetToken('');
  202.         $user->setUpdatedAt(new \DateTime('now'));
  203.         $user->setActive(1);
  204.         $entityManager->flush();
  205.         $this->addFlash('info''Votre compte est maintenant actif ! Il ne vous reste plus qu\'à vous connecter.');
  206.         return $this->redirectToRoute('app_login');
  207.     }
  208.     #[Route(path'/send/active-account'name'app_send_active_account')]
  209.     public function sendActiveAccount(Request $requestTokenGeneratorInterface $tokenGeneratorContactNotification $contactNotificationEntityManagerInterface $entityManager)
  210.     {
  211.         if ($request->isMethod('POST')) {
  212.             $email $request->request->get('email');
  213.             $user $entityManager->getRepository(User::class)->findOneByEmail($email);
  214.             if ($user === null) {
  215.                 $this->addFlash('danger''Email Inconnu');
  216.                 return $this->redirectToRoute('app_send_active_account');
  217.             }
  218.             $token $tokenGenerator->generateToken();
  219.             try {
  220.                 $user->setResetToken($token);
  221.                 $user->setUpdatedAt(new \DateTime('now'));
  222.                 $entityManager->flush();
  223.             } catch (\Exception $e) {
  224.                 $this->addFlash('warning'$e->getMessage());
  225.                 return $this->redirectToRoute('app_send_active_account');
  226.             }
  227.             $url $this->generateUrl('app_active_account', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  228.             $contactNotification->sendTokenActiveAccountByEmail($url$email);
  229.             return $this->redirectToRoute('app_login', ['message' => 'Mail pour activer votre compte envoyé.''sendTokenActiveAccount' => true]);
  230.         }
  231.         return $this->render('security/send_active_account.html.twig');
  232.     }
  233. }