Refactor admin panel: enhance user management and security features

- Added role-based access control for user management links in admin navigation.
- Improved user account display with a dedicated account link.
- Implemented form submission confirmation for delete actions in the admin interface.
- Introduced a password visibility toggle on the login page.
- Added login throttling to prevent brute-force attacks, recording failed attempts.
- Created a CLI script for creating an admin user, replacing the previous hardcoded admin credentials.
- Updated database schema to support login attempt tracking.
- Enhanced user editing functionality, allowing role changes with restrictions.
- Improved modal handling for user actions, ensuring better focus management.
- Added styles for new account management page and improved modal transitions.
This commit is contained in:
David Dyer committed 2026-10-25 12:58:19 -04:00
1 parent 91ec95a4a9
commit 242c5165e1
21 files changed
+669 -77

No files matched your search

+39 -7
View File
@@ -3,11 +3,30 @@
* Auth & session helper
*/
/**
* Whether the visitor reached us over HTTPS. TLS ends at the reverse proxy
* (NPM or Caddy), so PHP itself only ever sees plain HTTP — trust the
* proxy's X-Forwarded-Proto, but only from a private/loopback address so a
* public client can't claim it.
*/
function request_is_https(): bool {
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
return true;
}
$remote = $_SERVER['REMOTE_ADDR'] ?? '';
$fromProxy = filter_var($remote, FILTER_VALIDATE_IP)
&& !filter_var($remote, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
return $fromProxy && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
}
if (session_status() === PHP_SESSION_NONE) {
// Configure secure session cookie defaults
// Configure secure session cookie defaults. 'secure' follows the
// request scheme so local dev over plain HTTP (including the phone on
// the LAN) can still log in; in production it's always HTTPS.
session_set_cookie_params([
'lifetime' => 86400 * 7, // 7 days
'path' => '/',
'secure' => request_is_https(),
'httponly' => true,
'samesite' => 'Lax'
]);
@@ -26,18 +45,31 @@ function require_auth(): void {
exit;
}
// A user disabled mid-session should lose access immediately rather
// than keep it until their session expires — re-check against the DB
// instead of trusting the session's now-possibly-stale copy.
// A user disabled or re-roled mid-session should be affected
// immediately rather than when their session expires — re-check against
// the DB instead of trusting the session's now-possibly-stale copy.
$pdo = get_db();
$stmt = $pdo->prepare("SELECT is_enabled FROM users WHERE id = ?");
$stmt = $pdo->prepare("SELECT is_enabled, role FROM users WHERE id = ?");
$stmt->execute([$_SESSION['admin_user_id']]);
$stillEnabled = $stmt->fetchColumn();
if ($stillEnabled === false || (int) $stillEnabled !== 1) {
$row = $stmt->fetch();
if ($row === false || (int) $row['is_enabled'] !== 1) {
logout_user();
header('Location: login.php');
exit;
}
$_SESSION['admin_role'] = $row['role'];
}
/**
* Like require_auth(), but also requires a specific role. Checked against
* the role require_auth() just re-read from the DB, not the login-time copy.
*/
function require_role(string $role): void {
require_auth();
if (($_SESSION['admin_role'] ?? '') !== $role) {
http_response_code(403);
exit('Forbidden');
}
}
function get_logged_in_user(): ?array {
+15 -8
View File
@@ -96,6 +96,17 @@ function init_db_schema(PDO $pdo): void {
menu_enabled INTEGER NOT NULL DEFAULT 1,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- Failed admin logins, used by inc/login-throttle.php. Rows older
-- than the throttle window are pruned on every new failure.
CREATE TABLE IF NOT EXISTS login_attempts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT NOT NULL,
username TEXT NOT NULL,
attempted_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_login_attempts_ip ON login_attempts (ip, attempted_at);
CREATE INDEX IF NOT EXISTS idx_login_attempts_username ON login_attempts (username, attempted_at);
");
// users.is_enabled shipped after the initial release — CREATE TABLE IF
@@ -112,14 +123,10 @@ function init_db_schema(PDO $pdo): void {
$pdo->exec("ALTER TABLE users ADD COLUMN is_enabled INTEGER NOT NULL DEFAULT 1");
}
// Seed default admin user if table is empty (username: admin / password: password)
$stmt = $pdo->query("SELECT COUNT(*) as count FROM users");
$userCount = $stmt->fetchColumn();
if ($userCount == 0) {
$defaultPassHash = password_hash('password', PASSWORD_DEFAULT);
$insert = $pdo->prepare("INSERT INTO users (username, password_hash, role) VALUES (?, ?, 'admin')");
$insert->execute(['admin', $defaultPassHash]);
}
// No default admin is seeded — a fresh database has no users until one
// is created from the CLI (run as www-data so the sqlite file stays
// writable by Apache):
// docker exec -it -u www-data the-old-fitz php /var/www/html/bin/create-user.php
// Seed default weekly hours if the table is empty: closed Sun–Wed,
// 4–10pm Thu–Sat with the kitchen closing at 9 — matches the hours the
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
/**
* Login brute-force throttle.
*
* Failed logins are recorded per client IP and per username. If either
* passes its limit inside the window, further attempts are refused until
* enough failures age out. A successful login clears that IP + username's
* failures.
*/
require_once __DIR__ . '/db.php';
const LOGIN_WINDOW_SECONDS = 900; // 15 minutes
const LOGIN_MAX_PER_IP = 5;
const LOGIN_MAX_PER_USERNAME = 10;
/**
* The real client IP. Behind a reverse proxy (NPM or Caddy), REMOTE_ADDR
* is the proxy's Docker-network address, so X-Forwarded-For is trusted —
* but only when the request came from a private or loopback address (the
* proxy), never from a public address that could set the header itself.
*
* The rightmost entry is used because it's the one our proxy appended.
* NPM appends to any value the client sent, so leftmost entries can be
* forged; Caddy discards the client's value, so it's the only entry.
*/
function client_ip(): string {
$remote = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$isPublic = filter_var($remote, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
if (!$isPublic) {
$chain = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '');
$forwarded = trim(end($chain));
if (filter_var($forwarded, FILTER_VALIDATE_IP) !== false) {
return $forwarded;
}
}
return $remote;
}
/**
* Seconds until this IP / username may try again, or 0 if not locked.
* Locked means the Nth most recent failure (N = the limit) is still
* inside the window; the lock lifts when that failure ages out.
*/
function login_lock_seconds(string $ip, string $username): int {
$pdo = get_db();
$since = time() - LOGIN_WINDOW_SECONDS;
$checks = [
['ip', $ip, LOGIN_MAX_PER_IP],
['username', $username, LOGIN_MAX_PER_USERNAME],
];
$wait = 0;
foreach ($checks as [$column, $value, $max]) {
$stmt = $pdo->prepare(
"SELECT attempted_at FROM login_attempts
WHERE $column = ? AND attempted_at > ?
ORDER BY attempted_at DESC LIMIT 1 OFFSET ?"
);
$stmt->execute([$value, $since, $max - 1]);
$nth = $stmt->fetchColumn();
if ($nth !== false) {
$wait = max($wait, (int) $nth + LOGIN_WINDOW_SECONDS - time());
}
}
return $wait;
}
function record_login_failure(string $ip, string $username): void {
$pdo = get_db();
$pdo->prepare("INSERT INTO login_attempts (ip, username, attempted_at) VALUES (?, ?, ?)")
->execute([$ip, $username, time()]);
// Prune anything outside the window so the table stays small.
$pdo->prepare("DELETE FROM login_attempts WHERE attempted_at <= ?")
->execute([time() - LOGIN_WINDOW_SECONDS]);
}
function clear_login_failures(string $ip, string $username): void {
get_db()->prepare("DELETE FROM login_attempts WHERE ip = ? AND username = ?")
->execute([$ip, $username]);
}
+21
View File
@@ -11,6 +11,8 @@ declare(strict_types=1);
require_once __DIR__ . '/db.php';
const MIN_PASSWORD_LENGTH = 12;
function get_all_users(): array {
$pdo = get_db();
$stmt = $pdo->query("SELECT id, username, role, is_enabled, created_at FROM users ORDER BY username ASC");
@@ -41,6 +43,19 @@ function toggle_user_enabled(int $id): bool {
return $stmt->execute([$id]);
}
function validate_username(string $username): ?string {
if ($username === '') {
return 'Username is required.';
}
if (strlen($username) < 3 || strlen($username) > 32) {
return 'Username must be between 3 and 32 characters.';
}
if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $username)) {
return 'Username can only contain letters, numbers, and . _ -';
}
return null;
}
function username_exists(string $username, ?int $excludeId = null): bool {
$pdo = get_db();
if ($excludeId !== null) {
@@ -61,6 +76,12 @@ function create_user(string $username, string $password, string $role): int {
return (int) $pdo->lastInsertId();
}
function update_user(int $id, string $username, string $role): bool {
$pdo = get_db();
$stmt = $pdo->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
return $stmt->execute([$username, $role, $id]);
}
function set_user_password(int $id, string $newPassword): bool {
$pdo = get_db();
$hash = password_hash($newPassword, PASSWORD_DEFAULT);