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>
This commit is contained in:
parent
4eba8d1fef
commit
1c9aa0761f
7 changed files with 148 additions and 22 deletions
11
README.md
11
README.md
|
|
@ -116,6 +116,17 @@ ALTER TABLE users ADD COLUMN discord_avatar VARCHAR(64) NULL AFTER discord_usern
|
|||
Bereits verknüpfte Mitglieder müssen die Discord-Verknüpfung danach einmal in "Mein Profil"
|
||||
trennen und neu herstellen, damit der Avatar-Hash nachträglich gespeichert wird.
|
||||
|
||||
Falls die Datenbank schon vor dem automatischen Avatar-Abgleich existierte, fehlen zusätzlich
|
||||
`discord_refresh_token` und `discord_avatar_synced_at` (das Profilbild wird dann beim Öffnen von
|
||||
"Mein Profil" nicht automatisch aktualisiert, wenn sich das Discord-Profilbild ändert):
|
||||
```sql
|
||||
ALTER TABLE users ADD COLUMN discord_refresh_token VARCHAR(255) NULL AFTER discord_avatar;
|
||||
ALTER TABLE users ADD COLUMN discord_avatar_synced_at DATETIME NULL AFTER discord_refresh_token;
|
||||
```
|
||||
Auch hier müssen bereits verknüpfte Mitglieder die Discord-Verknüpfung einmal trennen und neu
|
||||
herstellen, damit ein Refresh-Token gespeichert wird (ohne das kann nicht automatisch aktualisiert
|
||||
werden).
|
||||
|
||||
### Raid-Anmeldung über die Website
|
||||
|
||||
Damit sich Mitglieder direkt über die Website zu Raids an-/abmelden können, braucht die
|
||||
|
|
|
|||
|
|
@ -22,8 +22,10 @@ try {
|
|||
$discordUser = discord_exchange_code($code);
|
||||
$user = current_user();
|
||||
|
||||
$stmt = db()->prepare('UPDATE users SET discord_id = ?, discord_username = ?, discord_avatar = ? WHERE id = ?');
|
||||
$stmt->execute([$discordUser['id'], $discordUser['username'], $discordUser['avatar'], $user['id']]);
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE users SET discord_id = ?, discord_username = ?, discord_avatar = ?, discord_refresh_token = ?, discord_avatar_synced_at = NOW() WHERE id = ?'
|
||||
);
|
||||
$stmt->execute([$discordUser['id'], $discordUser['username'], $discordUser['avatar'], $discordUser['refresh_token'], $user['id']]);
|
||||
|
||||
set_flash('success', 'Discord-Account "' . $discordUser['username'] . '" wurde verknüpft.');
|
||||
} catch (PDOException $e) {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|||
verify_csrf();
|
||||
|
||||
$user = current_user();
|
||||
db()->prepare('UPDATE users SET discord_id = NULL, discord_username = NULL, discord_avatar = NULL WHERE id = ?')->execute([$user['id']]);
|
||||
db()->prepare(
|
||||
'UPDATE users SET discord_id = NULL, discord_username = NULL, discord_avatar = NULL, discord_refresh_token = NULL, discord_avatar_synced_at = NULL WHERE id = ?'
|
||||
)->execute([$user['id']]);
|
||||
|
||||
set_flash('success', 'Discord-Verknüpfung wurde entfernt.');
|
||||
redirect('/dashboard.php');
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ function current_user(): ?array
|
|||
return null;
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT id, username, display_name, status, must_change_password, discord_id, discord_username, discord_avatar FROM users WHERE id = ?');
|
||||
$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();
|
||||
|
||||
|
|
|
|||
|
|
@ -40,12 +40,49 @@ function discord_authorize_url(string $state): string
|
|||
}
|
||||
|
||||
/**
|
||||
* Tauscht den OAuth-Code gegen ein Access-Token und liest damit die
|
||||
* Discord-Identitaet (ID + Benutzername + Avatar-Hash) aus.
|
||||
* 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')) {
|
||||
|
|
@ -82,28 +119,98 @@ function discord_exchange_code(string $code): array
|
|||
throw new RuntimeException('Discord hat den Login-Code nicht akzeptiert.');
|
||||
}
|
||||
|
||||
$ch2 = curl_init('https://discord.com/api/users/@me');
|
||||
curl_setopt_array($ch2, [
|
||||
$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_HTTPHEADER => ['Authorization: Bearer ' . $tokenData['access_token']],
|
||||
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,
|
||||
]);
|
||||
$userResponse = curl_exec($ch2);
|
||||
$userHttpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch2);
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($userResponse === false || $userHttpCode !== 200) {
|
||||
throw new RuntimeException('Discord-Benutzerdaten konnten nicht abgerufen werden.');
|
||||
if ($response === false) {
|
||||
throw new RuntimeException('Verbindung zu Discord fehlgeschlagen: ' . $curlError);
|
||||
}
|
||||
|
||||
$userData = json_decode($userResponse, true);
|
||||
if (!is_array($userData) || empty($userData['id']) || !isset($userData['username'])) {
|
||||
throw new RuntimeException('Unerwartete Antwort von Discord.');
|
||||
$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).');
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => (string) $userData['id'],
|
||||
'username' => (string) $userData['username'],
|
||||
'avatar' => isset($userData['avatar']) && $userData['avatar'] !== null ? (string) $userData['avatar'] : null,
|
||||
];
|
||||
$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');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/includes/bootstrap.php';
|
||||
require_once __DIR__ . '/includes/discord.php';
|
||||
require_login();
|
||||
|
||||
$user = current_user();
|
||||
discord_sync_avatar_if_stale($user);
|
||||
$profileError = null;
|
||||
$passwordError = null;
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ CREATE TABLE IF NOT EXISTS users (
|
|||
discord_id BIGINT UNSIGNED NULL UNIQUE,
|
||||
discord_username VARCHAR(100) NULL,
|
||||
discord_avatar VARCHAR(64) NULL,
|
||||
discord_refresh_token VARCHAR(255) NULL,
|
||||
discord_avatar_synced_at DATETIME NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login DATETIME NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
|
|
|||
Loading…
Reference in a new issue