467363d651
Made-with: Cursor
124 lines
2.7 KiB
PHP
124 lines
2.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
session_start([
|
|
'cookie_httponly' => true,
|
|
'cookie_samesite' => 'Lax',
|
|
'name' => 'SITEADMINSESSID',
|
|
'use_strict_mode' => true,
|
|
]);
|
|
|
|
define('ADMIN_PRIVATE_DIR', dirname(__DIR__) . '/private');
|
|
define('ADMIN_STORE', ADMIN_PRIVATE_DIR . '/store.json');
|
|
|
|
function json_response(array $data, int $code = 200): void
|
|
{
|
|
http_response_code($code);
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('X-Content-Type-Options: nosniff');
|
|
echo json_encode($data, JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
|
|
function default_store(): array
|
|
{
|
|
return [
|
|
'version' => 1,
|
|
'oauth' => [
|
|
'facebookAppId' => '',
|
|
'facebookAppSecret' => '',
|
|
'facebookRedirectUri' => '',
|
|
'googleClientId' => '',
|
|
'googleClientSecret' => '',
|
|
'googleRedirectUri' => '',
|
|
],
|
|
'admins' => [],
|
|
'accounts' => [],
|
|
];
|
|
}
|
|
|
|
function read_store(): array
|
|
{
|
|
if (!is_file(ADMIN_STORE)) {
|
|
return default_store();
|
|
}
|
|
$raw = @file_get_contents(ADMIN_STORE);
|
|
$j = json_decode($raw ?: '{}', true);
|
|
return is_array($j) ? array_replace_recursive(default_store(), $j) : default_store();
|
|
}
|
|
|
|
function write_store(array $data): bool
|
|
{
|
|
if (!is_dir(ADMIN_PRIVATE_DIR)) {
|
|
if (!@mkdir(ADMIN_PRIVATE_DIR, 0750, true)) {
|
|
return false;
|
|
}
|
|
}
|
|
$tmp = ADMIN_STORE . '.tmp.' . bin2hex(random_bytes(4));
|
|
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
|
if ($json === false) {
|
|
return false;
|
|
}
|
|
if (file_put_contents($tmp, $json, LOCK_EX) === false) {
|
|
return false;
|
|
}
|
|
if (!rename($tmp, ADMIN_STORE)) {
|
|
@unlink($tmp);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function store_needs_setup(): bool
|
|
{
|
|
if (!is_file(ADMIN_STORE)) {
|
|
return true;
|
|
}
|
|
$s = read_store();
|
|
return empty($s['admins']);
|
|
}
|
|
|
|
function require_json_body(): array
|
|
{
|
|
$raw = file_get_contents('php://input');
|
|
$j = json_decode($raw ?: '{}', true);
|
|
return is_array($j) ? $j : [];
|
|
}
|
|
|
|
function current_admin(): ?array
|
|
{
|
|
$id = $_SESSION['admin_id'] ?? null;
|
|
if (!$id || !is_string($id)) {
|
|
return null;
|
|
}
|
|
foreach (read_store()['admins'] ?? [] as $a) {
|
|
if (($a['id'] ?? '') === $id) {
|
|
return $a;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function require_login(): void
|
|
{
|
|
if (!current_admin()) {
|
|
json_response(['ok' => false, 'error' => 'Unauthorized'], 401);
|
|
}
|
|
}
|
|
|
|
function is_super(array $admin): bool
|
|
{
|
|
return ($admin['role'] ?? '') === 'super';
|
|
}
|
|
|
|
function strip_admin(array $a): array
|
|
{
|
|
unset($a['passwordHash']);
|
|
return $a;
|
|
}
|
|
|
|
function new_id(): string
|
|
{
|
|
return bin2hex(random_bytes(12));
|
|
}
|