diff --git a/README.md b/README.md index 8be473f..8eb7c4c 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,12 @@ und wird später ausgebaut. Fokus dieser Version ist der Mitglieder-/Admin-Berei für zukünftige Funktionen - Jeder Benutzer kann mehreren Berechtigungsgruppen angehören - Raids-Seite: zeigt anstehende Raid-Termine, Anforderungen, Gruppen und Anmeldungen, - bezogen von einer externen API (`config.php: raids_api`) + bezogen von einer externen API (`config.php: raids_api`), Filter Aktiv/Archiviert/Alle +- Discord-Verknüpfung: Mitglieder können ihren Discord-Account per OAuth mit ihrem + Website-Account verknüpfen (nötig, um sich über die Website zu Raids anzumelden) +- Raid-Anmeldung: verknüpfte Mitglieder können sich direkt über die Website zu einem Raid + an-/ummelden bzw. abmelden; Admins mit der Berechtigung `raids.manage` können Raids + archivieren/wiederherstellen ## Ordnerstruktur @@ -78,6 +83,46 @@ Berechtigung `raids.view` noch nicht automatisch. Leg sie einmalig unter **Berec die Raids sehen sollen (z.B. Administrator und Mitglied). Bei einer frischen Installation über `install.php` passiert das automatisch. +### Discord-Verknüpfung einrichten + +1. Discord-Application erstellen: https://discord.com/developers/applications -> **New + Application** -> unter **OAuth2 -> General** die **Client ID** und das **Client Secret** + kopieren -> unter **Redirects** exakt `https://deine-domain.de/discord_callback.php` + eintragen und speichern. +2. In `config.php` ergänzen: + ```php + 'discord' => [ + 'client_id' => 'deine-discord-client-id', + 'client_secret' => 'dein-discord-client-secret', + 'redirect_uri' => 'https://deine-domain.de/discord_callback.php', + ], + ``` +3. Falls die Datenbank schon vor diesem Update existierte, fehlen die Spalten `discord_id` und + `discord_username`: + ```sql + ALTER TABLE users ADD COLUMN discord_id BIGINT UNSIGNED NULL UNIQUE AFTER must_change_password; + ALTER TABLE users ADD COLUMN discord_username VARCHAR(100) NULL AFTER discord_id; + ``` + +Mitglieder verknüpfen ihren Account danach selbst über einen Button im Dashboard. + +### Raid-Anmeldung über die Website + +Damit sich Mitglieder direkt über die Website zu Raids an-/abmelden können, braucht die +Raid-Bot-API zwei zusätzliche Endpunkte (bestehen aktuell noch nicht in der API, die nur +Lesen/Archivieren/Wiederherstellen kann): + +- `POST /api/raids/{raid_id}/signup` mit Body `{"user_id": ..., "name": ..., "class": ..., "group": ...}` + (Upsert: bereits bestehende Anmeldung der gleichen `user_id` aktualisieren statt zu duplizieren) +- `DELETE /api/raids/{raid_id}/signup/{user_id}` (idempotent, auch ohne bestehende Anmeldung + `{"status": "success"}` zurückgeben) + +Sobald diese Endpunkte auf Bot-Seite existieren, funktionieren die Anmelden-/Abmelden-Buttons auf +der Raids-Seite automatisch. Archivieren/Wiederherstellen funktionieren bereits jetzt, da die API +das schon unterstützt. Zusätzlich gibt es die neue Berechtigung `raids.manage`, die genauso wie +`raids.view` nachträglich unter Berechtigungsgruppen angelegt/zugewiesen werden muss, falls dein +Account vor diesem Update installiert wurde. + ## Berechtigungskonzept - **Berechtigungen** sind einzelne Schlüssel wie `users.view`, `roles.manage`, `dashboard.view`. diff --git a/assets/css/style.css b/assets/css/style.css index 9c2afd2..abf0e76 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -403,6 +403,24 @@ input:focus, select:focus, textarea:focus { .panel-archived { opacity: 0.7; } +.raid-signup-note { + margin-top: 1rem; + padding-top: 1rem; + border-top: 1px solid var(--border); +} + +.raid-signup-form { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin-top: 1rem; + padding-top: 1rem; + border-top: 1px solid var(--border); +} + +.raid-signup-form select { width: auto; } + .filter-tabs { display: flex; flex-wrap: wrap; diff --git a/config.example.php b/config.example.php index 8b49bb8..091db47 100644 --- a/config.example.php +++ b/config.example.php @@ -17,4 +17,9 @@ return [ 'url' => 'https://api.maaxxs-coding.de/api/raids', 'key' => 'dein-api-key', ], + 'discord' => [ + 'client_id' => 'deine-discord-client-id', + 'client_secret' => 'dein-discord-client-secret', + 'redirect_uri' => 'https://lumina.maaxxs-coding.de/discord_callback.php', + ], ]; diff --git a/dashboard.php b/dashboard.php index 00c1cd5..cdc803e 100644 --- a/dashboard.php +++ b/dashboard.php @@ -15,6 +15,20 @@ include __DIR__ . '/includes/header.php';

