LuminaWebsite/includes/discord_auth.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

174 lines
6.6 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/discord.php';
/**
* Discord-Login, Kontoanlage und Abgleich der Berechtigungsgruppen mit den Discord-Rollen.
*
* Berechtigungsgruppen mit hinterlegter Discord-Rolle (roles.discord_role_id) werden
* vollstaendig von Discord gesteuert: wer die Rolle hat, ist drin, wer sie nicht (mehr)
* hat, fliegt raus. Gruppen ohne Discord-Rolle bleiben unangetastet und werden weiter von
* Hand vergeben. Hat jemand mehrere verknuepfte Rollen (z.B. Sedes Lumines und Lumina
* Ascendens), bekommt er alle zugehoerigen Gruppen - die Rechte addieren sich.
*/
// Wie oft waehrend einer Sitzung neu bei Discord nachgefragt wird (Sekunden).
const DISCORD_SYNC_INTERVAL = 300;
function discord_store_tokens(int $userId, ?array $tokens): void
{
db()->prepare(
'UPDATE users SET discord_access_token = ?, discord_refresh_token = ?, discord_token_expires = ? WHERE id = ?'
)->execute([
$tokens['access_token'] ?? null,
$tokens['refresh_token'] ?? null,
$tokens['expires_at'] ?? null,
$userId,
]);
}
/**
* Gleicht die Discord-gesteuerten Gruppen eines Nutzers mit seinen Discord-Rollen ab.
*
* @param array<int, string> $discordRoleIds Rollen auf dem Server ([] = nicht auf dem Server)
*/
function discord_sync_roles(int $userId, array $discordRoleIds): void
{
$linked = db()->query('SELECT id, discord_role_id FROM roles WHERE discord_role_id IS NOT NULL')->fetchAll();
if (empty($linked)) {
return;
}
$add = db()->prepare('INSERT IGNORE INTO user_roles (user_id, role_id) VALUES (?, ?)');
$remove = db()->prepare('DELETE FROM user_roles WHERE user_id = ? AND role_id = ?');
foreach ($linked as $role) {
if (in_array((string) $role['discord_role_id'], $discordRoleIds, true)) {
$add->execute([$userId, (int) $role['id']]);
} else {
$remove->execute([$userId, (int) $role['id']]);
}
}
}
/** Uebernimmt eine frisch abgefragte Mitgliedschaft: Rollen abgleichen, Zeitpunkt merken. */
function discord_apply_member(int $userId, array $member): void
{
discord_sync_roles($userId, $member['roles']);
db()->prepare('UPDATE users SET discord_synced_at = NOW() WHERE id = ?')->execute([$userId]);
}
/**
* Macht aus dem Discord-Namen einen freien Benutzernamen fuer die Website.
*/
function discord_unique_username(string $discordName): string
{
$base = strtolower(preg_replace('/[^A-Za-z0-9._-]/', '', $discordName) ?? '');
if ($base === '') {
$base = 'discord';
}
$base = substr($base, 0, 40);
$stmt = db()->prepare('SELECT 1 FROM users WHERE username = ?');
$candidate = $base;
for ($i = 2; ; $i++) {
$stmt->execute([$candidate]);
if (!$stmt->fetchColumn()) {
return $candidate;
}
$candidate = $base . '_' . $i;
}
}
/**
* Findet das Konto zu einem Discord-Account oder legt ein neues an. Neue Konten sind noch
* nicht freigeschaltet (status = pending) und koennen sich nur ueber Discord anmelden.
*
* @param array{id: string, username: string, global_name: string} $discordUser
* @param array{roles: array<int, string>, nick: string} $member
* @return array{id: int, status: string, created: bool}
*/
function discord_find_or_create_user(array $discordUser, array $member): array
{
$stmt = db()->prepare('SELECT id, status FROM users WHERE discord_id = ?');
$stmt->execute([$discordUser['id']]);
$row = $stmt->fetch();
if ($row) {
db()->prepare('UPDATE users SET discord_username = ? WHERE id = ?')
->execute([$discordUser['username'], (int) $row['id']]);
return ['id' => (int) $row['id'], 'status' => (string) $row['status'], 'created' => false];
}
// Anzeigename: Spitzname auf dem Server, sonst der globale Discord-Name.
$displayName = $member['nick'] !== '' ? $member['nick'] : ($discordUser['global_name'] ?: $discordUser['username']);
// Das Passwort kennt niemand - die Anmeldung laeuft nur ueber Discord, bis ein
// Administrator den Passwort-Login freischaltet und dabei ein Passwort setzt.
db()->prepare(
"INSERT INTO users (username, password_hash, display_name, status, must_change_password, password_login,
discord_id, discord_username)
VALUES (?, ?, ?, 'pending', 0, 0, ?, ?)"
)->execute([
discord_unique_username($discordUser['username']),
password_hash(bin2hex(random_bytes(24)), PASSWORD_DEFAULT),
mb_substr($displayName, 0, 100),
$discordUser['id'],
$discordUser['username'],
]);
return ['id' => (int) db()->lastInsertId(), 'status' => 'pending', 'created' => true];
}
/**
* Prueft waehrend einer Sitzung erneut bei Discord, ob der Nutzer noch auf dem Server ist
* und welche Rollen er hat - hoechstens alle DISCORD_SYNC_INTERVAL Sekunden.
*
* @return string ok | skipped | left (nicht mehr auf dem Server) | revoked (Token ungueltig) | error
*/
function discord_live_check(int $userId): string
{
$stmt = db()->prepare(
'SELECT discord_access_token, discord_refresh_token, discord_token_expires, discord_synced_at
FROM users WHERE id = ?'
);
$stmt->execute([$userId]);
$row = $stmt->fetch();
if (!$row || empty($row['discord_refresh_token'])) {
return 'skipped';
}
if ($row['discord_synced_at'] !== null && strtotime((string) $row['discord_synced_at']) > time() - DISCORD_SYNC_INTERVAL) {
return 'skipped';
}
// Vor dem Abfragen schon als geprueft markieren: faellt Discord aus oder greift das
// Rate-Limit, wird nicht bei jedem Seitenaufruf erneut gewartet.
db()->prepare('UPDATE users SET discord_synced_at = NOW() WHERE id = ?')->execute([$userId]);
try {
$accessToken = (string) $row['discord_access_token'];
if ($row['discord_token_expires'] === null || strtotime((string) $row['discord_token_expires']) <= time()) {
$tokens = discord_refresh_token((string) $row['discord_refresh_token']);
if ($tokens === null) {
discord_store_tokens($userId, null);
return 'revoked';
}
discord_store_tokens($userId, $tokens);
$accessToken = $tokens['access_token'];
}
$member = discord_fetch_member($accessToken);
if ($member === null) {
discord_sync_roles($userId, []);
return 'left';
}
discord_apply_member($userId, $member);
return 'ok';
} catch (Throwable $e) {
// Discord nicht erreichbar o.ae.: bisherige Gruppen bleiben, naechster Versuch spaeter.
return 'error';
}
}