src/Service/Security/LoginFormAuthenticator.php line 121

Open in your IDE?
  1. <?php
  2. namespace App\Service\Security;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  12. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  13. use Symfony\Component\Security\Core\Security;
  14. use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
  15. use Symfony\Component\Security\Core\User\UserProviderInterface;
  16. use Symfony\Component\Security\Csrf\CsrfToken;
  17. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  18. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  19. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  20. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  21. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  22. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  23. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  24. class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
  25. {
  26.     use TargetPathTrait;
  27.     public const LOGIN_ROUTE 'app_login';
  28.     private $entityManager;
  29.     private $urlGenerator;
  30.     private $csrfTokenManager;
  31.     private $passwordEncoder;
  32.     public function __construct(
  33.         EntityManagerInterface $entityManager,
  34.         UrlGeneratorInterface $urlGenerator,
  35.         CsrfTokenManagerInterface $csrfTokenManager,
  36.         UserPasswordHasherInterface $passwordEncoder
  37.     ) {
  38.         $this->entityManager $entityManager;
  39.         $this->urlGenerator $urlGenerator;
  40.         $this->csrfTokenManager $csrfTokenManager;
  41.         $this->passwordEncoder $passwordEncoder;
  42.     }
  43.     public function supports(Request $request): bool
  44.     {
  45.         return self::LOGIN_ROUTE === $request->attributes->get('_route')
  46.             && $request->isMethod('POST');
  47.     }
  48.     public function getCredentials(Request $request)
  49.     {
  50.         $credentials = [
  51.             'username' => $request->request->get('username'),
  52.             'password' => $request->request->get('password'),
  53.             'csrf_token' => $request->request->get('_csrf_token'),
  54.         ];
  55.         $request->getSession()->set(
  56.             Security::LAST_USERNAME,
  57.             $credentials['username']
  58.         );
  59.         return $credentials;
  60.     }
  61.     public function getUser($credentials)
  62.     {
  63.         $token = new CsrfToken('authenticate'$credentials['csrf_token']);
  64.         if (!$this->csrfTokenManager->isTokenValid($token)) {
  65.             throw new InvalidCsrfTokenException();
  66.         }
  67.         $user $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);
  68.         if (!$user) {
  69.             // fail authentication with a custom error
  70.             throw new CustomUserMessageAuthenticationException('Username could not be found.');
  71.         }
  72.         return $user;
  73.     }
  74.     public function checkUserIsActive($credentials): bool
  75.     {
  76.         if (!$this->getUser($credentials)->getActive()) {
  77.             throw new CustomUserMessageAuthenticationException('Username could not be found.');
  78.         }
  79.         return true;
  80.     }
  81.     public function checkCredentials($credentialsPasswordAuthenticatedUserInterface $user): bool
  82.     {
  83.         if (!$user->getActive()) {
  84.             return false;
  85.         }
  86.         return $this->passwordEncoder->isPasswordValid($user$credentials['password']);
  87.     }
  88.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $providerKey): ?Response
  89.     {
  90.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  91.             return new RedirectResponse($targetPath);
  92.         }
  93.         return new RedirectResponse($this->urlGenerator->generate('dashboard'));
  94.     }
  95.     protected function getLoginUrl(Request $request): string
  96.     {
  97.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  98.     }
  99.     public function authenticate(Request $request): Passport
  100.     {
  101.         $credentials $this->getCredentials($request);
  102.         if ($this->checkUserIsActive($credentials)) {
  103.             return new Passport(
  104.                 new UserBadge($credentials['username']),
  105.                 new PasswordCredentials($credentials['password']),
  106.                 [new CsrfTokenBadge('authenticate'$credentials['csrf_token'])]
  107.             );
  108.         }
  109.     }
  110. }