src/Security/AppCustomeAuthenticator.php line 18

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