Files
Rosary/api/prayers_api.php
T
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

193 lines
7.7 KiB
PHP

<?php
/**
* api/prayers_api.php — CRUD for custom_prayers.
* Requires superuser+.
*
* GET ?q=&source=all|standard|mine — list prayers
* POST — create prayer (body JSON)
* PUT ?id=X — update prayer (body JSON)
* DELETE ?id=X — delete prayer
*/
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
header('Content-Type: application/json');
function json_err(string $msg, int $code = 400): never {
http_response_code($code);
echo json_encode(['error' => $msg]);
exit;
}
require_auth();
if (!has_role('superuser')) json_err('Access denied', 403);
$pdo = get_pdo();
$user = current_user();
$uid = (int)$user['id'];
$is_admin = has_role('admin');
$method = $_SERVER['REQUEST_METHOD'];
// CSRF check applies to state-changing methods only (GET is read-only)
if ($method !== 'GET') csrf_verify();
// ─────────────────────────────────────────────────
// GET — list prayers
// ─────────────────────────────────────────────────
if ($method === 'GET') {
$source = $_GET['source'] ?? 'all';
$q = trim($_GET['q'] ?? '');
$where = [];
$params = [];
if ($source === 'standard' || $source === 'mine') {
if ($source === 'standard') {
$where[] = 'cp.is_global = 1 AND u.role = \'superadmin\'';
} else {
$where[] = 'cp.created_by = ?';
$params[] = $uid;
}
} else {
// all: global prayers + own private prayers
$where[] = '(cp.is_global = 1 OR cp.created_by = ?)';
$params[] = $uid;
}
if ($q !== '') {
$like = '%' . $q . '%';
$where[] = '(cp.name LIKE ? OR cp.leader_text LIKE ? OR cp.all_text LIKE ?)';
$params[] = $like;
$params[] = $like;
$params[] = $like;
}
$sql = "
SELECT cp.id, cp.name, cp.leader_text, cp.all_text,
cp.default_bead_type, cp.is_global, cp.created_by,
u.role AS creator_role,
IF(cp.is_global=1 AND u.role='superadmin', 'standard',
IF(cp.is_global=1, 'global', 'mine')) AS source_tag
FROM custom_prayers cp
LEFT JOIN users u ON u.id = cp.created_by
WHERE " . implode(' AND ', $where) . "
ORDER BY (cp.is_global=1 AND u.role='superadmin') DESC, cp.name ASC
";
$st = $pdo->prepare($sql);
$st->execute($params);
echo json_encode($st->fetchAll());
exit;
}
// ─────────────────────────────────────────────────
// POST — create prayer
// ─────────────────────────────────────────────────
if ($method === 'POST') {
$body = json_decode(file_get_contents('php://input'), true);
if (!$body) json_err('Invalid JSON');
$name = trim($body['name'] ?? '');
$leader = trim($body['leader_text'] ?? '');
$all = trim($body['all_text'] ?? '');
$global = $is_admin ? (int)!empty($body['is_global']) : 0;
$bead_type = in_array($body['default_bead_type'] ?? '', ['small','large','crucifix'])
? $body['default_bead_type'] : null;
if ($name === '') json_err('Prayer name is required');
$st = $pdo->prepare(
"INSERT INTO custom_prayers (name, leader_text, all_text, default_bead_type, is_global, created_by)
VALUES (?, ?, ?, ?, ?, ?)"
);
$st->execute([$name, $leader, $all, $bead_type, $global, $uid]);
$new_id = (int)$pdo->lastInsertId();
$row = $pdo->prepare("
SELECT cp.id, cp.name, cp.leader_text, cp.all_text,
cp.default_bead_type, cp.is_global, cp.created_by,
u.role AS creator_role,
IF(cp.is_global=1 AND u.role='superadmin', 'standard',
IF(cp.is_global=1, 'global', 'mine')) AS source_tag
FROM custom_prayers cp LEFT JOIN users u ON u.id = cp.created_by
WHERE cp.id = ?
");
$row->execute([$new_id]);
echo json_encode(['created' => true, 'prayer' => $row->fetch()]);
exit;
}
// ─────────────────────────────────────────────────
// PUT — update prayer
// ─────────────────────────────────────────────────
if ($method === 'PUT') {
$id = (int)($_GET['id'] ?? 0);
$body = json_decode(file_get_contents('php://input'), true);
if (!$id || !$body) json_err('Invalid request');
$st = $pdo->prepare("SELECT * FROM custom_prayers WHERE id = ?");
$st->execute([$id]);
$prayer = $st->fetch();
if (!$prayer) json_err('Prayer not found', 404);
$can_edit = $is_admin || (int)$prayer['created_by'] === $uid;
if (!$can_edit) json_err('Access denied', 403);
$name = trim($body['name'] ?? $prayer['name']);
$leader = trim($body['leader_text'] ?? $prayer['leader_text']);
$all = trim($body['all_text'] ?? $prayer['all_text']);
$global = $is_admin ? (int)!empty($body['is_global']) : (int)$prayer['is_global'];
$bead_type = array_key_exists('default_bead_type', $body)
? (in_array($body['default_bead_type'], ['small','large','crucifix']) ? $body['default_bead_type'] : null)
: $prayer['default_bead_type'];
if ($name === '') json_err('Prayer name is required');
$pdo->prepare(
"UPDATE custom_prayers SET name=?, leader_text=?, all_text=?, default_bead_type=?, is_global=?, updated_at=NOW()
WHERE id=?"
)->execute([$name, $leader, $all, $bead_type, $global, $id]);
$row = $pdo->prepare("
SELECT cp.id, cp.name, cp.leader_text, cp.all_text,
cp.default_bead_type, cp.is_global, cp.created_by,
u.role AS creator_role,
IF(cp.is_global=1 AND u.role='superadmin', 'standard',
IF(cp.is_global=1, 'global', 'mine')) AS source_tag
FROM custom_prayers cp LEFT JOIN users u ON u.id = cp.created_by
WHERE cp.id = ?
");
$row->execute([$id]);
echo json_encode(['updated' => true, 'prayer' => $row->fetch()]);
exit;
}
// ─────────────────────────────────────────────────
// DELETE — remove prayer
// ─────────────────────────────────────────────────
if ($method === 'DELETE') {
$id = (int)($_GET['id'] ?? 0);
if (!$id) json_err('Missing id');
$st = $pdo->prepare("SELECT * FROM custom_prayers WHERE id = ?");
$st->execute([$id]);
$prayer = $st->fetch();
if (!$prayer) json_err('Prayer not found', 404);
$can_delete = $is_admin || (int)$prayer['created_by'] === $uid;
if (!$can_delete) json_err('Access denied', 403);
// Prevent deleting if used in builder_steps
$st2 = $pdo->prepare("SELECT COUNT(*) FROM builder_steps WHERE prayer_id = ?");
$st2->execute([$id]);
if ((int)$st2->fetchColumn() > 0) {
json_err('Cannot delete: this prayer is used in one or more sessions. Remove it from those sessions first.');
}
$pdo->prepare("DELETE FROM custom_prayers WHERE id = ?")->execute([$id]);
echo json_encode(['deleted' => true]);
exit;
}
json_err('Method not allowed', 405);