src/Security/AppCustomAuthenticator.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpFoundation\RequestStack;
  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\Component\Security\Core\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\Authenticator\Passport\PassportInterface;
  16. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  17. use App\Repository\UserRepository;
  18. class AppCustomAuthenticator extends AbstractLoginFormAuthenticator
  19. {
  20.     use TargetPathTrait;
  21.     public const LOGIN_ROUTE 'app_login';
  22.     private $urlGenerator;
  23.     private $repo_user;
  24.     public function __construct(UrlGeneratorInterface $urlGeneratorUserRepository $repo_userRequestStack $requestStack)
  25.     {
  26.         $this->requestStack $requestStack;
  27.         $this->urlGenerator $urlGenerator;
  28.         $this->repo_user $repo_user;
  29.     }
  30.     public function authenticate(Request $request): PassportInterface
  31.     {
  32.         $email $request->request->get('email''');
  33.         $session $this->requestStack->getCurrentRequest()->getSession();
  34.         $session->set(Security::LAST_USERNAME$email);
  35.         return new Passport(
  36.             new UserBadge($email),
  37.             new PasswordCredentials($request->request->get('password''')),
  38.             [
  39.                 new CsrfTokenBadge('authenticate'$request->get('_csrf_token')),
  40.             ]
  41.         );
  42.     }
  43.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  44.     {
  45.         if ($targetPath $this->getTargetPath($this->requestStack->getCurrentRequest()->getSession(), $firewallName)) {
  46.             return new RedirectResponse($targetPath);
  47.         }
  48.         // For example:
  49.         return new RedirectResponse($this->urlGenerator->generate('parent'));
  50.     }
  51.     protected function getLoginUrl(Request $request): string
  52.     {
  53.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  54.     }
  55. }