Files
contabilidad/api/common/Service/Auth.php
2022-12-20 14:13:05 -03:00

88 lines
2.5 KiB
PHP

<?php
namespace Common\Service;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use DI\NotFoundException;
class Auth {
protected string $key;
public function __construct(string $api_key)
{
$this->key = $api_key;
}
public function isValid(Request $request): bool
{
return $this->key == $this->getKey($request);
}
public function getKey(Request $request): string
{
$errors = [];
try {
return $this->getHeaderKey($request);
} catch (NotFoundExceptionInterface $e) {
$errors []= $e;
}
try {
return $this->getBodyKey($request);
} catch (NotFoundExceptionInterface $e) {
$errors []= $e;
}
try {
return $this->getQueryKey($request);
} catch (NotFoundExceptionInterface $e) {
$errors []= $e;
}
throw new NotFoundException('API Key not found.');
}
protected function getHeaderKey(Request $request): string
{
if ($request->hasHeader('Authorization')) {
return $this->getAuthKey($request->getHeader('Authorization'));
}
throw new NotFoundException('API Key not found on header');
}
protected function getBodyKey(Request $request): string
{
if (isset($request->getParsedBody()['api_key'])) {
return $request->getParsedBody()['api_key'];
}
$post = $request->getParsedBody() ?? json_decode($request->getBody());
try {
return $this->getArrayKey($post);
} catch (\Exception $e) {
throw new NotFoundException('API Key not found in body.');
}
}
protected function getQueryKey(Request $request): string
{
try {
return $this->getArrayKey($request->getQueryParams());
} catch (\Exception $e) {
throw new NotFoundException('API Key not found in query.');
}
}
protected function getAuthKey($auth)
{
if (is_array($auth)) {
$auth = $auth[0];
}
if (str_contains($auth, 'Bearer')) {
$auth = trim(str_replace('Bearer', '', $auth), ' ,');
}
return $auth;
}
protected function getArrayKey($array) {
$posible_keys = [
'API_KEY',
'api_key',
];
foreach ($posible_keys as $key) {
if (isset($array[$key])) {
return $array[$key];
}
}
return null;
}
}