LuminaWebsite/includes/discord.php
Maaxxs 01719dd958 Login: Discord first, pending approval, groups synced from Discord roles
The login page leads with "Mit Discord einloggen"; username/password stays
available below and can be allowed or refused per user. The Discord login
asks for identify + guilds.members.read, so the site itself can check that
the account is on the legion's server and read its roles - no bot token on
the webspace. Unknown accounts get a new user in the new status "pending",
Discord-only, who sees nothing but a "Freischaltung ausstehend" page and has
no permissions until approved from the user list.

Permission groups can be linked to a Discord role. Linked groups are granted
and revoked from the member's roles at every Discord login and then every
five minutes during a session, using the stored (refreshed) user token;
leaving the server removes them and ends a Discord session. Manual groups are
untouched, and several linked roles simply add up their groups.

New columns are added automatically on first request (includes/schema.php),
since the login page itself needs them; existing accounts keep password login.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 07:49:47 +02:00

226 lines
7.7 KiB
PHP

<?php
declare(strict_types=1);
/**
* Discord-OAuth fuer Login und Verknuepfung.
*
* Scopes: "identify" (wer ist das) und "guilds.members.read" (ist er auf dem Legions-Server,
* welche Rollen hat er dort). Mit dem zweiten laesst sich die Mitgliedschaft ueber das Token
* des Nutzers selbst pruefen - die Website braucht dafuer keinen Bot-Token.
*/
const DISCORD_API = 'https://discord.com/api/v10';
const DISCORD_SCOPES = 'identify guilds.members.read';
/**
* @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;
}
/**
* Der Discord-Server der Legion. Eigene Angabe unter discord.guild_id, sonst derselbe Server
* wie fuer Raids/Reports/Events (raids_api.guild_id).
*
* @throws RuntimeException
*/
function discord_guild_id(): string
{
$config = require __DIR__ . '/../config.php';
$guildId = $config['discord']['guild_id'] ?? $config['raids_api']['guild_id'] ?? null;
if (!$guildId) {
throw new RuntimeException('Der Discord-Server ist nicht konfiguriert (config.php: discord.guild_id oder raids_api.guild_id).');
}
return (string) $guildId;
}
/** @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' => DISCORD_SCOPES,
'state' => $state,
// Wer schon einmal zugestimmt hat, wird ohne erneute Rueckfrage direkt zurueckgeschickt.
'prompt' => 'none',
];
return 'https://discord.com/oauth2/authorize?' . http_build_query($params);
}
/**
* Ein HTTP-Aufruf gegen Discord. Liefert Statuscode und dekodierte Antwort.
*
* @return array{status: int, data: mixed}
* @throws RuntimeException bei Verbindungsfehlern
*/
function discord_http(string $method, string $url, array $headers = [], ?array $form = null): array
{
if (!function_exists('curl_init')) {
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
}
$ch = curl_init($url);
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => $headers,
];
if ($form !== null) {
$options[CURLOPT_POSTFIELDS] = http_build_query($form);
$options[CURLOPT_HTTPHEADER][] = 'Content-Type: application/x-www-form-urlencoded';
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
if ($response === false) {
throw new RuntimeException('Verbindung zu Discord fehlgeschlagen: ' . $error);
}
return ['status' => $status, 'data' => json_decode((string) $response, true)];
}
/**
* Wandelt eine Token-Antwort von Discord in das Format um, das in users gespeichert wird.
*
* @return array{access_token: string, refresh_token: string, expires_at: string}
*/
function discord_token_row(array $data): array
{
// Eine Minute Puffer, damit ein Token nicht mitten in einer Anfrage ablaeuft.
$expiresIn = max(60, (int) ($data['expires_in'] ?? 604800) - 60);
return [
'access_token' => (string) $data['access_token'],
'refresh_token' => (string) ($data['refresh_token'] ?? ''),
'expires_at' => date('Y-m-d H:i:s', time() + $expiresIn),
];
}
/**
* Tauscht den OAuth-Code nach dem Login gegen ein Token.
*
* @return array{access_token: string, refresh_token: string, expires_at: string}
* @throws RuntimeException
*/
function discord_exchange_code(string $code): array
{
$config = discord_config();
$result = discord_http('POST', DISCORD_API . '/oauth2/token', [], [
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $config['redirect_uri'],
]);
if ($result['status'] !== 200 || empty($result['data']['access_token'])) {
throw new RuntimeException('Discord hat den Login-Code nicht akzeptiert.');
}
return discord_token_row($result['data']);
}
/**
* Holt mit dem Refresh-Token ein neues Access-Token. Null, wenn Discord das Token nicht
* mehr annimmt (z.B. weil der Nutzer die App in Discord entfernt hat) - dann muss er sich
* neu anmelden.
*
* @return array{access_token: string, refresh_token: string, expires_at: string}|null
* @throws RuntimeException bei Verbindungs- oder Serverfehlern
*/
function discord_refresh_token(string $refreshToken): ?array
{
$config = discord_config();
$result = discord_http('POST', DISCORD_API . '/oauth2/token', [], [
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
]);
// Nur "invalid_grant" heisst wirklich: Token widerrufen/abgelaufen. Andere Fehler (etwa
// ein falsches Client-Secret in config.php) sollen nicht alle Nutzer abmelden.
if ($result['status'] === 400 && ($result['data']['error'] ?? '') === 'invalid_grant') {
return null;
}
if ($result['status'] !== 200 || empty($result['data']['access_token'])) {
throw new RuntimeException('Discord-Token konnte nicht erneuert werden (Status ' . $result['status'] . ').');
}
return discord_token_row($result['data']);
}
/**
* Der Discord-Account hinter einem Token.
*
* @return array{id: string, username: string, global_name: string}
* @throws RuntimeException
*/
function discord_fetch_user(string $accessToken): array
{
$result = discord_http('GET', DISCORD_API . '/users/@me', ['Authorization: Bearer ' . $accessToken]);
$data = $result['data'];
if ($result['status'] !== 200 || !is_array($data) || empty($data['id'])) {
throw new RuntimeException('Discord-Benutzerdaten konnten nicht abgerufen werden.');
}
return [
'id' => (string) $data['id'],
'username' => (string) ($data['username'] ?? ''),
'global_name' => (string) ($data['global_name'] ?? ''),
];
}
/**
* Die Mitgliedschaft auf dem Legions-Server: Rollen-IDs und Server-Spitzname. Null, wenn
* der Account nicht auf dem Server ist.
*
* @return array{roles: array<int, string>, nick: string}|null
* @throws RuntimeException bei Verbindungsfehlern, abgelaufenem Token oder Rate-Limit
*/
function discord_fetch_member(string $accessToken): ?array
{
$result = discord_http(
'GET',
DISCORD_API . '/users/@me/guilds/' . rawurlencode(discord_guild_id()) . '/member',
['Authorization: Bearer ' . $accessToken]
);
// 404 "Unknown Guild": der Account ist nicht (mehr) auf dem Server.
if ($result['status'] === 404) {
return null;
}
if ($result['status'] !== 200 || !is_array($result['data'])) {
throw new RuntimeException('Discord-Mitgliedschaft konnte nicht geprüft werden (Status ' . $result['status'] . ').');
}
return [
'roles' => array_map('strval', (array) ($result['data']['roles'] ?? [])),
'nick' => (string) ($result['data']['nick'] ?? ''),
];
}