Files
crowd-fund-api/src/Security/CookieAuthenticator.php
T

57 lines
1.9 KiB
PHP

<?php
namespace App\Security;
use App\Service\Auth\AuthService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
/**
* @see https://symfony.com/doc/current/security/custom_authenticator.html
*/
class CookieAuthenticator extends AbstractAuthenticator
{
public function __construct(
private AccessTokenHandler $accessTokenHandler,
) {}
/**
* Called on every request to decide if this authenticator should be
* used for the request. Returning `false` will cause this authenticator
* to be skipped.
*/
public function supports(Request $request): ?bool
{
return $request->cookies->has(AuthService::AUTH_COOKIE_NAME);
}
public function authenticate(Request $request): Passport
{
$token = $request->cookies->get(AuthService::AUTH_COOKIE_NAME);
if (!$token) {
throw new AuthenticationException();
}
return new SelfValidatingPassport($this->accessTokenHandler->getUserBadgeFrom($token));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new JsonResponse([
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
], Response::HTTP_UNAUTHORIZED);
}
}