diff --git a/app/index.php b/app/index.php index d44d0ef..278a11a 100644 --- a/app/index.php +++ b/app/index.php @@ -3,6 +3,13 @@ define('CADDY_ADMIN_URL', getenv('CADDY_ADMIN_URL') ?: 'http://localhost:2019'); define('CADDYFILE_STORE', getenv('CADDYFILE_STORE') ?: '/data/Caddyfile'); define('CADDYFILE_IMPORT', getenv('CADDYFILE_IMPORT') ?: ''); +define('AUTH_USER', getenv('AUTH_USER') ?: ''); +define('AUTH_PASS', getenv('AUTH_PASS') ?: ''); // bcrypt hash + +// ─── Session / Auth ────────────────────────────────────────────────────────── +session_start(); +$auth_enabled = AUTH_USER !== '' && AUTH_PASS !== ''; +$logged_in = !$auth_enabled || !empty($_SESSION['koncad_auth']); // ─── Helpers ───────────────────────────────────────────────────────────────── function dedent(array $lines): array { @@ -105,6 +112,31 @@ if (isset($_GET['action'])) { ini_set('display_errors', 0); header('Content-Type: application/json'); + switch ($_GET['action']) { + + case 'login': + $user = trim($_POST['user'] ?? ''); + $pass = $_POST['pass'] ?? ''; + if ($auth_enabled && $user === AUTH_USER && password_verify($pass, AUTH_PASS)) { + $_SESSION['koncad_auth'] = true; + echo json_encode(['ok' => true]); + } else { + echo json_encode(['ok' => false, 'error' => 'Invalid credentials']); + } + exit; + + case 'logout': + session_destroy(); + echo json_encode(['ok' => true]); + exit; + + default: + if ($auth_enabled && !$logged_in) { + echo json_encode(['ok' => false, 'error' => 'Unauthorized']); + exit; + } + } + switch ($_GET['action']) { case 'check_admin': @@ -117,11 +149,10 @@ if (isset($_GET['action'])) { exit; case 'load': - if (file_exists(CADDYFILE_STORE)) { - $raw = file_get_contents(CADDYFILE_STORE); - } elseif (CADDYFILE_IMPORT && file_exists(CADDYFILE_IMPORT)) { + if (CADDYFILE_IMPORT && file_exists(CADDYFILE_IMPORT)) { $raw = file_get_contents(CADDYFILE_IMPORT); - file_put_contents(CADDYFILE_STORE, $raw); + } elseif (file_exists(CADDYFILE_STORE)) { + $raw = file_get_contents(CADDYFILE_STORE); } else { $raw = ''; } @@ -159,12 +190,60 @@ if (isset($_GET['action'])) { echo json_encode(['ok' => false, 'error' => 'Unknown action']); exit; } + +// ─── Login page ─────────────────────────────────────────────────────────────── +if ($auth_enabled && !$logged_in): +$login_error = ''; +if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $u = trim($_POST['user'] ?? ''); + $p = $_POST['pass'] ?? ''; + if ($u === AUTH_USER && password_verify($p, AUTH_PASS)) { + $_SESSION['koncad_auth'] = true; + header('Location: /'); exit; + } + $login_error = 'Invalid credentials'; +} ?>
+