<?php
declare(strict_types=1);
namespace Smakmedia\Security;
use Smakmedia\Repository\AdminUserRepository;
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\Core\Security;
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;
class LoginAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
private UrlGeneratorInterface $urlGenerator;
private AdminUserRepository $adminUserRepository;
public function __construct(UrlGeneratorInterface $urlGenerator, AdminUserRepository $adminUserRepository)
{
$this->urlGenerator = $urlGenerator;
$this->adminUserRepository = $adminUserRepository;
}
public function authenticate(Request $request): Passport
{
$credentials = $this->getCredentials($request);
return new Passport(
new UserBadge($credentials['username'], function (string $userIdentifier) {
return $this->adminUserRepository->findOneBy(['username' => $userIdentifier, 'status' => 1]);
}),
new PasswordCredentials($credentials['password']),
[new CsrfTokenBadge('authenticate', $credentials['csrf_token'])]
);
}
public function getCredentials(Request $request): array
{
$credentials = [
'username' => $request->request->get('_username'),
'password' => $request->request->get('_password'),
'csrf_token' => $request->request->get('_csrf_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['username']
);
return $credentials;
}
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('dashboard'));
}
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate('login');
}
}