<?php
namespace App\Security;
use App\Form\LoginFormType;
use ReCaptcha\ReCaptcha;
use Symfony\Component\Form\FormFactoryInterface;
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\Exception\CustomUserMessageAuthenticationException;
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 AppAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_login';
private ReCaptcha $reCaptcha;
public function __construct(private UrlGeneratorInterface $urlGenerator,
private FormFactoryInterface $formFactory,
string $googleRecaptchaSiteSecret)
{
$this->reCaptcha = new ReCaptcha($googleRecaptchaSiteSecret);
}
public function authenticate(Request $request)
{
//form generation should be in the same way (createdNamed in this case) as in LoginController
$loginForm = $this->formFactory->createNamed('login', LoginFormType::class);
if (!$loginForm->has('captcha')) {
throw new CustomUserMessageAuthenticationException('Ha ocurrido un error1. Por favor intenta de nuevo.');
}
$loginArray = $request->request->get('login_form');
$loginForm->submit($loginArray);
if (!$loginForm->isSubmitted()) {
throw new CustomUserMessageAuthenticationException('Ha ocurrido un error2. Por favor intenta de nuevo.');
}
if (!$loginForm->get('captcha')->isValid()) {
throw new CustomUserMessageAuthenticationException('Error validando si es un robot. Por favor intenta de nuevo');
}
$username = $loginForm->get('_username')->getData();
$password = $loginForm->get('_password')->getData();
$token = $loginArray['_csrf_token']??'';
$request->getSession()->set(Security::LAST_USERNAME, $username);
return new Passport(
new UserBadge($username),
new PasswordCredentials($password),
[new CsrfTokenBadge('authenticate', $token)]
);
}
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(self::LOGIN_ROUTE);
}
}