52 lines
1.5 KiB
PHP
52 lines
1.5 KiB
PHP
<?php
|
|
namespace Incoviba\API\Common\Service;
|
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
|
|
|
class Auth {
|
|
protected string $key;
|
|
public function __construct(string $key) {
|
|
$this->key = $key;
|
|
}
|
|
public function isValid(Request $request): bool {
|
|
$api_key = '';
|
|
if ($request->hasHeader('Authorization')) {
|
|
$api_key = $request->getHeader('Authorization');
|
|
if (is_array($api_key)) {
|
|
$api_key = $api_key[0];
|
|
}
|
|
if (str_contains($api_key, 'Bearer')) {
|
|
$api_key = explode(' ', $api_key)[1];
|
|
}
|
|
} elseif ($request->getParsedBody() !== null and in_array('API_KEY', $request->getParsedBody())) {
|
|
$api_key = $request->getParsedBody()['API_KEY'];
|
|
} elseif ($request->getQueryParams() !== null and in_array('API_KEY', array_keys($request->getQueryParams()))) {
|
|
$api_key = $request->getQueryParams()['API_KEY'];
|
|
}
|
|
if ($this->key == $api_key) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
public function generate(int $length = 32, bool $removeSimilarCharacters = true): string {
|
|
$token = "";
|
|
try {
|
|
$bytesWithMargin = random_bytes($length*3);
|
|
|
|
$base64 = base64_encode($bytesWithMargin);
|
|
$purified = preg_replace("/[+=\/.]/", "", $base64);
|
|
|
|
if ($removeSimilarCharacters){
|
|
$purified = preg_replace("/[I1l0Oo]/", "", $purified);
|
|
}
|
|
|
|
$token = substr($purified, 0, $length);
|
|
|
|
} catch (\Exception $e){
|
|
echo $e->getMessage();
|
|
}
|
|
|
|
return $token;
|
|
}
|
|
}
|