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:
1 parent
91ec95a4a9
commit
242c5165e1
21 files changed
+665
-73
No files matched your search
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/../inc/auth.php';
|
||||
require_once __DIR__ . '/../inc/assets.php';
|
||||
require_once __DIR__ . '/../inc/users.php';
|
||||
|
||||
// Any signed-in user can change their own username and/or password here,
|
||||
// whatever their role. Any change requires the current password.
|
||||
require_auth();
|
||||
$user = get_logged_in_user();
|
||||
$userId = (int) $user['id'];
|
||||
|
||||
$errorMsg = '';
|
||||
|
||||
function account_post_str(string $key): string {
|
||||
return is_string($_POST[$key] ?? null) ? $_POST[$key] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves whichever of username / password changed, after checking the
|
||||
* current password once. Returns an error message, or null on success.
|
||||
*/
|
||||
function handle_update_account(int $userId, array $user): ?string {
|
||||
$username = trim(account_post_str('username'));
|
||||
$newPassword = account_post_str('new_password');
|
||||
$usernameChanged = $username !== $user['username'];
|
||||
$passwordChanged = $newPassword !== '';
|
||||
|
||||
if (!verify_user_password($userId, account_post_str('current_password'))) {
|
||||
return 'Your current password is incorrect.';
|
||||
}
|
||||
if (!$usernameChanged && !$passwordChanged) {
|
||||
return 'Nothing to change — edit your username or enter a new password.';
|
||||
}
|
||||
|
||||
// Validate everything before saving anything, so a bad password
|
||||
// doesn't leave a half-applied username change behind.
|
||||
if ($usernameChanged) {
|
||||
if ($error = validate_username($username)) {
|
||||
return $error;
|
||||
}
|
||||
if (username_exists($username, $userId)) {
|
||||
return 'That username is already taken.';
|
||||
}
|
||||
}
|
||||
if ($passwordChanged) {
|
||||
if (strlen($newPassword) < MIN_PASSWORD_LENGTH) {
|
||||
return 'New password must be at least ' . MIN_PASSWORD_LENGTH . ' characters.';
|
||||
}
|
||||
if ($newPassword !== account_post_str('confirm_password')) {
|
||||
return 'New passwords do not match.';
|
||||
}
|
||||
}
|
||||
|
||||
if ($usernameChanged) {
|
||||
update_user($userId, $username, $user['role']);
|
||||
$_SESSION['admin_username'] = $username;
|
||||
}
|
||||
if ($passwordChanged) {
|
||||
set_user_password($userId, $newPassword);
|
||||
// New session ID after a credential change, so any copy of the old
|
||||
// session cookie stops working.
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
if (!verify_csrf_token(account_post_str('csrf_token'))) {
|
||||
$errorMsg = 'Session expired or invalid security token. Please try again.';
|
||||
} else {
|
||||
$errorMsg = handle_update_account($userId, $user) ?? '';
|
||||
}
|
||||
|
||||
if ($errorMsg === '') {
|
||||
header('Location: account.php?saved=1');
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
$justSaved = !$_POST && isset($_GET['saved']);
|
||||
$isAdmin = ($user['role'] ?? '') === 'admin';
|
||||
// After a failed save, keep the username they typed in the field.
|
||||
$usernameValue = $_POST ? trim(account_post_str('username')) : $user['username'];
|
||||
?>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>My Account | The Old Fitz Admin</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,600;1,9..144,400&family=Karla:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="../styles.css<?= asset_version('styles.css') ?>">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<nav class="admin-nav">
|
||||
<div class="container admin-nav-inner">
|
||||
<a href="index.php" class="admin-brand">
|
||||
<img src="../assets/knot.png" alt="" class="knot">
|
||||
<span>The Old Fitz Admin</span>
|
||||
</a>
|
||||
<div class="admin-nav-links">
|
||||
<a href="index.php">Announcements</a>
|
||||
<a href="menu.php">Menu</a>
|
||||
<?php if ($isAdmin): ?>
|
||||
<a href="users.php">Users</a>
|
||||
<?php endif; ?>
|
||||
<a href="hours.php">Hours</a>
|
||||
</div>
|
||||
<div class="admin-user">
|
||||
<a href="../" target="_blank" rel="noopener">View Public Site ↗</a>
|
||||
<a href="account.php" class="admin-account-link active" title="My Account"><?= htmlspecialchars($user['username']) ?></a>
|
||||
<a href="logout.php">Sign Out</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main class="dashboard-layout">
|
||||
<div class="container">
|
||||
<div class="dash-header">
|
||||
<p class="eyebrow">Account</p>
|
||||
<h1>My Account</h1>
|
||||
</div>
|
||||
|
||||
<?php if ($errorMsg !== ''): ?>
|
||||
<div class="alert-error" role="alert"><?= htmlspecialchars($errorMsg) ?></div>
|
||||
<?php elseif ($justSaved): ?>
|
||||
<div class="alert-success" role="status">Account updated.</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="panel account-panel">
|
||||
<div class="panel-head">
|
||||
<h2>
|
||||
<span>👤 Account Details</span>
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<p class="muted">Role: <?= htmlspecialchars(ucfirst((string) $user['role'])) ?></p>
|
||||
|
||||
<form method="POST" action="account.php">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(get_csrf_token()) ?>">
|
||||
|
||||
<div class="form-grid">
|
||||
<div class="form-group">
|
||||
<label for="account-username">Username</label>
|
||||
<input type="text" id="account-username" name="username" class="form-control" autocomplete="username" value="<?= htmlspecialchars($usernameValue) ?>" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="account-current">Current Password</label>
|
||||
<input type="password" id="account-current" name="current_password" class="form-control" autocomplete="current-password" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="account-new">New Password</label>
|
||||
<input type="password" id="account-new" name="new_password" class="form-control" autocomplete="new-password" minlength="<?= MIN_PASSWORD_LENGTH ?>">
|
||||
<p class="muted field-hint">Leave blank to keep your current password.</p>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="account-confirm">Confirm New Password</label>
|
||||
<input type="password" id="account-confirm" name="confirm_password" class="form-control" autocomplete="new-password" minlength="<?= MIN_PASSWORD_LENGTH ?>">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary">Save Changes</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+3
-1
@@ -87,12 +87,14 @@ $justSaved = !$_POST && isset($_GET['saved']);
|
||||
<div class="admin-nav-links">
|
||||
<a href="index.php">Announcements</a>
|
||||
<a href="menu.php">Menu</a>
|
||||
<?php if (($user['role'] ?? '') === 'admin'): ?>
|
||||
<a href="users.php">Users</a>
|
||||
<?php endif; ?>
|
||||
<a href="hours.php" class="active">Hours</a>
|
||||
</div>
|
||||
<div class="admin-user">
|
||||
<span>Logged in as <strong><?= htmlspecialchars($user['username']) ?></strong></span>
|
||||
<a href="../" target="_blank" rel="noopener">View Public Site ↗</a>
|
||||
<a href="account.php" class="admin-account-link" title="My Account"><?= htmlspecialchars($user['username']) ?></a>
|
||||
<a href="logout.php">Sign Out</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -32,3 +32,13 @@ document.addEventListener('submit', async (e) => {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Asks before submitting any form marked .js-confirm-submit (e.g. delete),
|
||||
// using the message in its data-confirm attribute.
|
||||
document.addEventListener('submit', (e) => {
|
||||
const form = e.target;
|
||||
if (!form.classList.contains('js-confirm-submit')) return;
|
||||
if (!confirm(form.dataset.confirm || 'Are you sure?')) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
+4
-2
@@ -122,12 +122,14 @@ $announcements = get_all_announcements();
|
||||
<div class="admin-nav-links">
|
||||
<a href="index.php" class="active">Announcements</a>
|
||||
<a href="menu.php">Menu</a>
|
||||
<?php if (($user['role'] ?? '') === 'admin'): ?>
|
||||
<a href="users.php">Users</a>
|
||||
<?php endif; ?>
|
||||
<a href="hours.php">Hours</a>
|
||||
</div>
|
||||
<div class="admin-user">
|
||||
<span>Logged in as <strong><?= htmlspecialchars($user['username']) ?></strong></span>
|
||||
<a href="../" target="_blank" rel="noopener">View Public Site ↗</a>
|
||||
<a href="account.php" class="admin-account-link" title="My Account"><?= htmlspecialchars($user['username']) ?></a>
|
||||
<a href="logout.php">Sign Out</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -219,7 +221,7 @@ $announcements = get_all_announcements();
|
||||
<div class="action-stack">
|
||||
<a href="index.php?edit=<?= (int)$ann['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
|
||||
|
||||
<form method="POST" action="index.php" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this announcement?');">
|
||||
<form method="POST" action="index.php" style="display: inline;" class="js-confirm-submit" data-confirm="Are you sure you want to delete this announcement?">
|
||||
<input type="hidden" name="action" value="delete_announcement">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(get_csrf_token()) ?>">
|
||||
<input type="hidden" name="announcement_id" value="<?= (int)$ann['id'] ?>">
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Login page: show/hide password toggle. Both icons are in the markup;
|
||||
// this just flips which one is hidden, so no HTML is built in JS.
|
||||
|
||||
const btn = document.getElementById('btn-toggle-login-password');
|
||||
const input = document.getElementById('password');
|
||||
|
||||
if (btn && input) {
|
||||
const eyeOpen = btn.querySelector('.js-eye-open');
|
||||
const eyeOff = btn.querySelector('.js-eye-off');
|
||||
|
||||
btn.addEventListener('click', () => {
|
||||
const show = input.type === 'password';
|
||||
input.type = show ? 'text' : 'password';
|
||||
btn.setAttribute('aria-label', show ? 'Hide password' : 'Show password');
|
||||
eyeOpen.hidden = show;
|
||||
eyeOff.hidden = !show;
|
||||
input.focus();
|
||||
});
|
||||
}
|
||||
+23
-21
@@ -1,17 +1,26 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../inc/auth.php';
|
||||
require_once __DIR__ . '/../inc/login-throttle.php';
|
||||
require_once __DIR__ . '/../inc/assets.php';
|
||||
|
||||
$error = '';
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$username = $_POST['username'] ?? '';
|
||||
$password = $_POST['password'] ?? '';
|
||||
$username = is_string($_POST['username'] ?? null) ? $_POST['username'] : '';
|
||||
$password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
|
||||
$ip = client_ip();
|
||||
$throttleKey = strtolower(trim($username));
|
||||
$lockSeconds = login_lock_seconds($ip, $throttleKey);
|
||||
|
||||
if (authenticate_user($username, $password)) {
|
||||
if ($lockSeconds > 0) {
|
||||
http_response_code(429);
|
||||
$error = 'Too many failed attempts. Try again in ' . (int) ceil($lockSeconds / 60) . ' minute(s).';
|
||||
} elseif (authenticate_user($username, $password)) {
|
||||
clear_login_failures($ip, $throttleKey);
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
} else {
|
||||
record_login_failure($ip, $throttleKey);
|
||||
$error = 'Invalid username or password.';
|
||||
}
|
||||
}
|
||||
@@ -49,10 +58,20 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
<div class="password-input-wrap">
|
||||
<input type="password" id="password" name="password" class="form-input" required autocomplete="current-password">
|
||||
<button type="button" class="password-toggle-btn" aria-label="Show password" id="btn-toggle-login-password">
|
||||
<span class="js-eye-open">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye">
|
||||
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
</span>
|
||||
<span class="js-eye-off" hidden>
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye-off">
|
||||
<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24" />
|
||||
<path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68" />
|
||||
<path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61" />
|
||||
<line x1="2" y1="2" x2="22" y2="22" />
|
||||
</svg>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -62,23 +81,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
<a href="../" class="back-link">← Return to Pub Website</a>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
var btn = document.getElementById('btn-toggle-login-password');
|
||||
var input = document.getElementById('password');
|
||||
if (!btn || !input) return;
|
||||
|
||||
var eyeOpen = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>';
|
||||
var eyeOff = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye-off"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>';
|
||||
|
||||
btn.addEventListener('click', function() {
|
||||
var isPassword = input.type === 'password';
|
||||
input.type = isPassword ? 'text' : 'password';
|
||||
btn.setAttribute('aria-label', isPassword ? 'Hide password' : 'Show password');
|
||||
btn.innerHTML = isPassword ? eyeOff : eyeOpen;
|
||||
input.focus();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="login.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
+3
-1
@@ -201,12 +201,14 @@ $menuEnabled = is_menu_enabled();
|
||||
<div class="admin-nav-links">
|
||||
<a href="index.php">Announcements</a>
|
||||
<a href="menu.php" class="active">Menu</a>
|
||||
<?php if (($user['role'] ?? '') === 'admin'): ?>
|
||||
<a href="users.php">Users</a>
|
||||
<?php endif; ?>
|
||||
<a href="hours.php">Hours</a>
|
||||
</div>
|
||||
<div class="admin-user">
|
||||
<span>Logged in as <strong><?= htmlspecialchars($user['username']) ?></strong></span>
|
||||
<a href="../" target="_blank" rel="noopener">View Public Site ↗</a>
|
||||
<a href="account.php" class="admin-account-link" title="My Account"><?= htmlspecialchars($user['username']) ?></a>
|
||||
<a href="logout.php">Sign Out</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+87
-3
@@ -7,6 +7,7 @@ const currentUserId = document.body.dataset.currentUserId;
|
||||
|
||||
const userModal = document.getElementById('modal-user-backdrop');
|
||||
const passwordModal = document.getElementById('modal-password-backdrop');
|
||||
const editModal = document.getElementById('modal-edit-backdrop');
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
@@ -54,11 +55,19 @@ function openUserModal() {
|
||||
form.reset();
|
||||
resetPasswordVisibility(form);
|
||||
userModal.classList.add('is-open');
|
||||
document.getElementById('user-field-username').focus();
|
||||
}
|
||||
|
||||
// Safari ignores autocomplete="off" on fields labeled "Username" and offers
|
||||
// saved logins whenever one has focus. The modals used to auto-focus that
|
||||
// field, and a closed modal left it focused, so the prompt kept popping up.
|
||||
// Now nothing is auto-focused, and closing a modal drops focus.
|
||||
function closeModal(modal) {
|
||||
modal.classList.remove('is-open');
|
||||
if (modal.contains(document.activeElement)) document.activeElement.blur();
|
||||
}
|
||||
|
||||
function closeUserModal() {
|
||||
userModal.classList.remove('is-open');
|
||||
closeModal(userModal);
|
||||
}
|
||||
|
||||
// Change Password modal
|
||||
@@ -80,9 +89,76 @@ function openPasswordModal(userId, username) {
|
||||
}
|
||||
|
||||
function closePasswordModal() {
|
||||
passwordModal.classList.remove('is-open');
|
||||
closeModal(passwordModal);
|
||||
}
|
||||
|
||||
// Edit User modal
|
||||
function openEditModal(userId, username, role) {
|
||||
const isSelf = String(userId) === currentUserId;
|
||||
const form = document.getElementById('form-edit');
|
||||
const roleSelect = document.getElementById('edit-field-role');
|
||||
|
||||
form.reset();
|
||||
document.getElementById('edit-field-user-id').value = userId;
|
||||
document.getElementById('edit-field-username').value = username;
|
||||
roleSelect.value = role;
|
||||
roleSelect.disabled = isSelf;
|
||||
document.getElementById('edit-role-self-hint').hidden = !isSelf;
|
||||
|
||||
editModal.classList.add('is-open');
|
||||
}
|
||||
|
||||
function closeEditModal() {
|
||||
closeModal(editModal);
|
||||
}
|
||||
|
||||
function capitalize(text) {
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
|
||||
// Updates an existing row's text and data attributes in place after an edit.
|
||||
function updateUserRow(user) {
|
||||
const row = document.getElementById(`user-row-${user.id}`);
|
||||
if (!row) return;
|
||||
|
||||
row.querySelector('[data-label="Username"] strong').textContent = user.username;
|
||||
row.querySelector('[data-label="Role"]').textContent = capitalize(user.role);
|
||||
row.querySelectorAll('.btn-edit-user, .btn-change-password').forEach((btn) => {
|
||||
btn.dataset.username = user.username;
|
||||
});
|
||||
row.querySelector('.btn-edit-user').dataset.role = user.role;
|
||||
|
||||
if (String(user.id) === currentUserId) {
|
||||
const navName = document.querySelector('.admin-account-link');
|
||||
if (navName) navName.textContent = user.username;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('btn-close-edit-modal').addEventListener('click', closeEditModal);
|
||||
document.getElementById('btn-cancel-edit').addEventListener('click', closeEditModal);
|
||||
|
||||
document.getElementById('form-edit').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const saveBtn = document.getElementById('btn-save-edit');
|
||||
saveBtn.disabled = true;
|
||||
saveBtn.textContent = 'Saving...';
|
||||
|
||||
try {
|
||||
const res = await postForm(new FormData(e.target));
|
||||
if (res.success) {
|
||||
closeEditModal();
|
||||
updateUserRow(res.user);
|
||||
} else {
|
||||
alert(res.error || 'Failed to update user.');
|
||||
}
|
||||
} catch {
|
||||
alert('Network error. Please try again.');
|
||||
} finally {
|
||||
saveBtn.disabled = false;
|
||||
saveBtn.textContent = 'Save Changes';
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('btn-new-user').addEventListener('click', () => openUserModal());
|
||||
document.getElementById('btn-close-user-modal').addEventListener('click', closeUserModal);
|
||||
document.getElementById('btn-cancel-user').addEventListener('click', closeUserModal);
|
||||
@@ -184,6 +260,11 @@ document.getElementById('users-rows').addEventListener('click', async (e) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.classList.contains('btn-edit-user')) {
|
||||
openEditModal(target.dataset.id, target.dataset.username, target.dataset.role);
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.classList.contains('btn-change-password')) {
|
||||
openPasswordModal(target.dataset.id, target.dataset.username);
|
||||
return;
|
||||
@@ -236,11 +317,14 @@ function insertUserRow(user) {
|
||||
<div data-label="Role">${escapeHtml(user.role.charAt(0).toUpperCase() + user.role.slice(1))}</div>
|
||||
<div class="font-mono timestamp-cell" data-label="Created">${escapeHtml(user.created_at)}</div>
|
||||
<div data-label="Actions"><div class="row-actions"><div class="action-stack">
|
||||
<button type="button" class="btn btn-outline btn-sm btn-edit-user" data-id="${user.id}">Edit</button>
|
||||
<button type="button" class="btn btn-outline btn-sm btn-change-password" data-id="${user.id}">Change Password</button>
|
||||
<button type="button" class="btn btn-danger btn-sm btn-delete-user" data-id="${user.id}">Delete</button>
|
||||
</div></div></div>
|
||||
`;
|
||||
row.querySelector('.btn-change-password').dataset.username = user.username;
|
||||
row.querySelector('.btn-edit-user').dataset.username = user.username;
|
||||
row.querySelector('.btn-edit-user').dataset.role = user.role;
|
||||
|
||||
rowsContainer.appendChild(row);
|
||||
}
|
||||
+92
-26
@@ -5,16 +5,15 @@ require_once __DIR__ . '/../inc/auth.php';
|
||||
require_once __DIR__ . '/../inc/assets.php';
|
||||
require_once __DIR__ . '/../inc/users.php';
|
||||
|
||||
require_auth();
|
||||
// User management is admin-only. Other pages don't check roles yet —
|
||||
// what manager and staff can do is still to be decided with the owner.
|
||||
require_role('admin');
|
||||
$user = get_logged_in_user();
|
||||
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
// Role is a label only right now — every account has identical access
|
||||
// regardless of what's stored here. This just keeps the value to a known,
|
||||
// displayable set instead of trusting arbitrary POST input.
|
||||
// Keeps the stored role to a known set instead of trusting arbitrary POST
|
||||
// input. Anything unrecognized falls back to the least-privileged role.
|
||||
const ALLOWED_ROLES = ['admin', 'manager', 'staff'];
|
||||
const DEFAULT_ROLE = 'admin';
|
||||
const DEFAULT_ROLE = 'staff';
|
||||
|
||||
/**
|
||||
* Safely read a trimmed string from a POST payload, guarding against
|
||||
@@ -30,19 +29,6 @@ function post_role(array $data): string {
|
||||
return in_array($role, ALLOWED_ROLES, true) ? $role : DEFAULT_ROLE;
|
||||
}
|
||||
|
||||
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 handle_create_user(array $post, array $currentUser): array {
|
||||
$username = post_str($post, 'username');
|
||||
$password = post_str($post, 'password');
|
||||
@@ -65,6 +51,42 @@ function handle_create_user(array $post, array $currentUser): array {
|
||||
return ['success' => true, 'user' => get_user_by_id($newId)];
|
||||
}
|
||||
|
||||
function handle_edit_user(array $post, array $currentUser): array {
|
||||
$targetId = (int) ($post['user_id'] ?? 0);
|
||||
$target = $targetId > 0 ? get_user_by_id($targetId) : null;
|
||||
if (!$target) {
|
||||
return ['success' => false, 'error' => 'User not found.'];
|
||||
}
|
||||
|
||||
$username = post_str($post, 'username');
|
||||
$isSelf = $targetId === (int) $currentUser['id'];
|
||||
|
||||
if ($error = validate_username($username)) {
|
||||
return ['success' => false, 'error' => $error];
|
||||
}
|
||||
if (username_exists($username, $targetId)) {
|
||||
return ['success' => false, 'error' => 'That username is already taken.'];
|
||||
}
|
||||
|
||||
// You can't change your own role: an admin demoting themselves could
|
||||
// leave nobody able to manage users. Another admin has to do it.
|
||||
if ($isSelf) {
|
||||
$role = $target['role'];
|
||||
} else {
|
||||
$role = post_str($post, 'role');
|
||||
if (!in_array($role, ALLOWED_ROLES, true)) {
|
||||
return ['success' => false, 'error' => 'Invalid role.'];
|
||||
}
|
||||
}
|
||||
|
||||
update_user($targetId, $username, $role);
|
||||
if ($isSelf) {
|
||||
$_SESSION['admin_username'] = $username;
|
||||
}
|
||||
|
||||
return ['success' => true, 'user' => get_user_by_id($targetId)];
|
||||
}
|
||||
|
||||
function handle_change_password(array $post, array $currentUser): array {
|
||||
$targetId = (int) ($post['user_id'] ?? 0);
|
||||
$target = $targetId > 0 ? get_user_by_id($targetId) : null;
|
||||
@@ -139,6 +161,7 @@ function handle_delete_user(array $post, array $currentUser): array {
|
||||
function handle_users_action(string $action, array $post, array $currentUser): array {
|
||||
return match ($action) {
|
||||
'create_user' => handle_create_user($post, $currentUser),
|
||||
'edit_user' => handle_edit_user($post, $currentUser),
|
||||
'change_password' => handle_change_password($post, $currentUser),
|
||||
'toggle_user_enabled' => handle_toggle_user_enabled($post, $currentUser),
|
||||
'delete_user' => handle_delete_user($post, $currentUser),
|
||||
@@ -192,8 +215,8 @@ $users = get_all_users();
|
||||
<a href="hours.php">Hours</a>
|
||||
</div>
|
||||
<div class="admin-user">
|
||||
<span>Logged in as <strong><?= htmlspecialchars($user['username']) ?></strong></span>
|
||||
<a href="../" target="_blank" rel="noopener">View Public Site ↗</a>
|
||||
<a href="account.php" class="admin-account-link" title="My Account"><?= htmlspecialchars($user['username']) ?></a>
|
||||
<a href="logout.php">Sign Out</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -252,6 +275,12 @@ $users = get_all_users();
|
||||
<div data-label="Actions">
|
||||
<div class="row-actions">
|
||||
<div class="action-stack">
|
||||
<button type="button" class="btn btn-outline btn-sm btn-edit-user"
|
||||
data-id="<?= (int) $row['id'] ?>"
|
||||
data-username="<?= htmlspecialchars($row['username']) ?>"
|
||||
data-role="<?= htmlspecialchars($row['role']) ?>">
|
||||
Edit
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline btn-sm btn-change-password"
|
||||
data-id="<?= (int) $row['id'] ?>"
|
||||
data-username="<?= htmlspecialchars($row['username']) ?>">
|
||||
@@ -297,13 +326,13 @@ $users = get_all_users();
|
||||
<option value="manager">Manager</option>
|
||||
<option value="staff">Staff</option>
|
||||
</select>
|
||||
<p class="muted field-hint">For your own reference only — every account has the same access.</p>
|
||||
<p class="muted field-hint">Only admins can manage users. Other permissions are still to be decided.</p>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="user-field-password">Password</label>
|
||||
<div class="password-input-wrap">
|
||||
<input type="password" id="user-field-password" name="password" class="form-control" autocomplete="new-password" minlength="8" required>
|
||||
<input type="password" id="user-field-password" name="password" class="form-control" autocomplete="new-password" minlength="<?= MIN_PASSWORD_LENGTH ?>" required>
|
||||
<button type="button" class="password-toggle-btn" aria-label="Show password" data-target="user-field-password">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye">
|
||||
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
|
||||
@@ -316,7 +345,7 @@ $users = get_all_users();
|
||||
<div class="form-group">
|
||||
<label for="user-field-confirm">Confirm Password</label>
|
||||
<div class="password-input-wrap">
|
||||
<input type="password" id="user-field-confirm" name="confirm_password" class="form-control" autocomplete="new-password" minlength="8" required>
|
||||
<input type="password" id="user-field-confirm" name="confirm_password" class="form-control" autocomplete="new-password" minlength="<?= MIN_PASSWORD_LENGTH ?>" required>
|
||||
<button type="button" class="password-toggle-btn" aria-label="Show password" data-target="user-field-confirm">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye">
|
||||
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
|
||||
@@ -335,6 +364,43 @@ $users = get_all_users();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Backdrop: Edit User -->
|
||||
<div class="admin-modal-backdrop" id="modal-edit-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-edit-title">
|
||||
<div class="admin-modal">
|
||||
<div class="modal-header">
|
||||
<h2 id="modal-edit-title">✏️ Edit User</h2>
|
||||
<button type="button" class="modal-close" aria-label="Close dialog" id="btn-close-edit-modal">×</button>
|
||||
</div>
|
||||
<form id="form-edit">
|
||||
<input type="hidden" name="action" value="edit_user">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars(get_csrf_token()) ?>">
|
||||
<input type="hidden" name="user_id" id="edit-field-user-id" value="0">
|
||||
|
||||
<div class="form-grid">
|
||||
<div class="form-group full-width">
|
||||
<label for="edit-field-username">Username</label>
|
||||
<input type="text" id="edit-field-username" name="username" class="form-control" autocomplete="off" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group full-width">
|
||||
<label for="edit-field-role">Role</label>
|
||||
<select id="edit-field-role" name="role" class="form-control">
|
||||
<option value="admin">Admin</option>
|
||||
<option value="manager">Manager</option>
|
||||
<option value="staff">Staff</option>
|
||||
</select>
|
||||
<p class="muted field-hint" id="edit-role-self-hint" hidden>You can't change your own role. Another admin has to do it.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary" id="btn-save-edit">Save Changes</button>
|
||||
<button type="button" class="btn btn-outline" id="btn-cancel-edit">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Backdrop: Change Password -->
|
||||
<div class="admin-modal-backdrop" id="modal-password-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-password-title">
|
||||
<div class="admin-modal">
|
||||
@@ -364,7 +430,7 @@ $users = get_all_users();
|
||||
<div class="form-group">
|
||||
<label for="password-field-new">New Password</label>
|
||||
<div class="password-input-wrap">
|
||||
<input type="password" id="password-field-new" name="new_password" class="form-control" autocomplete="new-password" minlength="8" required>
|
||||
<input type="password" id="password-field-new" name="new_password" class="form-control" autocomplete="new-password" minlength="<?= MIN_PASSWORD_LENGTH ?>" required>
|
||||
<button type="button" class="password-toggle-btn" aria-label="Show password" data-target="password-field-new">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye">
|
||||
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
|
||||
@@ -377,7 +443,7 @@ $users = get_all_users();
|
||||
<div class="form-group">
|
||||
<label for="password-field-confirm">Confirm New Password</label>
|
||||
<div class="password-input-wrap">
|
||||
<input type="password" id="password-field-confirm" name="confirm_password" class="form-control" autocomplete="new-password" minlength="8" required>
|
||||
<input type="password" id="password-field-confirm" name="confirm_password" class="form-control" autocomplete="new-password" minlength="<?= MIN_PASSWORD_LENGTH ?>" required>
|
||||
<button type="button" class="password-toggle-btn" aria-label="Show password" data-target="password-field-confirm">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" class="icon-eye">
|
||||
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" />
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Require all denied
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CLI-only: create an admin account.
|
||||
*
|
||||
* Replaces the old admin/password seed in inc/db.php. Run inside the
|
||||
* container as www-data, so a newly created fitz.sqlite isn't owned by root:
|
||||
* docker exec -it -u www-data the-old-fitz php /var/www/html/bin/create-user.php
|
||||
*/
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/../inc/users.php';
|
||||
|
||||
function prompt(string $label, bool $hidden = false): string {
|
||||
fwrite(STDOUT, $label);
|
||||
if ($hidden) {
|
||||
shell_exec('stty -echo');
|
||||
}
|
||||
$value = fgets(STDIN);
|
||||
if ($hidden) {
|
||||
shell_exec('stty echo');
|
||||
fwrite(STDOUT, PHP_EOL);
|
||||
}
|
||||
return trim((string) $value);
|
||||
}
|
||||
|
||||
$username = prompt('Username: ');
|
||||
if ($username === '') {
|
||||
fwrite(STDERR, "Username is required.\n");
|
||||
exit(1);
|
||||
}
|
||||
if (username_exists($username)) {
|
||||
fwrite(STDERR, "User '$username' already exists.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$password = prompt('Password (' . MIN_PASSWORD_LENGTH . '+ chars): ', true);
|
||||
if (strlen($password) < MIN_PASSWORD_LENGTH) {
|
||||
fwrite(STDERR, 'Password must be at least ' . MIN_PASSWORD_LENGTH . " characters.\n");
|
||||
exit(1);
|
||||
}
|
||||
if (prompt('Confirm password: ', true) !== $password) {
|
||||
fwrite(STDERR, "Passwords don't match.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$id = create_user($username, $password, 'admin');
|
||||
fwrite(STDOUT, "Created admin '$username' (id $id).\n");
|
||||
+39
-7
@@ -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
@@ -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
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
"dev": "concurrently --kill-others-on-fail \"npm:dev:php\" \"npm:dev:sass\" \"npm:dev:browser\"",
|
||||
"dev:php": "php -S localhost:8000",
|
||||
"dev:sass": "sass --watch --source-map src/scss/styles.scss:styles.css",
|
||||
"dev:browser": "browser-sync start --proxy http://localhost:8000 --files \"*.php,admin/**/*.php,inc/**/*.php,main.js,styles.css\" --no-open",
|
||||
"dev:browser": "browser-sync start --proxy http://localhost:8000 --files \"*.php,admin/**/*.php,inc/**/*.php,main.js,styles.css\" --no-open --no-ui",
|
||||
"build:sass": "sass --no-source-map src/scss/styles.scss:styles.css",
|
||||
"dist": "npm run build:sass && node scripts/build-dist.js"
|
||||
},
|
||||
|
||||
@@ -28,7 +28,7 @@ const FILES = [
|
||||
'config.php', // holds the live FB_PAGE_ACCESS_TOKEN — see README before sharing dist/ anywhere but the server
|
||||
];
|
||||
|
||||
const DIRS = ['admin', 'assets', 'inc'];
|
||||
const DIRS = ['admin', 'assets', 'bin', 'inc'];
|
||||
|
||||
function copyDir(src, dest) {
|
||||
fs.cpSync(src, dest, {
|
||||
|
||||
@@ -11,12 +11,19 @@
|
||||
padding: 1.5rem;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity .2s ease;
|
||||
// Closed modals must be visibility: hidden, not just transparent —
|
||||
// otherwise their fields stay focusable and Safari offers saved logins
|
||||
// for an invisible Username field. The visibility switch waits for the
|
||||
// fade-out to finish so the close animation still plays.
|
||||
visibility: hidden;
|
||||
transition: opacity .2s ease, visibility 0s linear .2s;
|
||||
}
|
||||
|
||||
.admin-modal-backdrop.is-open {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
visibility: visible;
|
||||
transition: opacity .2s ease, visibility 0s;
|
||||
}
|
||||
|
||||
.admin-modal {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/* ---------- admin: my account ---------- */
|
||||
/* One panel, fields in the shared two-column .form-grid (which already
|
||||
stacks below 47.5em). Capped so the fields don't stretch across the
|
||||
full dashboard width on large screens. */
|
||||
.account-panel {
|
||||
max-width: 56rem;
|
||||
}
|
||||
@@ -31,3 +31,4 @@
|
||||
@use "pages/admin-login";
|
||||
@use "pages/admin-menu";
|
||||
@use "pages/admin-hours";
|
||||
@use "pages/admin-account";
|
||||
+13
-1
@@ -797,12 +797,15 @@ button.status-badge:disabled {
|
||||
padding: 1.5rem;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s ease;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.2s ease, visibility 0s linear 0.2s;
|
||||
}
|
||||
|
||||
.admin-modal-backdrop.is-open {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
visibility: visible;
|
||||
transition: opacity 0.2s ease, visibility 0s;
|
||||
}
|
||||
|
||||
.admin-modal {
|
||||
@@ -2166,3 +2169,12 @@ footer a.email:hover {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
/* ---------- admin: my account ---------- */
|
||||
/* One panel, fields in the shared two-column .form-grid (which already
|
||||
stacks below 47.5em). Capped so the fields don't stretch across the
|
||||
full dashboard width on large screens. */
|
||||
.account-panel {
|
||||
max-width: 56rem;
|
||||
}
|
||||
|
||||
/*# sourceMappingURL=styles.css.map */
|
||||
Reference in new issue
Block a user