src/Security/LoginFormAuthenticator.php line 19

  1. <?php
  2. namespace App\Security;
  3. use App\Repository\UserRepository;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Bundle\SecurityBundle\Security;
  10. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  11. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  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 LoginFormAuthenticator extends AbstractLoginFormAuthenticator
  17. {
  18.     use TargetPathTrait;
  19.     public const LOGIN_ROUTE 'app_login';
  20.     public function __construct(
  21.         private readonly UrlGeneratorInterface $urlGenerator,
  22.         private readonly UserRepository $userRepo
  23.     ) {}
  24.     public function authenticate(Request $request): Passport
  25.     {
  26.         $email $request->request->get('email''');
  27.         $request->getSession()->set(Security::LAST_USERNAME$email);
  28.         return new Passport(
  29.             new UserBadge($email, function (string $userIdentify){
  30.                 return $this->userRepo->findOneBy(['email' => $userIdentify]);
  31.             }),
  32.             new PasswordCredentials($request->request->get('password''')),
  33.             [
  34.                 new CsrfTokenBadge('authenticate'$request->get('_csrf_token')),
  35.             ]
  36.         );
  37.     }
  38.     /**
  39.      * @throws \Exception
  40.      */
  41.     public function onAuthenticationSuccessRequest $requestTokenInterface $tokenstring $firewallName): ?Response
  42.     {
  43.         if ($targetPath $this->getTargetPath($request->getSession(), $firewallName)) {
  44.             return new RedirectResponse($targetPath);
  45.         }
  46.         // For example:
  47.         return new RedirectResponse($this->urlGenerator->generate('home'));
  48.     }
  49.     protected function getLoginUrl(Request $request): string
  50.     {
  51.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  52.     }
  53. }