61 lines
2.2 KiB
PHP
61 lines
2.2 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 = $this->getRequestKey($request);
|
|
if ($this->key == $api_key) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
protected function getRequestKey(Request $request) {
|
|
if ($request->hasHeader('Authorization')) {
|
|
return $this->getKeyFromHeader($request);
|
|
} elseif ($request->getParsedBody() !== null and in_array('API_KEY', $request->getParsedBody())) {
|
|
return $request->getParsedBody()['API_KEY'];
|
|
} elseif ($request->getQueryParams() !== null and in_array('API_KEY', array_keys($request->getQueryParams()))) {
|
|
return $request->getQueryParams()['API_KEY'];
|
|
}
|
|
return '';
|
|
}
|
|
protected function getKeyFromHeader(Request $request) {
|
|
$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];
|
|
}
|
|
return $api_key;
|
|
}
|
|
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){
|
|
error_log(var_export($e, true));
|
|
}
|
|
return $token;
|
|
}
|
|
public function generateToken(): object {
|
|
$selector = bin2hex(\random_bytes(12));
|
|
$token = bin2hex(\random_bytes(20));
|
|
$full = "{$selector}:{$token}";
|
|
$token = password_hash($token, \PASSWORD_DEFAULT);
|
|
return (object) compact('selector', 'token', 'full');
|
|
}
|
|
}
|