Files
pguzman 9622f9aeca Consolidate schema, add CSRF protection, and add login rate-limiting
Six fixes from a codebase review:

- Consolidate the ad hoc install.php + migrate_v2..v6.php chain into one
  canonical schema.sql (structure reference) plus a simplified install.php
  that creates all tables and seeds site_settings, the superadmin account,
  and the standard prayer library. The six migrate_v*.php scripts are
  deleted — their cumulative effect is now fully captured in schema.sql.

- Delete the two root-level setup.php/novena_group.php files that existed
  only to redirect to their admin/ equivalents of the same name; confirmed
  unreferenced by any link or .htaccess rule.

- Decouple includes/build_slides.php from data/prayers.php's implicit
  `global $opening, $mysteries, ...` contract. data/prayers.php now
  explicitly returns its arrays; build_slides.php loads them through a
  small memoized get_prayer_data() and destructures them by key.

- Add CSRF protection (includes/csrf.php: csrf_token/csrf_field/csrf_verify)
  across every POST-handling endpoint — 10 form pages and 7 API endpoints —
  plus token wiring in the JS/inline scripts that call the FormData- and
  JSON-body API endpoints (builder.js, setup.js, and the inline scripts in
  admin/audio.php, admin/novena_group.php, and index.php).

- Stop round-tripping the SMTP password in plaintext through the settings
  form: the field now renders blank with a "currently set" hint, and a
  blank submission leaves the stored password unchanged instead of
  clearing it.

- Add login rate-limiting: users.failed_login_attempts / locked_until
  columns, is_locked_out()/record_login_failure()/record_login_success()
  helpers in includes/auth.php, and lockout handling in login.php (5
  failed attempts locks the account for 15 minutes). README documents the
  one manual ALTER TABLE needed to add these columns to an existing
  production database.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 09:34:10 -07:00

106 lines
3.8 KiB
PHP

<?php
/**
* includes/auth.php — multi-user role-based authentication.
*/
function _auth_start(): void {
if (session_status() === PHP_SESSION_NONE) session_start();
}
/** Redirect to login if not authenticated. */
function require_auth(): void {
_auth_start();
if (empty($_SESSION['user_id'])) {
header('Location: ' . BASE_URL . '/login');
exit;
}
}
/** Redirect/abort if user doesn't have the minimum role. */
function require_role(string $min_role): void {
require_auth();
if (!has_role($min_role)) {
http_response_code(403);
echo '<!DOCTYPE html><html><body style="font-family:system-ui;max-width:500px;margin:60px auto;text-align:center">'
. '<h1 style="color:#dc2626">Access Denied</h1>'
. '<p>You do not have permission to view this page.</p>'
. '<a href="' . BASE_URL . '/admin/">&#8592; Dashboard</a></body></html>';
exit;
}
}
/** True if current session user has at least $min_role. */
function has_role(string $min): bool {
_auth_start();
$levels = ['user' => 1, 'superuser' => 2, 'admin' => 3, 'superadmin' => 4];
return ($levels[$_SESSION['role'] ?? ''] ?? 0) >= ($levels[$min] ?? 999);
}
/** Return current user data from session (or empty defaults). */
function current_user(): array {
_auth_start();
return [
'id' => $_SESSION['user_id'] ?? null,
'username' => $_SESSION['username'] ?? '',
'email' => $_SESSION['email'] ?? '',
'role' => $_SESSION['role'] ?? '',
'display_name' => $_SESSION['display_name'] ?? '',
'rosary_limit' => $_SESSION['rosary_limit'] ?? 1,
];
}
/**
* Check if user can create another rosary.
* Novenas count as 1 regardless of number of days.
* Returns true if under limit (or limit is -1 = unlimited).
*/
function can_create_rosary(int $user_id, int $limit): bool {
if ($limit < 0) return true; // unlimited
$pdo = get_pdo();
$st = $pdo->prepare("
SELECT
(SELECT COUNT(*) FROM sessions WHERE user_id = ? AND occasion != 'novena_deceased') +
(SELECT COUNT(*) FROM novena_groups WHERE user_id = ?)
AS total
");
$st->execute([$user_id, $user_id]);
return (int)$st->fetchColumn() < $limit;
}
const LOGIN_LOCKOUT_THRESHOLD = 5;
const LOGIN_LOCKOUT_MINUTES = 15;
/** True if this user account is currently locked out from login attempts. */
function is_locked_out(array $user): bool {
if (empty($user['locked_until'])) return false;
return strtotime($user['locked_until']) > time();
}
/** Minutes remaining until a locked-out account can try again (0 if not locked). */
function login_lockout_minutes_remaining(array $user): int {
if (!is_locked_out($user)) return 0;
return (int)ceil((strtotime($user['locked_until']) - time()) / 60);
}
/** Record a failed login attempt; locks the account after LOGIN_LOCKOUT_THRESHOLD attempts. */
function record_login_failure(int $user_id): void {
$pdo = get_pdo();
$pdo->prepare('UPDATE users SET failed_login_attempts = failed_login_attempts + 1 WHERE id = ?')
->execute([$user_id]);
$st = $pdo->prepare('SELECT failed_login_attempts FROM users WHERE id = ?');
$st->execute([$user_id]);
$attempts = (int)$st->fetchColumn();
if ($attempts >= LOGIN_LOCKOUT_THRESHOLD) {
$locked_until = date('Y-m-d H:i:s', time() + LOGIN_LOCKOUT_MINUTES * 60);
$pdo->prepare('UPDATE users SET locked_until = ? WHERE id = ?')->execute([$locked_until, $user_id]);
}
}
/** Reset the failed-attempt counter and any lockout after a successful login. */
function record_login_success(int $user_id): void {
get_pdo()->prepare('UPDATE users SET failed_login_attempts = 0, locked_until = NULL WHERE id = ?')
->execute([$user_id]);
}