Dies ist dein Mitgliederbereich. Die eigentliche Gilden-Homepage folgt hier später.

+
+

Discord-Verknüpfung

+ +

Verknüpft als

+
+ + +
+ +

Verknüpfe deinen Discord-Account, um dich über die Website zu Raids anmelden zu können.

+ Mit Discord verknüpfen + +
+
diff --git a/discord_callback.php b/discord_callback.php new file mode 100644 index 0000000..8a9fd11 --- /dev/null +++ b/discord_callback.php @@ -0,0 +1,35 @@ +prepare('UPDATE users SET discord_id = ?, discord_username = ? WHERE id = ?'); + $stmt->execute([$discordUser['id'], $discordUser['username'], $user['id']]); + + set_flash('success', 'Discord-Account "' . $discordUser['username'] . '" wurde verknüpft.'); +} catch (PDOException $e) { + set_flash('error', 'Dieser Discord-Account ist bereits mit einem anderen Benutzer verknüpft.'); +} catch (Throwable $e) { + set_flash('error', 'Discord-Verknüpfung fehlgeschlagen: ' . $e->getMessage()); +} + +redirect('/dashboard.php'); diff --git a/discord_login.php b/discord_login.php new file mode 100644 index 0000000..2d6071d --- /dev/null +++ b/discord_login.php @@ -0,0 +1,13 @@ +getMessage()); + redirect('/dashboard.php'); +} diff --git a/discord_unlink.php b/discord_unlink.php new file mode 100644 index 0000000..29c09cc --- /dev/null +++ b/discord_unlink.php @@ -0,0 +1,14 @@ +prepare('UPDATE users SET discord_id = NULL, discord_username = NULL WHERE id = ?')->execute([$user['id']]); + +set_flash('success', 'Discord-Verknüpfung wurde entfernt.'); +redirect('/dashboard.php'); diff --git a/includes/auth.php b/includes/auth.php index ef21ecd..e9bb02f 100644 --- a/includes/auth.php +++ b/includes/auth.php @@ -15,7 +15,7 @@ function current_user(): ?array return null; } - $stmt = db()->prepare('SELECT id, username, display_name, status, must_change_password FROM users WHERE id = ?'); + $stmt = db()->prepare('SELECT id, username, display_name, status, must_change_password, discord_id, discord_username FROM users WHERE id = ?'); $stmt->execute([$_SESSION['user_id']]); $row = $stmt->fetch(); diff --git a/includes/discord.php b/includes/discord.php new file mode 100644 index 0000000..fcb6e68 --- /dev/null +++ b/includes/discord.php @@ -0,0 +1,108 @@ + $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); +} + +/** + * Tauscht den OAuth-Code gegen ein Access-Token und liest damit die + * Discord-Identitaet (ID + Benutzername) aus. + * + * @return array{id: string, username: 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.'); + } + + $ch2 = curl_init('https://discord.com/api/users/@me'); + curl_setopt_array($ch2, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $tokenData['access_token']], + CURLOPT_TIMEOUT => 10, + ]); + $userResponse = curl_exec($ch2); + $userHttpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE); + curl_close($ch2); + + 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'], + ]; +} diff --git a/includes/permissions.php b/includes/permissions.php index fe5986a..050eaca 100644 --- a/includes/permissions.php +++ b/includes/permissions.php @@ -13,6 +13,7 @@ const CORE_PERMISSIONS = [ ['key' => 'users.delete', 'description' => 'Benutzer löschen'], ['key' => 'roles.manage', 'description' => 'Berechtigungsgruppen verwalten'], ['key' => 'raids.view', 'description' => 'Raids einsehen'], + ['key' => 'raids.manage', 'description' => 'Raids archivieren/wiederherstellen'], ]; function user_has_permission(string $key): bool diff --git a/includes/raids_api.php b/includes/raids_api.php index 51141e8..769b4d0 100644 --- a/includes/raids_api.php +++ b/includes/raids_api.php @@ -4,15 +4,11 @@ declare(strict_types=1); const RAID_STATUSES = ['active', 'archived', 'all']; /** - * @return array> + * @return array * @throws RuntimeException */ -function fetch_raids(string $status = 'active'): array +function raids_api_config(): array { - if (!in_array($status, RAID_STATUSES, true)) { - $status = 'active'; - } - $configPath = __DIR__ . '/../config.php'; if (!file_exists($configPath)) { throw new RuntimeException('Konfigurationsdatei fehlt.'); @@ -26,20 +22,48 @@ function fetch_raids(string $status = 'active'): array throw new RuntimeException('Raid-API ist nicht konfiguriert (config.php: raids_api.url / raids_api.key fehlt).'); } + return ['url' => rtrim($apiUrl, '/'), 'key' => $apiKey]; +} + +/** + * Fuehrt einen Request gegen die Raid-API aus und liefert die dekodierte + * JSON-Antwort zurueck. + * + * @param string $path Wird an die Basis-URL angehaengt, z.B. "/123/signup". + * @param array|null $jsonBody Wird bei POST/DELETE als JSON-Body mitgeschickt. + * @return array + * @throws RuntimeException + */ +function raids_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null): array +{ if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } - $separator = str_contains($apiUrl, '?') ? '&' : '?'; - $requestUrl = $apiUrl . $separator . 'status=' . urlencode($status); + $config = raids_api_config(); + $url = $config['url'] . $path; + if (!empty($queryParams)) { + $url .= '?' . http_build_query($queryParams); + } - $ch = curl_init($requestUrl); - curl_setopt_array($ch, [ + $headers = ['X-API-Key: ' . $config['key']]; + + $ch = curl_init($url); + $options = [ CURLOPT_RETURNTRANSFER => true, - CURLOPT_HTTPHEADER => ['X-API-Key: ' . $apiKey], + CURLOPT_CUSTOMREQUEST => $method, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => true, - ]); + ]; + + if ($jsonBody !== null) { + $headers[] = 'Content-Type: application/json'; + $options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE); + } + + $options[CURLOPT_HTTPHEADER] = $headers; + curl_setopt_array($ch, $options); + $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); @@ -48,14 +72,69 @@ function fetch_raids(string $status = 'active'): array if ($response === false) { throw new RuntimeException('Verbindung zur Raid-API fehlgeschlagen: ' . $curlError); } - if ($httpCode !== 200) { - throw new RuntimeException('Raid-API antwortete mit Statuscode ' . $httpCode . '.'); - } $data = json_decode($response, true); - if (!is_array($data) || ($data['status'] ?? '') !== 'success' || !isset($data['raids']) || !is_array($data['raids'])) { + + if ($httpCode < 200 || $httpCode >= 300) { + $detail = is_array($data) ? ($data['detail'] ?? '') : ''; + $message = 'Raid-API antwortete mit Statuscode ' . $httpCode . '.'; + if ($detail !== '') { + $message .= ' (' . $detail . ')'; + } + throw new RuntimeException($message); + } + + if (!is_array($data)) { + throw new RuntimeException('Unerwartetes Antwortformat der Raid-API.'); + } + + return $data; +} + +/** + * @return array> + * @throws RuntimeException + */ +function fetch_raids(string $status = 'active'): array +{ + if (!in_array($status, RAID_STATUSES, true)) { + $status = 'active'; + } + + $data = raids_api_request('GET', '', ['status' => $status]); + + if (($data['status'] ?? '') !== 'success' || !isset($data['raids']) || !is_array($data['raids'])) { throw new RuntimeException('Unerwartetes Antwortformat der Raid-API.'); } return $data['raids']; } + +/** @throws RuntimeException */ +function archive_raid(int $raidId): void +{ + raids_api_request('DELETE', '/' . $raidId); +} + +/** @throws RuntimeException */ +function restore_raid(int $raidId): void +{ + raids_api_request('POST', '/' . $raidId . '/restore'); +} + +/** @throws RuntimeException */ +function raid_signup(int $raidId, int $discordId, string $discordName, string $className, int $group): void +{ + raids_api_request('POST', '/' . $raidId . '/signup', [], [ + 'user_id' => $discordId, + 'name' => $discordName, + 'class' => $className, + 'group' => $group, + ]); +} + +/** @throws RuntimeException */ +function raid_unsignup(int $raidId, int $discordId): void +{ + raids_api_request('DELETE', '/' . $raidId . '/signup/' . $discordId); +} diff --git a/raid_archive.php b/raid_archive.php new file mode 100644 index 0000000..6589172 --- /dev/null +++ b/raid_archive.php @@ -0,0 +1,29 @@ +getMessage()); +} + +redirect($redirectTo); diff --git a/raid_restore.php b/raid_restore.php new file mode 100644 index 0000000..58596e0 --- /dev/null +++ b/raid_restore.php @@ -0,0 +1,29 @@ +getMessage()); +} + +redirect($redirectTo); diff --git a/raid_signup.php b/raid_signup.php new file mode 100644 index 0000000..ab6fd11 --- /dev/null +++ b/raid_signup.php @@ -0,0 +1,39 @@ +getMessage()); +} + +redirect($redirectTo); diff --git a/raid_unsignup.php b/raid_unsignup.php new file mode 100644 index 0000000..285516c --- /dev/null +++ b/raid_unsignup.php @@ -0,0 +1,34 @@ +getMessage()); +} + +redirect($redirectTo); diff --git a/raids.php b/raids.php index 0da7a66..a296ae6 100644 --- a/raids.php +++ b/raids.php @@ -3,6 +3,12 @@ require_once __DIR__ . '/includes/bootstrap.php'; require_once __DIR__ . '/includes/raids_api.php'; require_permission('raids.view'); +$currentUser = current_user(); +$currentDiscordId = $currentUser['discord_id'] ?? null; +$canManageRaids = user_has_permission('raids.manage'); + +$classOptions = ['Gladiator', 'Templer', 'Assassine', 'Jäger', 'Magier', 'Geisterbeschwörer', 'Kleriker', 'Barde']; + $status = (string) ($_GET['status'] ?? 'active'); if (!in_array($status, RAID_STATUSES, true)) { $status = 'active'; @@ -67,9 +73,13 @@ include __DIR__ . '/includes/header.php'; $groupNames = array_values(array_filter(array_map('trim', explode(',', (string) ($raid['groups'] ?? ''))))); $signupsByGroup = []; + $mySignup = null; foreach ($signups as $signup) { $groupNumber = (int) ($signup['group'] ?? 0); $signupsByGroup[$groupNumber][] = $signup; + if ($currentDiscordId && (string) ($signup['user_id'] ?? '') === (string) $currentDiscordId) { + $mySignup = $signup; + } } ?>
@@ -80,6 +90,23 @@ include __DIR__ . '/includes/header.php'; Archiviert / angemeldet + + +
+ + + + +
+ +
+ + + + +
+ +

@@ -107,10 +134,12 @@ include __DIR__ . '/includes/header.php'; ?>
  • - + <?= e($memberClass) ?> - () + + () +
  • @@ -119,6 +148,46 @@ include __DIR__ . '/includes/header.php';
    + + +

    Dieser Raid ist archiviert – Anmeldungen sind geschlossen.

    + +

    Verknüpfe deinen Discord-Account, um dich anzumelden.

    + + +
    +

    + Du bist angemeldet als + in Gruppe . +

    +
    + + + + +
    +
    + + +
    + + + + + + +
    + + diff --git a/sql/schema.sql b/sql/schema.sql index 2150615..a4eaa17 100644 --- a/sql/schema.sql +++ b/sql/schema.sql @@ -10,6 +10,8 @@ CREATE TABLE IF NOT EXISTS users ( display_name VARCHAR(100) NOT NULL DEFAULT '', status ENUM('active', 'disabled') NOT NULL DEFAULT 'active', must_change_password TINYINT(1) NOT NULL DEFAULT 0, + discord_id BIGINT UNSIGNED NULL UNIQUE, + discord_username VARCHAR(100) NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login DATETIME NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;