src/Security/LoginAuthenticator.php line 45
<?php
namespace App\Security;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use App\Entity\UserEntity;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Contracts\Translation\TranslatorInterface;
class LoginAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
private $entityManager;
private $translator;
public const LOGIN_ROUTE = 'login';
public function __construct(private UrlGeneratorInterface $urlGenerator, EntityManagerInterface $entityManager, TranslatorInterface $translator)
{
$this->entityManager = $entityManager;
$this->translator = $translator;
}
public function authenticate(Request $request): Passport
{
$username = $request->request->get('username', '');
$user = $this->entityManager->getRepository(UserEntity::class)->findOneBy(['username' => $username]);
if (!$user instanceof UserEntity || !$user->getActive()) {
$message = $this->translator->trans('user_not_active');
throw new CustomUserMessageAuthenticationException($message);
}
$request->getSession()->set(Security::LAST_USERNAME, $username);
return new Passport(
new UserBadge($username),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
]
);
}
public function redirectToLogin(): ?Response
{
return new RedirectResponse($this->urlGenerator->generate('login'));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate('index', ['_locale' => $request->getLocale()]));
}
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}