Previously the stored Discord identity only updated when a member manually unlinked and relinked their account, so a changed Discord avatar never showed up. The OAuth exchange now also captures the refresh_token; discord_sync_avatar_if_stale() uses it to silently pull the current username/avatar (throttled to once per hour) and is called from profile.php, so opening "Mein Profil" keeps it current without any re-consent flow. Adds discord_refresh_token and discord_avatar_synced_at columns. 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, discord_id, discord_username, discord_avatar, discord_refresh_token, discord_avatar_synced_at FROM users WHERE id = ?');
|
|
$stmt->execute([$_SESSION['user_id']]);
|
|
$row = $stmt->fetch();
|
|
|
|
if (!$row || $row['status'] !== 'active') {
|
|
// Benutzer wurde gelöscht 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();
|
|
}
|