Add API keys and server list api

This commit is contained in:
marc-go
2026-02-18 15:05:34 +01:00
parent 75899064c5
commit 4b4a46225f
5 changed files with 118 additions and 2 deletions

35
api/servers/list.php Normal file
View File

@@ -0,0 +1,35 @@
<?php
require "../../main.php";
$mcServ = new mcServ;
if (!$mcServ->checkApiAuth()) {
die('{"status":500, "error":"Unauthrized"}');
}
$db = $mcServ->getDB();
$sql = "SELECT * FROM servers";
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$servers = [];
if ($result) {
foreach ($result as $server_res) {
$server["name"] = $server_res["name"];
$server["uuid"] = $server_res["uuid"];
$servers[] = $server;
}
$json["servers"] = $servers;
}else{
$json["servers"] = [];
}
$json["status"] = 200;
echo json_encode($json);
?>

View File

@@ -33,6 +33,26 @@ CREATE TABLE IF NOT EXISTS users (
$db->exec($sql);
$sql = "
CREATE table IF NOT EXISTS servers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uuid VARCHAR(50) UNIQUE NOT NULL,
name VARCHAR(30)
)
";
$db->exec($sql);
$sql = "
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key VARCHAR(100) UNIQUE NOT NULL,
user_id INTEGER
)
";
$db->exec($sql);
$sql = "
INSERT INTO users (username, mail, passwd) VALUES (:user, :mail, :passwd)
";

View File

@@ -1,4 +1,14 @@
<?php
foreach ($_SERVER as $key => $value) {
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);
/*foreach ($_SERVER as $key => $value) {
echo $key . " = " . $value . "<br>";
}
}*/
require "../main.php";
$mcServ = new mcServ();
echo $mcServ->checkApiAuth() ? "TRUE" : "FALSE";

View File

@@ -15,6 +15,8 @@ ini_set("display_startup_errors", 1);
error_reporting(E_ALL);
class mcServ {
private $api_keys;
public function checkConf() {
if (!file_exists("../mcServ.db")) {
return false;
@@ -64,4 +66,53 @@ class mcServ {
return $hash;
}
public function checkApiAuth() {
if ($this->checkLogin()) {
return true;
}elseif (isset($_SERVER["HTTP_X_API_KEY"])) {
$key = $_SERVER["HTTP_X_API_KEY"];
$db = $this->getDB();
$sql = "SELECT * FROM api_keys WHERE key = :key";
$stmt = $db->prepare($sql);
$stmt->execute([":key" => $key]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
$user_id = $result["user_id"];
$sql = "SELECT username FROM users WHERE id = :id";
$stmt = $db->prepare($sql);
$stmt->execute([":id" => $user_id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$username = $result["username"];
$this->api_keys[$key] = $username;
return true;
}else{
return false;
}
}else{
return false;
}
}
public function getUser() {
if ($this->checkLogin()) {
return $_COOKIE["username"];
}elseif (isset($_SERVER["HTTP_X_API_KEY"])) {
$key = $_SERVER["HTTP_X_API_KEY"];
if (isset($this->api_keys[$key])) {
return $this->api_keys[$key];
}
}
}
}

BIN
mcServ.db

Binary file not shown.