Refactor authentication: streamline cookie handling and enhance username retrieval in responses

This commit is contained in:
marc-go committed 2026-10-09 19:20:53 +02:00
1 parent a1bbae383a
commit 6b5a299079
3 files changed
+47 -20

No files matched your search

+45 -18
View File
@@ -8,7 +8,10 @@ if ($debug) {
}
// API Main Library
class gbAPI {
public $username;
private $db;
private $config;
private function b64url_encode($data) {
return rtrim(strtr(base64_encode($data), "+/", "-_"), "=");
}
@@ -34,7 +37,11 @@ class gbAPI {
}
function getConfig() {
return parse_ini_file(APP_PATH . ".env");
if (isset($this->config)) {
return $config;
}else{
return parse_ini_file(APP_PATH . ".env");
}
}
function generateCookieToken($username) {
@@ -69,37 +76,57 @@ class gbAPI {
}
function checkAuth() {
if (!isset($_SERVER["HTTP_X_API_KEY"]) && !isset($_COOKIE["auth_token"])) {
return false;
}elseif (isset($_COOKIE["auth_token"]) && isset($_COOKIE["username"])) {
// Check Token
$username = $_COOKIE["username"];
$expected = $this->generateCookieToken($username);
$given = $_COOKIE["auth_token"];
if (isset($_COOKIE["auth_token"])) {
// Get Config
$config = $this->getConfig();
$result = hash_equals($expected, $given);
// Check Token
$given = $_COOKIE["auth_token"];
if (!is_string($given)) {
return false;
}
$given_string = explode(".", $given);
if (count($parts) !== 2) {
return false;
}
$sig_expected = hash_hmac("sha256", $given_string[0], $config["COOKIE_TOKEN_SIGNATURE"]);
@$result = hash_equals($sig_expected, $given_string[1]);
if ($result) {
$given_string = explode(".", $given);
$body = json_decode($this->b64url_decode($given_string[0]), true);
if ($body["exp"] > time()) {
$this->username = $body["user"];
return true;
}else{
return false;
}
}else{
return false;
}
}elseif (isset($_SERVER["HTTP_X_API_KEY"])) {
// Get config
$config = $this->getConfig();
// Decode Token
$payload = json_decode($this->b64url_decode($_SERVER["HTTP_X_API_KEY"]), true);
$username = $payload["username"];
$given = $_SERVER["HTTP_X_API_KEY"];
$given = $payload["auth_token"];
$expected = $this->generateAPIToken($username);
$result = hash_equals($expected, $given);
if ($result) {
return true;
if (!is_string($given)) {
return false;
}
$given_string = explode(".", $given);
if (count($parts) !== 2) {
return false;
}
$sig_expected = hash_hmac("sha256", $given_string[0], $config["API_TOKEN_SIGNATURE"]);
@$result = hash_equals($sig_expected, $given_string[1]);
}
return false;
+2 -1
View File
@@ -4,5 +4,6 @@ require "../api.php";
$api = new gbAPI(true);
$api->answer(200, [
"login" => true
"login" => true,
"username" => $api->username
]);
-1
View File
@@ -40,7 +40,6 @@ if ($result && password_verify($password, $result[0]["password"])) {
// Set cookies
setcookie("auth_token", $token, time() + 86400, "/");
setcookie("username", $username, time() + 86400, "/");
$api->answer(200);
}else{