New users no longer get a manually typed password: admins get a random one-time password shown once after creation, and the account is flagged must_change_password. require_login() redirects anyone with that flag to the new change_password.php page (except that page and logout) until they set their own password. Admins can also toggle the flag when editing an existing user to force a re-change. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
69 lines
1.7 KiB
PHP
69 lines
1.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
function current_user(): ?array
|
|
{
|
|
static $user = null;
|
|
static $loaded = false;
|
|
|
|
if ($loaded) {
|
|
return $user;
|
|
}
|
|
$loaded = true;
|
|
|
|
if (empty($_SESSION['user_id'])) {
|
|
return null;
|
|
}
|
|
|
|
$stmt = db()->prepare('SELECT id, username, display_name, status, must_change_password FROM users WHERE id = ?');
|
|
$stmt->execute([$_SESSION['user_id']]);
|
|
$row = $stmt->fetch();
|
|
|
|
if (!$row || $row['status'] !== 'active') {
|
|
// Benutzer wurde geloescht oder deaktiviert -> Session beenden.
|
|
session_destroy();
|
|
return null;
|
|
}
|
|
|
|
$user = $row;
|
|
return $user;
|
|
}
|
|
|
|
function require_login(): void
|
|
{
|
|
$user = current_user();
|
|
if (!$user) {
|
|
redirect('/login.php');
|
|
}
|
|
|
|
$exemptScripts = ['change_password.php', 'logout.php'];
|
|
$currentScript = basename((string) ($_SERVER['SCRIPT_NAME'] ?? ''));
|
|
if (!empty($user['must_change_password']) && !in_array($currentScript, $exemptScripts, true)) {
|
|
redirect('/change_password.php');
|
|
}
|
|
}
|
|
|
|
function attempt_login(string $username, string $password): bool
|
|
{
|
|
$stmt = db()->prepare('SELECT id, password_hash, status FROM users WHERE username = ?');
|
|
$stmt->execute([$username]);
|
|
$row = $stmt->fetch();
|
|
|
|
if (!$row || $row['status'] !== 'active' || !password_verify($password, $row['password_hash'])) {
|
|
return false;
|
|
}
|
|
|
|
session_regenerate_id(true);
|
|
$_SESSION['user_id'] = $row['id'];
|
|
|
|
$update = db()->prepare('UPDATE users SET last_login = NOW() WHERE id = ?');
|
|
$update->execute([$row['id']]);
|
|
|
|
return true;
|
|
}
|
|
|
|
function logout(): void
|
|
{
|
|
$_SESSION = [];
|
|
session_destroy();
|
|
}
|