LuminaWebsite/includes/discord.php
Maaxxs 1c9aa0761f Auto-refresh Discord username/avatar via OAuth refresh token
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>
2026-09-19 07:26:02 +02:00

216 lines
7.7 KiB
PHP

<?php
declare(strict_types=1);
/**
* @return array{client_id: string, client_secret: string, redirect_uri: string}
* @throws RuntimeException
*/
function discord_config(): array
{
$configPath = __DIR__ . '/../config.php';
if (!file_exists($configPath)) {
throw new RuntimeException('Konfigurationsdatei fehlt.');
}
$config = require $configPath;
$discord = $config['discord'] ?? [];
if (empty($discord['client_id']) || empty($discord['client_secret']) || empty($discord['redirect_uri'])) {
throw new RuntimeException('Discord-Login ist nicht konfiguriert (config.php: discord.client_id / client_secret / redirect_uri fehlt).');
}
return $discord;
}
/** @throws RuntimeException */
function discord_authorize_url(string $state): string
{
$config = discord_config();
$params = [
'client_id' => $config['client_id'],
'redirect_uri' => $config['redirect_uri'],
'response_type' => 'code',
'scope' => 'identify',
'state' => $state,
'prompt' => 'consent',
];
return 'https://discord.com/oauth2/authorize?' . http_build_query($params);
}
/**
* Ruft mit einem OAuth-Access-Token die Discord-Identitaet
* (ID + Benutzername + Avatar-Hash) ab.
*
* @return array{id: string, username: string, avatar: ?string}
* @throws RuntimeException
*/
function discord_fetch_user(string $accessToken): array
{
$ch = curl_init('https://discord.com/api/users/@me');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $accessToken],
CURLOPT_TIMEOUT => 10,
]);
$userResponse = curl_exec($ch);
$userHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($userResponse === false || $userHttpCode !== 200) {
throw new RuntimeException('Discord-Benutzerdaten konnten nicht abgerufen werden.');
}
$userData = json_decode($userResponse, true);
if (!is_array($userData) || empty($userData['id']) || !isset($userData['username'])) {
throw new RuntimeException('Unerwartete Antwort von Discord.');
}
return [
'id' => (string) $userData['id'],
'username' => (string) $userData['username'],
'avatar' => isset($userData['avatar']) && $userData['avatar'] !== null ? (string) $userData['avatar'] : null,
];
}
/**
* Tauscht den OAuth-Code gegen ein Access-Token und liest damit die
* Discord-Identitaet aus. Das Refresh-Token wird mitgeliefert, damit
* Benutzername/Avatar spaeter ohne erneuten Login-Dialog aktualisiert
* werden koennen (siehe discord_refresh_identity()).
*
* @return array{id: string, username: string, avatar: ?string, refresh_token: string}
* @throws RuntimeException
*/
function discord_exchange_code(string $code): array
{
if (!function_exists('curl_init')) {
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
}
$config = discord_config();
$ch = curl_init('https://discord.com/api/oauth2/token');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $config['redirect_uri'],
]),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new RuntimeException('Verbindung zu Discord fehlgeschlagen: ' . $curlError);
}
$tokenData = json_decode($response, true);
if ($httpCode !== 200 || !is_array($tokenData) || empty($tokenData['access_token'])) {
throw new RuntimeException('Discord hat den Login-Code nicht akzeptiert.');
}
$userInfo = discord_fetch_user((string) $tokenData['access_token']);
$userInfo['refresh_token'] = (string) ($tokenData['refresh_token'] ?? '');
return $userInfo;
}
/**
* Erneuert Benutzername/Avatar ueber das gespeicherte Refresh-Token, ohne dass
* der Nutzer den Discord-Login-Dialog erneut durchlaufen muss. Discord rotiert
* das Refresh-Token bei jeder Nutzung, deshalb wird das neue mit zurueckgegeben
* und muss anstelle des alten gespeichert werden.
*
* @return array{id: string, username: string, avatar: ?string, refresh_token: string}
* @throws RuntimeException
*/
function discord_refresh_identity(string $refreshToken): array
{
if (!function_exists('curl_init')) {
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
}
$config = discord_config();
$ch = curl_init('https://discord.com/api/oauth2/token');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
]),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new RuntimeException('Verbindung zu Discord fehlgeschlagen: ' . $curlError);
}
$tokenData = json_decode($response, true);
if ($httpCode !== 200 || !is_array($tokenData) || empty($tokenData['access_token'])) {
throw new RuntimeException('Discord-Token konnte nicht erneuert werden (Verknuepfung eventuell widerrufen).');
}
$userInfo = discord_fetch_user((string) $tokenData['access_token']);
$userInfo['refresh_token'] = (string) ($tokenData['refresh_token'] ?? $refreshToken);
return $userInfo;
}
/**
* Aktualisiert Benutzername/Avatar im Hintergrund per Refresh-Token, falls der
* letzte Abgleich laenger als eine Stunde her ist. Damit muessen Mitglieder
* ihre Discord-Verknuepfung nicht manuell erneuern, wenn sie ihr Profilbild
* auf Discord aendern - der naechste Aufruf von "Mein Profil" zieht es nach.
* Schlaegt der Refresh fehl (z.B. Verknuepfung auf Discord-Seite widerrufen),
* bleibt der zuletzt bekannte Stand unveraendert; es wird lediglich der
* Zeitstempel gesetzt, damit nicht bei jedem Aufruf erneut versucht wird.
*
* @param array<string, mixed> $user
*/
function discord_sync_avatar_if_stale(array &$user): void
{
if (empty($user['discord_id']) || empty($user['discord_refresh_token'])) {
return;
}
$syncedAt = $user['discord_avatar_synced_at'] ?? null;
if ($syncedAt !== null && strtotime((string) $syncedAt) > time() - 3600) {
return;
}
try {
$fresh = discord_refresh_identity((string) $user['discord_refresh_token']);
} catch (Throwable $e) {
db()->prepare('UPDATE users SET discord_avatar_synced_at = NOW() WHERE id = ?')->execute([$user['id']]);
$user['discord_avatar_synced_at'] = date('Y-m-d H:i:s');
return;
}
db()->prepare(
'UPDATE users SET discord_username = ?, discord_avatar = ?, discord_refresh_token = ?, discord_avatar_synced_at = NOW() WHERE id = ?'
)->execute([$fresh['username'], $fresh['avatar'], $fresh['refresh_token'], $user['id']]);
$user['discord_username'] = $fresh['username'];
$user['discord_avatar'] = $fresh['avatar'];
$user['discord_refresh_token'] = $fresh['refresh_token'];
$user['discord_avatar_synced_at'] = date('Y-m-d H:i:s');
}