<?php
namespace App\Security;
use LogicException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class AuthenticationUtilsExtend extends AuthenticationUtils
{
public function __construct(private RequestStack $requestStack)
{
parent::__construct($this->requestStack);
}
public function getLastAuthenticationError(bool $clearSession = true)
{
$request = $this->getRequest();
$authenticationException = null;
$session = $request->getSession();
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$authenticationException = $request->attributes->get(Security::AUTHENTICATION_ERROR);
$session->set(Security::AUTHENTICATION_ERROR, $authenticationException);
} elseif ($request->hasSession() && $session->has(Security::AUTHENTICATION_ERROR)) {
$authenticationException = $session->get(Security::AUTHENTICATION_ERROR);
if ($clearSession) {
$session->remove(Security::AUTHENTICATION_ERROR);
}
}
return $authenticationException;
}
public function getLastUsername()
{
$request = $this->getRequest();
if ($request->attributes->has(Security::LAST_USERNAME)) {
return $request->attributes->get(Security::LAST_USERNAME, '');
}
return $request->hasSession() ? $request->getSession()->get(Security::LAST_USERNAME, '') : '';
}
private function getRequest(): Request
{
if ($this->requestStack->getParentRequest()?->attributes?->has(Security::AUTHENTICATION_ERROR)) {
$request = $this->requestStack->getParentRequest();
} else {
$request = $this->requestStack->getCurrentRequest();
}
if (null === $request) {
throw new LogicException('Request should exist so it can be processed for error.');
}
return $request;
}
}