93 lines
2.6 KiB
PHP
Executable File
93 lines
2.6 KiB
PHP
Executable File
<?php
|
|
// API Main Library
|
|
class gbAPI {
|
|
function __construct($authRequired) {
|
|
define("APP_PATH", __DIR__ . "/../");
|
|
|
|
if ($authRequired) {
|
|
if (!$this->checkAuth()) {
|
|
$status = 401;
|
|
$data = [
|
|
"error" => "unauthorized",
|
|
"error_text" => "Authentication failed."
|
|
];
|
|
|
|
$this->answer($status, $data);
|
|
}
|
|
}
|
|
}
|
|
|
|
function getConfig() {
|
|
return parse_ini_file(APP_PATH . ".env");
|
|
}
|
|
|
|
function generateToken($username) {
|
|
$config = $this->getConfig();
|
|
|
|
// Generate Token
|
|
$payload = [
|
|
"user" => $username,
|
|
"auth" => true
|
|
];
|
|
$string = json_encode($payload);
|
|
$secret = $config["TOKEN_SIGNATURE"];
|
|
|
|
return hash_hmac("sha256", $string, $secret);
|
|
}
|
|
|
|
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->generateToken($username);
|
|
$given = $_COOKIE["auth_token"];
|
|
|
|
$result = hash_equals($expected, $given);
|
|
if ($result) {
|
|
return true;
|
|
}
|
|
}elseif (isset($_SERVER["HTTP_X_API_KEY"])) {
|
|
// Decode Token
|
|
$payload = json_decode(base64_decode($_SERVER["HTTP_X_API_KEY"]), true);
|
|
$username = $payload["username"];
|
|
|
|
$given = $payload["auth_token"];
|
|
$expected = $this->generateToken($username);
|
|
|
|
$result = hash_equals($expected, $given);
|
|
if ($result) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
function answer($status, $data = []) {
|
|
http_response_code($status);
|
|
Header ("Content-Type: application/json; charset=UTF-8");
|
|
|
|
$data = json_encode($data);
|
|
|
|
$json = '{"status":' . $status . ',"data":' . $data . '}';
|
|
die($json);
|
|
}
|
|
|
|
function dbCommand($command, $expectResult, $stmtArgsRequired = false, $stmtArgs = []) {
|
|
$db_path = APP_PATH . "database.db";
|
|
|
|
$db = new PDO("sqlite:" . $db_path);
|
|
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
|
|
$stmt = $db->prepare($command);
|
|
$stmt->execute($stmtArgs);
|
|
|
|
if ($expectResult) {
|
|
$result = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
return $result;
|
|
}
|
|
}
|
|
} |