50 lines
1.5 KiB
PHP
50 lines
1.5 KiB
PHP
<?php
|
|
namespace Common\Service;
|
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
|
|
|
class Auth {
|
|
protected string $key;
|
|
public function __construct(string $api_key) {
|
|
$this->key = $api_key;
|
|
}
|
|
public function isValid(Request $request): bool {
|
|
if ($request->hasHeader('Authorization')) {
|
|
$sent_key = $this->getAuthKey($request->getHeader('Authorization'));
|
|
return $this->key == $sent_key;
|
|
}
|
|
if (isset($request->getParsedBody()['api_key'])) {
|
|
$sent_key = $request->getParsedBody()['api_key'];
|
|
return $this->key == $sent_key;
|
|
}
|
|
$post = $request->getParsedBody() ?? json_decode($request->getBody());
|
|
$sent_key = $this->getArrayKey($post);
|
|
if ($sent_key !== null) {
|
|
return $this->key == $sent_key;
|
|
}
|
|
$sent_key = $this->getArrayKey($request->getQueryParams());
|
|
return $this->key == $sent_key;
|
|
}
|
|
protected function getAuthKey($auth) {
|
|
if (is_array($auth)) {
|
|
$auth = $auth[0];
|
|
}
|
|
if (str_contains($auth, 'Bearer')) {
|
|
$auth = explode(' ', $auth)[1];
|
|
}
|
|
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;
|
|
}
|
|
}
|