This commit is contained in:
2021-11-30 18:04:41 -03:00
parent 87323b22d8
commit f589ff960b
56 changed files with 1960 additions and 0 deletions

51
common/Service/Auth.php Normal file
View File

@ -0,0 +1,51 @@
<?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;
}
}