src/Security/FormAuthenticator.php line 66

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