Add cookie token lifetime configuration and implement base64 encoding/decoding methods
This commit is contained in:
1 parent
bf552e87cc
commit
a1bbae383a
4 files changed
+27
-7
No files matched your search
+14
-7
@@ -9,6 +9,13 @@ if ($debug) {
|
||||
// API Main Library
|
||||
class gbAPI {
|
||||
private $db;
|
||||
private function b64url_encode($data) {
|
||||
return rtrim(strtr(base64_encode($data), "+/", "-_"), "=");
|
||||
}
|
||||
|
||||
private function b64url_decode($data) {
|
||||
return base64_decode(strtr($data, "-_", "+/"));
|
||||
}
|
||||
|
||||
function __construct($authRequired) {
|
||||
define("APP_PATH", __DIR__ . "/../");
|
||||
@@ -37,13 +44,13 @@ class gbAPI {
|
||||
$payload = [
|
||||
"user" => $username,
|
||||
"auth" => true,
|
||||
"exp" => $config["COOKIE_TOKEN_LIFETIME"]
|
||||
"exp" => time() + $config["COOKIE_TOKEN_LIFETIME"]
|
||||
];
|
||||
$string = base64_encode(json_encode($payload));
|
||||
$string = $this->b64url_encode(json_encode($payload));
|
||||
$secret = $config["COOKIE_TOKEN_SIGNATURE"];
|
||||
|
||||
$sig = hash_hmac("sha256", $string, $secret);
|
||||
return base64_encode(json_encode($payload)) . "." . $sig;
|
||||
return $string . "." . $sig;
|
||||
}
|
||||
|
||||
function generateAPIToken($username) {
|
||||
@@ -54,11 +61,11 @@ class gbAPI {
|
||||
"user" => $username,
|
||||
"auth" => true
|
||||
];
|
||||
$string = base64_encode(json_encode($payload));
|
||||
$string = $this->b64url_encode(json_encode($payload));
|
||||
$secret = $config["API_TOKEN_SIGNATURE"];
|
||||
|
||||
$sig = hash_hmac("sha256", $string, $secret);
|
||||
return base
|
||||
return $string . "." . $sig;
|
||||
}
|
||||
|
||||
function checkAuth() {
|
||||
@@ -73,7 +80,7 @@ class gbAPI {
|
||||
$result = hash_equals($expected, $given);
|
||||
if ($result) {
|
||||
$given_string = explode(".", $given);
|
||||
$body = json_decode(base64_decode($given_string[0]));
|
||||
$body = json_decode($this->b64url_decode($given_string[0]), true);
|
||||
|
||||
if ($body["exp"] > time()) {
|
||||
return true;
|
||||
@@ -83,7 +90,7 @@ class gbAPI {
|
||||
}
|
||||
}elseif (isset($_SERVER["HTTP_X_API_KEY"])) {
|
||||
// Decode Token
|
||||
$payload = json_decode(base64_decode($_SERVER["HTTP_X_API_KEY"]), true);
|
||||
$payload = json_decode($this->b64url_decode($_SERVER["HTTP_X_API_KEY"]), true);
|
||||
$username = $payload["username"];
|
||||
|
||||
$given = $payload["auth_token"];
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
// Load Main Library
|
||||
require "../api.php";
|
||||
$api = new gbAPI(true);
|
||||
|
||||
$api->answer(200, [
|
||||
"login" => true
|
||||
]);
|
||||
@@ -90,6 +90,7 @@ $api_token = bin2hex(random_bytes(32));
|
||||
$env .= "API_TOKEN_SIGNATURE=" . $api_token . "\n";
|
||||
|
||||
$env .= "DB_FILE=database.db";
|
||||
$env .= "COOKIE_TOKEN_LIFETIME=86400";
|
||||
|
||||
file_put_contents(APP_PATH . ".env", $env);
|
||||
|
||||
|
||||
Reference in new issue
Block a user