src/Security/LoginFormAuthenticator.php line 64

Open in your IDE?
  1. <?php
  2. // src/Security/LoginFormAuthenticator.php
  3. namespace App\Security;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  13. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  14. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  15. use Symfony\Component\Security\Core\Security;
  16. use Symfony\Component\Security\Core\User\UserInterface;
  17. use Symfony\Component\Security\Core\User\UserProviderInterface;
  18. use Symfony\Component\Security\Csrf\CsrfToken;
  19. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  20. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  21. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  22. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  23. class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  24. {
  25.     use TargetPathTrait;
  26.     public const LOGIN_ROUTE 'app_login';
  27.     private $entityManager;
  28.     private $urlGenerator;
  29.     private $csrfTokenManager;
  30.     private $passwordEncoder;
  31.     private $security;
  32.     public function __construct(EntityManagerInterface $entityManagerUrlGeneratorInterface $urlGenerator,
  33.                                 CsrfTokenManagerInterface $csrfTokenManager,
  34.                                 UserPasswordHasherInterface $passwordEncoder)
  35.     {
  36.         $this->entityManager $entityManager;
  37.         $this->urlGenerator $urlGenerator;
  38.         $this->csrfTokenManager $csrfTokenManager;
  39.         $this->passwordEncoder $passwordEncoder;
  40.     }
  41.     public function supports(Request $request): bool
  42.     {
  43.         return self::LOGIN_ROUTE === $request->attributes->get('_route')
  44.             && $request->isMethod('POST');
  45.     }
  46.     public function getCredentials(Request $request)
  47.     {
  48.         $credentials = [
  49.             'email' => $request->request->get('email'),
  50.             'password' => $request->request->get('password'),
  51.             'csrf_token' => $request->request->get('_csrf_token'),
  52.         ];
  53.         $request->getSession()->set(
  54.             Security::LAST_USERNAME,
  55.             $credentials['email']
  56.         );
  57.         return $credentials;
  58.     }
  59.     public function getUser($credentialsUserProviderInterface $userProvider): ?User
  60.     {
  61.         $token = new CsrfToken('authenticate'$credentials['csrf_token']);
  62.         if (!$this->csrfTokenManager->isTokenValid($token)) {
  63.             throw new InvalidCsrfTokenException();
  64.         }
  65.         $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
  66.         if (!$user) {
  67.             // fail authentication with a custom error
  68.             throw new CustomUserMessageAuthenticationException('Email could not be found.');
  69.         }
  70.         return $user;
  71.     }
  72.     public function checkCredentials($credentialsUserInterface $user): bool
  73.     {
  74.         return $this->passwordEncoder->isPasswordValid($user$credentials['password']);
  75.     }
  76.     /**
  77.      * Used to upgrade (rehash) the user's password automatically over time.
  78.      */
  79.     public function getPassword($credentials): ?string
  80.     {
  81.         return $credentials['password'];
  82.     }
  83.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey): ?Response
  84.     {
  85.         /*if ($this->security->isGranted('ROLE_ADMIN')){
  86.             return new RedirectResponse($this->router->generate('admin_index'), 307);
  87.         }*/
  88.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  89.             return new RedirectResponse($targetPath);
  90.         }
  91.         // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
  92.         //throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  93.         return new RedirectResponse($this->urlGenerator->generate('admin_index'));
  94.     }
  95.     protected function getLoginUrl(): string
  96.     {
  97.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  98.     }
  99. }