ogcore/src/Security/ApiKeyAuthenticator.php

78 lines
2.9 KiB
PHP

<?php
namespace App\Security;
use App\Entity\User;
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\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\HttpKernel\KernelInterface;
class ApiKeyAuthenticator extends AbstractAuthenticator
{
private string $projectDir;
public function __construct(KernelInterface $kernel)
{
$this->projectDir = $kernel->getProjectDir();
}
/**
* 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->headers->has('X-API-KEY');
}
public function authenticate(Request $request): Passport
{
$apiToken = $request->headers->get('X-API-KEY');
$envFile = $this->projectDir . DIRECTORY_SEPARATOR . 'env.json';
if (!is_file($envFile)) {
throw new CustomUserMessageAuthenticationException('Configuration file not found.');
}
$config = json_decode(file_get_contents($envFile), true);
$expectedToken = $config['vars']['OGCLIENT_API_KEY'] ?? null;
if (null === $expectedToken || $apiToken !== $expectedToken) {
throw new CustomUserMessageAuthenticationException('Invalid API Token.');
}
// Usamos tu propia entidad User para crear un usuario virtual "al vuelo"
return new SelfValidatingPassport(new UserBadge('ogclient_api_user', function() {
$apiUser = new User();
$apiUser->setUsername('ogclient_api_user');
$apiUser->setRoles(['ROLE_OGCLIENT_API']);
$apiUser->setPassword(''); // Evitamos nulos en propiedades requeridas si las hay
return $apiUser;
}));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
// on success, let the request continue
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$data = [
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
}