Validacion API/external

This commit is contained in:
Juan Pablo Vial
2025-05-12 16:01:09 -04:00
parent abe37227ce
commit 9e2d7277b0
3 changed files with 47 additions and 2 deletions

View File

@ -27,4 +27,9 @@ return [
'/api/login/',
'/api/logout'
],
'externalPaths' => [
'/api/external' => [
'/toku' => $_ENV['TOKU_TOKEN']
],
]
];

View File

@ -17,9 +17,10 @@ return [
$container->get(Psr\Log\LoggerInterface::class),
$container->get(Incoviba\Service\API::class),
$container->get(Incoviba\Service\Login::class),
$container->get('API_KEY'),
$container->get('permittedPaths'),
$container->get('simplePaths'),
$container->get('API_KEY')
$container->get('externalPaths'),
);
}
];

View File

@ -15,12 +15,16 @@ class API
protected LoggerInterface $logger,
protected Service\API $apiService,
protected Service\Login $loginService,
protected string $key,
protected array $permittedPaths,
protected array $simplePaths,
protected string $key) {}
protected array $externalPaths) {}
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($this->validExternal($request)) {
return $handler->handle($request);
}
try {
$key = $this->apiService->getKey($request);
} catch (MissingAuthorizationHeader $exception) {
@ -63,4 +67,39 @@ class API
$uri = $request->getUri();
return in_array($uri->getPath(), $this->permittedPaths);
}
protected function validExternal(ServerRequestInterface $request): bool
{
$uri = $request->getUri();
foreach ($this->externalPaths as $basePath => $paths) {
if (!str_starts_with($uri->getPath(), $basePath)) {
continue;
}
foreach ($paths as $subPath) {
$fullPath = "{$basePath}{$subPath}";
if ($uri->getPath() === $fullPath) {
return $this->validateExternalKey($request, $basePath, $subPath);
}
}
}
return false;
}
protected function validateExternalKey(ServerRequestInterface $request, $basePath, $subPath): bool
{
if ($request->hasHeader('x-api-key')) {
$key = $request->getHeaderLine('x-api-key');
if ($key === $this->externalPaths[$basePath][$subPath]) {
return true;
}
}
if ($request->hasHeader('Authorization')) {
$key = $request->getHeaderLine('Authorization');
if (str_starts_with($key, 'Bearer ')) {
$key = substr($key, 7);
if ($key === $this->externalPaths[$basePath][$subPath]) {
return true;
}
}
}
return false;
}
}