src/Security/FormAuthenticator.php line 70

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Consultant;
  4. use App\Entity\Jeu;
  5. use App\Entity\Session;
  6. use App\Entity\User;
  7. use App\Entity\Candidat;
  8. use App\Repository\CandidatRepository;
  9. use App\Service\Commun\Utils;
  10. use Doctrine\Common\Util\ClassUtils;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\RateLimiter\RateLimiterFactory;
  16. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  17. use Symfony\Component\Routing\RouterInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  20. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  21. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Security\Core\User\UserInterface;
  24. use Symfony\Component\Security\Core\User\UserProviderInterface;
  25. use Symfony\Component\Security\Csrf\CsrfToken;
  26. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  27. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  28. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  29. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  30. use Symfony\Contracts\Translation\TranslatorInterface;
  31. use Symfony\Component\Translation\Translator;
  32. class FormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  33. {
  34.     use TargetPathTrait;
  35.     const USERNAME 'username';
  36.     const PASS 'password';
  37.     private $entityManager;
  38.     private $router;
  39.     private $csrfTokenManager;
  40.     private $passwordEncoder;
  41.     private $security;
  42.     private $params;
  43.     private $translator;
  44.     private $user;
  45.     private $loginLimiterUsername;
  46.     private $loginLimiterIp;
  47. //    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface  $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder, ParameterBagInterface $params, TranslatorInterface $translator)
  48. //    {
  49. //        $this->entityManager = $entityManager;
  50. //        $this->urlGenerator = $urlGenerator;
  51. //        $this->csrfTokenManager = $csrfTokenManager;
  52. //        $this->passwordEncoder = $passwordEncoder;
  53. //
  54. //                $this->params = $params;
  55. //        $this->translator = $translator;
  56. //    }
  57.     public function __construct(EntityManagerInterface $managerRouterInterface $routerCsrfTokenManagerInterface $csrfTokenManagerUserPasswordHasherInterface $passwordEncoderSecurity $securityParameterBagInterface $paramsTranslatorInterface $translatorRateLimiterFactory $loginAttemptsUsernameLimiterRateLimiterFactory $loginAttemptsIpLimiter)
  58.     {
  59.         $this->manager $manager;
  60.         $this->router $router;
  61.         $this->csrfTokenManager $csrfTokenManager;
  62.         $this->passwordEncoder $passwordEncoder;
  63.         $this->security $security;
  64.         $this->params $params;
  65.         $this->translator $translator;
  66.         $this->loginLimiterUsername $loginAttemptsUsernameLimiter;
  67.         $this->loginLimiterIp $loginAttemptsIpLimiter;
  68.     }
  69.     public function supports(Request $request)
  70.     {
  71.         return 'security_login' === $request->attributes->get('_route')
  72.             && $request->isMethod('POST');
  73.     }
  74.     public function getCredentials(Request $request)
  75.     {
  76.         $credentials = [
  77.             FormAuthenticator::USERNAME => $request->request->get(FormAuthenticator::USERNAME),
  78.             FormAuthenticator::PASS => $request->request->get(FormAuthenticator::PASS),
  79.             'csrf_token' => $request->request->get('_csrf_token'),
  80.         ];
  81.         $request->getSession()->set(
  82.             Security::LAST_USERNAME,
  83.             $credentials[FormAuthenticator::USERNAME]
  84.         );
  85.         return $credentials;
  86.     }
  87.     public function getUser($credentialsUserProviderInterface $userProvider)
  88.     {
  89.         $usernameLimiter $this->loginLimiterUsername->create($credentials[self::USERNAME]);
  90.         $ipLimiter $this->loginLimiterIp->create($_SERVER['REMOTE_ADDR'] ?? 'unknown_ip');
  91.         $usernameLimit $usernameLimiter->consume(1);
  92.         $ipLimit $ipLimiter->consume(1);
  93.         if (!$usernameLimit->isAccepted() || !$ipLimit->isAccepted()) {
  94.             throw new CustomUserMessageAuthenticationException(
  95.                 $this->translator->trans('error.too_many_attempts')
  96.             );
  97.         }
  98.         $token = new CsrfToken('authenticate'$credentials['csrf_token']);
  99.         if (!$this->csrfTokenManager->isTokenValid($token)) {
  100.             throw new InvalidCsrfTokenException();
  101.         }
  102. //        die;
  103.         /** @var User $user */
  104.         $user $this->manager->getRepository(User::class)->findOneBy([FormAuthenticator::USERNAME => $credentials[FormAuthenticator::USERNAME]]);
  105.         if (!$user) {
  106.             // fail authentication with a custom error
  107.             throw new CustomUserMessageAuthenticationException($this->translator->trans('error.identifiant_introuvable'));
  108.         }
  109.         $roles $user->getRoles();
  110.         if (!$user->getIsActive()) {
  111.             throw new CustomUserMessageAuthenticationException($this->translator->trans('error.disable_account'));
  112.         }
  113.         if (!in_array('ROLE_ADMIN'$rolestrue) && !in_array('ROLE_CONSULTANT'$rolestrue) && !in_array('ROLE_PMO'$rolestrue)) {
  114.             /** @var Session $session */
  115.             //TODO: Verifier si le jeu est OK.
  116.             /*$candidat = $this->manager->getRepository(Candidat::class)->find($user->getId());
  117.             $jeu = $candidat->getProject()->getJeu();
  118.             if ($jeu->getSocietes()->count() === 0 || $jeu->getCorrespondantsCounter() === 0 || $jeu->isValid() === false || $jeu->getEmailModeles()->count() === 0) {
  119.                 throw new CustomUserMessageAuthenticationException($this->translator->trans('error.jeu_incomplet'));
  120.             }*/
  121.             $session $user->getSession();
  122.             if (!$session) {
  123.                 throw new CustomUserMessageAuthenticationException($this->translator->trans('error.non_inscrit'));
  124.             }
  125.             if ($session->getStatus() == 'CLOSE') {
  126.                 throw new CustomUserMessageAuthenticationException($this->translator->trans('error.session_cloturee'));
  127.             }
  128.             if ($session->getStatus() == 'SOON') {
  129.                 throw new CustomUserMessageAuthenticationException($this->translator->trans('error.session_non_encore_ouverte'));
  130.             }
  131.             $sessionSartTime $this->params->get('session_start_time');
  132.             $sessionCloseTime $this->params->get('session_close_time');
  133.             $sessionSartTime strtotime($sessionSartTime);
  134.             $sessionCloseTime strtotime($sessionCloseTime);
  135.             $currentDateTime = new \DateTime();
  136.             $currentTime $currentDateTime->format('H:i:s');
  137.             $currentTime strtotime($currentTime);
  138.             if ($currentTime $sessionSartTime || $currentTime >= $sessionCloseTime) {
  139.                 throw new CustomUserMessageAuthenticationException($this->translator->trans('error.session_indisponible'));
  140.             }
  141.         }
  142.         return $this->user $user;
  143.     }
  144.     public function checkCredentials($credentialsUserInterface $user)
  145.     {
  146.         return $this->passwordEncoder->isPasswordValid($user$credentials[FormAuthenticator::PASS]);
  147.     }
  148.     /**
  149.      * Used to upgrade (rehash) the user's password automatically over time.
  150.      */
  151.     public function getPassword($credentials): ?string
  152.     {
  153.         return $credentials['password'];
  154.     }
  155.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  156.     {
  157.         // RĂ©initialiser le compteur du limiter
  158.         $usernameLimiter $this->loginLimiterUsername->create($this->user->getUsername());
  159.         $ipLimiter $this->loginLimiterIp->create($request->getClientIp());
  160.         $usernameLimiter->reset();
  161.         $ipLimiter->reset();
  162.         $currentDateTime = new \DateTime();
  163. //        dump($token->getAttributes());
  164. //        dump($request->attributes);
  165.         $this->user->eraseCredentials();
  166.         $this->user->setConnectionOrigin('form');
  167.         $this->user->setSsoPartner('');
  168.         $this->user->setDateLastConnection($currentDateTime);
  169.         $this->user->addNumberConnection();
  170.         $this->manager->flush();
  171.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  172.             return new RedirectResponse($targetPath);
  173.         }
  174.         $roles $token->getRoleNames();
  175.         if (in_array('ROLE_ADMIN'$rolestrue) || in_array('ROLE_CONSULTANT'$rolestrue) || in_array('ROLE_PMO'$rolestrue)) {
  176.             $redirection = new RedirectResponse($this->router->generate('admin_index'));
  177.         } else {
  178.             /** @var Candidat $candidat */
  179.             $candidat $this->manager->getRepository(Candidat::class)->find($this->user->getId());
  180.             $langueJeu $candidat->getProject()->getJeu()->getLangue();
  181.             $request->setLocale($langueJeu);
  182.             $redirection = new RedirectResponse($this->router->generate('mail_inbox'));
  183.         }
  184.         return $redirection;
  185.     }
  186.     protected function getLoginUrl()
  187.     {
  188.         return $this->router->generate("security_login");
  189.     }
  190. }