src/Security/AuthAuthenticator.php line 19

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\RememberMeBadge;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  14. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  15. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  16. class AuthAuthenticator extends AbstractLoginFormAuthenticator
  17. {
  18.     use TargetPathTrait;
  19.     public const LOGIN_ROUTE 'app_login';
  20.     public function __construct(private UrlGeneratorInterface $urlGenerator)
  21.     {
  22.     }
  23.     public function authenticate(Request $request): Passport
  24.     {
  25.         $email $request->request->get('email''');
  26.         $request->getSession()->set(Security::LAST_USERNAME$email);
  27.         return new Passport(
  28.             new UserBadge($email),
  29.             new PasswordCredentials($request->request->get('password''')),
  30.             [
  31.                 new CsrfTokenBadge('authenticate'$request->request->get('_csrf_token')),
  32.                 new RememberMeBadge(),
  33.             ]
  34.         );
  35.     }
  36.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  37.     {
  38.         if ($targetPath $this->getTargetPath($request->getSession(), $firewallName)) {
  39.             return new RedirectResponse($targetPath);
  40.         }
  41.         // For example:
  42.         return new RedirectResponse($this->urlGenerator->generate('app_lookup'));
  43.         // throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  44.     }
  45.     protected function getLoginUrl(Request $request): string
  46.     {
  47.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  48.     }
  49. }