src/Security/Authenticator.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  10. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  11. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  14. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  15. class Authenticator extends AbstractLoginFormAuthenticator
  16. {
  17.     use TargetPathTrait;
  18.     public const LOGIN_ROUTE 'login';
  19.     public const ON_AUTHENTICATION_SUCCESS_ROUTE 'index';
  20.     public const ON_AUTHENTICATION_FAIL_URL '/login';
  21.     private UrlGeneratorInterface $urlGenerator;
  22.     public function __construct(UrlGeneratorInterface $urlGenerator)
  23.     {
  24.         $this->urlGenerator $urlGenerator;
  25.     }
  26.     public function authenticate(Request $request): Passport
  27.     {
  28.         $username $request->request->get('username''');
  29.         $request->getSession()->set(Security::LAST_USERNAME$username);
  30.         return new Passport(
  31.             new UserBadge($username),
  32.             new PasswordCredentials($request->request->get('password''')),
  33.             [
  34.                 new CsrfTokenBadge('authenticate'$request->request->get('_csrf_token')),
  35.             ]
  36.         );
  37.     }
  38.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  39.     {
  40.         if ($targetPath $this->getTargetPath($request->getSession(), $firewallName)) {
  41.             return new RedirectResponse($targetPath);
  42.         }
  43.         return new RedirectResponse($this->urlGenerator->generate(self::ON_AUTHENTICATION_SUCCESS_ROUTE));
  44.     }
  45.     protected function getLoginUrl(Request $request): string
  46.     {
  47.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  48.     }
  49. }