rinkplanner/hub/app/pages.php
torsten 055a2919c3 feat: Kür-Hub mit Einladungen, Uploads und API
- PHP-App unter hub/ für rinkplanner-hub.programmschmiede.de
- MariaDB-Schema, Argon2id, Sessions, CSRF und Ratenbegrenzung
- Einladungscodes, Admin-Bereich und Kür-Pakete mit Audiodatei
- JSON-API v1 mit Bearer-Tokens für die Godot-App
- Deployment und Erstinstallation über tools/deploy_hub.sh
- Doku und Credentials-Vorlage ergänzt
2026-11-11 13:14:26 +01:00

729 lines
24 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/** Web-Oberfläche: Routen, Formulare und Admin-Seiten. */
const HUB_RESERVED_USERNAMES = [
'admin', 'administrator', 'root', 'system', 'support', 'moderator',
'rinkplanner', 'hub', 'team', 'test', 'guest', 'gast',
];
function page_handle(string $method, string $path): void
{
$path = '/' . trim($path, '/');
if (!in_array($method, ['GET', 'POST'], true)) {
abort_page(405, 'Diese Methode ist nicht erlaubt.');
}
if ($path === '/health') {
health_check();
return;
}
$user = auth_user();
if ($user !== null && $user['must_change_password'] === 1
&& !in_array($path, ['/account', '/account/password', '/logout'], true)
) {
flash('info', 'Bitte zuerst das Passwort ändern.');
redirect('/account');
}
if ($path === '/login') {
page_login($method);
return;
}
if ($path === '/register') {
page_register($method);
return;
}
if ($path === '/logout') {
if ($method !== 'POST' || !csrf_valid()) {
redirect('/');
}
auth_logout();
flash('success', 'Abgemeldet.');
redirect('/login');
}
if ($path === '/') {
page_dashboard($method);
return;
}
if ($path === '/upload') {
page_upload($method);
return;
}
if ($path === '/account') {
page_account($method);
return;
}
if ($path === '/account/password') {
page_account_password($method);
return;
}
if ($path === '/account/tokens') {
page_account_token_create($method);
return;
}
if ($path === '/account/tokens/revoke') {
page_account_token_revoke($method);
return;
}
if ($path === '/admin/invites') {
page_admin_invites($method);
return;
}
if ($path === '/admin/invites/revoke') {
page_admin_invite_revoke($method);
return;
}
if ($path === '/admin/users') {
page_admin_users($method);
return;
}
if ($path === '/admin/users/action') {
page_admin_user_action($method);
return;
}
if ($path === '/admin/routines') {
page_admin_routines($method);
return;
}
if ($path === '/admin/routines/action') {
page_admin_routine_action($method);
return;
}
if ($path === '/admin/audit') {
require_admin_page();
render_page('admin_audit', ['entries' => audit_list(200)], 'Audit-Log');
return;
}
if (preg_match('#^/routines/(\d+)$#', $path, $matches) === 1) {
page_routine_detail((int) $matches[1], $method);
return;
}
if (preg_match('#^/routines/(\d+)/(download|audio)$#', $path, $matches) === 1) {
page_routine_file((int) $matches[1], (string) $matches[2]);
return;
}
if (preg_match('#^/routines/(\d+)/revise$#', $path, $matches) === 1) {
page_routine_revise((int) $matches[1], $method);
return;
}
if (preg_match('#^/routines/(\d+)/(hide|publish)$#', $path, $matches) === 1) {
page_routine_status((int) $matches[1], (string) $matches[2], $method);
return;
}
abort_page(404, 'Diese Seite gibt es nicht.');
}
function health_check(): void
{
try {
db()->query('SELECT 1');
header('Content-Type: text/plain; charset=utf-8');
echo "ok\n";
} catch (Throwable) {
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo "db error\n";
}
}
function require_admin_page(): array
{
return auth_require_admin();
}
function page_login(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$error = '';
$login = '';
$next = auth_next_url('/');
if ($method === 'POST') {
csrf_require();
$login = post_string('login');
$password = (string) ($_POST['password'] ?? '');
$result = auth_attempt($login, $password);
if ($result['ok']) {
auth_login($result['user'], isset($_POST['remember']));
redirect(auth_next_url($next));
}
$error = (string) $result['error'];
if (($result['retry'] ?? 0) > 0) {
http_response_code(429);
header('Retry-After: ' . (int) $result['retry']);
}
}
render_page('login', [
'error' => $error,
'login' => $login,
'next' => $next,
], 'Anmelden');
}
function username_error(string $username): ?string
{
if (mb_strlen($username, 'UTF-8') < 3 || mb_strlen($username, 'UTF-8') > 32) {
return 'Der Benutzername muss 3 bis 32 Zeichen lang sein.';
}
if (preg_match('/^[a-z0-9](?:[a-z0-9._-]{1,30}[a-z0-9])$/u', $username) !== 1) {
return 'Nur Kleinbuchstaben, Ziffern, Punkt, Bindestrich und Unterstrich; Anfang und Ende alphanumerisch.';
}
if (in_array($username, HUB_RESERVED_USERNAMES, true)) {
return 'Dieser Benutzername ist reserviert.';
}
return null;
}
function page_register(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$invite = null;
$code = '';
$errors = [];
$input = [
'username' => '',
'display_name' => '',
'email' => '',
];
if ($method === 'GET') {
$code = query_string('code');
$invite = invite_find_valid($code);
if ($invite !== null && !empty($invite['email'])) {
$input['email'] = (string) $invite['email'];
}
} else {
csrf_require();
$code = post_string('code');
$invite = invite_find_valid($code);
$input['username'] = mb_strtolower(post_string('username'));
$input['display_name'] = post_string('display_name');
$input['email'] = post_string('email');
if ($invite === null) {
$errors[] = 'Dieser Einladungscode ist ungültig, abgelaufen oder bereits eingelöst.';
} elseif (!empty($invite['email']) && $input['email'] === '') {
$input['email'] = (string) $invite['email'];
}
$usernameError = username_error($input['username']);
if ($usernameError !== null) {
$errors[] = $usernameError;
}
if ($input['display_name'] === '') {
$input['display_name'] = $input['username'];
}
if (mb_strlen($input['display_name'], 'UTF-8') > 64) {
$errors[] = 'Der Anzeigename darf höchstens 64 Zeichen lang sein.';
}
if ($input['email'] !== '' && filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Die E-Mail-Adresse ist nicht gültig.';
}
if ($invite !== null && !empty($invite['email'])
&& strcasecmp((string) $invite['email'], $input['email']) !== 0
) {
$errors[] = 'Diese Einladung ist an eine andere E-Mail-Adresse gebunden.';
}
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['password_repeat'] ?? '');
$policy = password_policy_error($password, $input['username']);
if ($policy !== null) {
$errors[] = $policy;
}
if ($password !== $repeat) {
$errors[] = 'Die Passwortwiederholung passt nicht.';
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = 'Bitte die Beta-Regeln akzeptieren.';
}
if (!$errors && $invite !== null) {
$pdo = db();
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare(
'INSERT INTO users
(username, display_name, email, password_hash, role, status,
must_change_password, auth_epoch, created_at, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?, 0, 1, ?, ?)'
);
$now = utc_now();
$stmt->execute([
$input['username'],
$input['display_name'],
$input['email'] !== '' ? $input['email'] : null,
hash_password($password),
'user',
'active',
$now,
$now,
]);
$newId = (int) $pdo->lastInsertId();
if (!invite_consume((int) $invite['id'], $newId)) {
$pdo->rollBack();
$errors[] = 'Der Einladungscode wurde gerade eingelöst. Bitte einen neuen Code anfordern.';
} else {
audit('invite.use', 'invite', (int) $invite['id'], $input['username'], $newId);
audit('user.register', 'user', $newId, $input['username'], $newId);
$pdo->commit();
}
} catch (PDOException $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
if (str_contains($exception->getMessage(), 'uq_users_username')) {
$errors[] = 'Dieser Benutzername ist schon vergeben.';
} elseif (str_contains($exception->getMessage(), 'uq_users_email')) {
$errors[] = 'Diese E-Mail-Adresse ist schon registriert.';
} else {
throw $exception;
}
}
if (!$errors) {
$user = auth_user_by_id($newId);
if ($user !== null) {
auth_login($user);
flash('success', 'Willkommen im Kür-Hub!');
redirect('/');
}
}
}
}
render_page('register', [
'invite' => $invite,
'code' => $code,
'errors' => $errors,
'input' => $input,
], 'Registrieren');
}
function page_dashboard(string $method): void
{
$user = auth_require_login();
$query = query_string('q');
$page = max(1, query_int('page', 1));
$mine = query_string('mine') === '1';
$result = routines_query($query, $page, 20, $mine ? (int) $user['id'] : null, $mine);
render_page('dashboard', [
'items' => $result['items'],
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
'query' => $query,
'mine' => $mine,
], 'Küren');
}
function page_routine_detail(int $id, string $method): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_view($routine, $user)) {
abort_page(403, 'Diese Kür ist nicht freigegeben.');
}
render_page('routine', [
'routine' => $routine,
'can_edit' => routine_can_edit($routine, $user),
'is_admin' => auth_is_admin($user),
], $routine['title']);
}
function page_routine_file(int $id, string $kind): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_view($routine, $user)) {
abort_page(403, 'Diese Kür ist nicht freigegeben.');
}
routine_send_file($routine, $kind);
}
function page_upload(string $method): void
{
$user = auth_require_login();
$errors = [];
$input = [
'description' => '',
'music_title' => '',
'music_artist' => '',
];
if ($method === 'POST') {
csrf_require();
if (!routine_upload_quota_ok((int) $user['id'])) {
$errors[] = 'Stündliches Upload-Limit erreicht. Bitte später erneut versuchen.';
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = 'Bitte bestätigen, dass du Kür und Musik teilen darfst.';
}
if (!$errors) {
$package = routine_validate_package($_POST);
if (!$package['ok']) {
$errors = $package['errors'];
} else {
$duplicate = routine_duplicate_exists((int) $user['id'], $package);
if ($duplicate !== null) {
flash('info', 'Diese Kür ist bereits im Hub.');
redirect('/routines/' . $duplicate);
}
try {
$routineId = routine_create((int) $user['id'], $package);
flash('success', 'Kür veröffentlicht.');
redirect('/routines/' . $routineId);
} catch (Throwable $error) {
hub_log('Upload fehlgeschlagen: ' . $error->getMessage());
$errors[] = 'Die Kür konnte nicht gespeichert werden.';
}
}
}
$input['description'] = post_string('description');
$input['music_title'] = post_string('music_title');
$input['music_artist'] = post_string('music_artist');
}
render_page('upload', [
'errors' => $errors,
'input' => $input,
'routine' => null,
], 'Kür hochladen');
}
function page_routine_revise(int $id, string $method): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_edit($routine, $user)) {
abort_page(403, 'Nur der Eigentümer oder ein Admin kann diese Kür ändern.');
}
$errors = [];
$input = [
'description' => (string) ($routine['description'] ?? ''),
'music_title' => (string) ($routine['music_title'] ?? ''),
'music_artist' => (string) ($routine['music_artist'] ?? ''),
];
if ($method === 'POST') {
csrf_require();
if (!routine_upload_quota_ok((int) $user['id'])) {
$errors[] = 'Stündliches Upload-Limit erreicht. Bitte später erneut versuchen.';
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = 'Bitte bestätigen, dass du Kür und Musik teilen darfst.';
}
if (!$errors) {
$package = routine_validate_package($_POST);
if (!$package['ok']) {
$errors = $package['errors'];
} else {
try {
$revision = routine_add_revision($id, (int) $user['id'], $package);
flash('success', 'Neue Revision ' . $revision . ' gespeichert.');
redirect('/routines/' . $id);
} catch (Throwable $error) {
hub_log('Revision fehlgeschlagen: ' . $error->getMessage());
$errors[] = 'Die Revision konnte nicht gespeichert werden.';
}
}
}
$input['description'] = post_string('description');
$input['music_title'] = post_string('music_title');
$input['music_artist'] = post_string('music_artist');
}
render_page('upload', [
'errors' => $errors,
'input' => $input,
'routine' => $routine,
], 'Neue Revision');
}
function page_routine_status(int $id, string $action, string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/routines/' . $id);
}
csrf_require();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_edit($routine, $user)) {
abort_page(403, 'Nur der Eigentümer oder ein Admin kann diese Kür ändern.');
}
$status = $action === 'publish' ? 'published' : 'hidden';
routine_set_status($id, $status);
flash('success', $status === 'published' ? 'Kür ist wieder sichtbar.' : 'Kür wurde aus dem Hub genommen.');
redirect('/routines/' . $id);
}
function page_account(string $method): void
{
$user = auth_require_login();
render_page('account', [
'tokens' => tokens_list((int) $user['id']),
], 'Konto');
}
function page_account_password(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$current = (string) ($_POST['current_password'] ?? '');
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['password_repeat'] ?? '');
$errors = [];
if (!password_verify($current, (string) $user['password_hash'])) {
$errors[] = 'Das aktuelle Passwort ist falsch.';
}
$policy = password_policy_error($password, (string) $user['username']);
if ($policy !== null) {
$errors[] = $policy;
}
if ($password !== $repeat) {
$errors[] = 'Die Passwortwiederholung passt nicht.';
}
if ($errors) {
foreach ($errors as $error) {
flash('error', $error);
}
redirect('/account');
}
db()->prepare(
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0 WHERE id = ?'
)->execute([hash_password($password), utc_now(), (int) $user['id']]);
auth_revoke_sessions((int) $user['id']);
audit('user.password_change', 'user', (int) $user['id']);
flash('success', 'Passwort geändert. Andere Sitzungen wurden abgemeldet.');
redirect('/account');
}
function page_account_token_create(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$name = post_string('name');
if ($name === '') {
$name = 'App';
}
$created = token_create((int) $user['id'], $name);
flash_secret('Neuer API-Token – jetzt kopieren, er wird nicht erneut angezeigt', $created['token']);
redirect('/account');
}
function page_account_token_revoke(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$tokenId = (int) post_string('token_id');
if (token_revoke($tokenId, (int) $user['id'])) {
audit('token.revoke', 'token', $tokenId);
flash('success', 'Token widerrufen.');
} else {
flash('error', 'Token nicht gefunden.');
}
redirect('/account');
}
function page_admin_invites(string $method): void
{
$admin = require_admin_page();
if ($method === 'POST') {
csrf_require();
$note = post_string('note');
$email = post_string('email');
$days = (int) post_string('expires_days', '30');
$errors = [];
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Die E-Mail-Adresse ist nicht gültig.';
}
if ($errors) {
foreach ($errors as $error) {
flash('error', $error);
}
} else {
$code = invite_create($note, $email, $days, (int) $admin['id']);
$publicUrl = rtrim((string) config('app.public_url', ''), '/');
$link = $publicUrl . '/register?code=' . rawurlencode($code);
flash_secret('Einladungscode', $code . ' – Link: ' . $link);
flash('success', 'Einladung erstellt.');
}
redirect('/admin/invites');
}
render_page('admin_invites', [
'invites' => invites_list(),
], 'Einladungen');
}
function page_admin_invite_revoke(string $method): void
{
require_admin_page();
if ($method !== 'POST') {
redirect('/admin/invites');
}
csrf_require();
$inviteId = (int) post_string('invite_id');
if (invite_revoke($inviteId)) {
audit('invite.revoke', 'invite', $inviteId);
flash('success', 'Einladung widerrufen.');
} else {
flash('error', 'Einladung konnte nicht widerrufen werden.');
}
redirect('/admin/invites');
}
function page_admin_users(string $method): void
{
require_admin_page();
$users = db()->query(
'SELECT u.*, (SELECT COUNT(*) FROM routines r WHERE r.owner_id = u.id) AS routine_count
FROM users u ORDER BY u.created_at DESC, u.id DESC'
)->fetchAll();
render_page('admin_users', ['users' => $users], 'Benutzer');
}
function page_admin_user_action(string $method): void
{
$admin = require_admin_page();
if ($method !== 'POST') {
redirect('/admin/users');
}
csrf_require();
$targetId = (int) post_string('user_id');
$action = post_string('action');
$target = auth_user_by_id($targetId);
if ($target === null) {
flash('error', 'Benutzer nicht gefunden.');
redirect('/admin/users');
}
if ($targetId === (int) $admin['id']) {
flash('error', 'Das eigene Konto lässt sich hier nicht ändern.');
redirect('/admin/users');
}
if ($action === 'disable') {
db()->prepare("UPDATE users SET status = 'disabled' WHERE id = ?")->execute([$targetId]);
auth_revoke_sessions($targetId);
audit('user.disable', 'user', $targetId, (string) $target['username']);
flash('success', 'Benutzer deaktiviert.');
} elseif ($action === 'enable') {
db()->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$targetId]);
audit('user.enable', 'user', $targetId, (string) $target['username']);
flash('success', 'Benutzer aktiviert.');
} elseif ($action === 'reset') {
$alphabet = HUB_INVITE_ALPHABET;
$temp = '';
for ($i = 0; $i < 12; $i++) {
$temp .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
db()->prepare(
'UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = ? WHERE id = ?'
)->execute([hash_password($temp), utc_now(), $targetId]);
auth_revoke_sessions($targetId);
audit('user.password_reset', 'user', $targetId, (string) $target['username']);
flash_secret('Temporäres Passwort für ' . $target['username'], $temp);
flash('info', 'Der Benutzer muss das Passwort bei der nächsten Anmeldung ändern.');
} elseif ($action === 'delete') {
if (($_POST['confirm'] ?? '') !== '1') {
flash('error', 'Löschen muss bestätigt werden.');
redirect('/admin/users');
}
$stmt = db()->prepare('SELECT id FROM routines WHERE owner_id = ?');
$stmt->execute([$targetId]);
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $routineId) {
routine_delete((int) $routineId);
}
db()->prepare('UPDATE invites SET revoked_at = ? WHERE used_by = ? AND revoked_at IS NULL')
->execute([utc_now(), $targetId]);
audit('user.delete', 'user', $targetId, (string) $target['username']);
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$targetId]);
flash('success', 'Benutzer und zugehörige Küren gelöscht.');
} else {
flash('error', 'Unbekannte Aktion.');
}
redirect('/admin/users');
}
function page_admin_routines(string $method): void
{
require_admin_page();
$query = query_string('q');
$page = max(1, query_int('page', 1));
$result = routines_query($query, $page, 50, null, true);
render_page('admin_routines', [
'items' => $result['items'],
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
'query' => $query,
], 'Alle Küren');
}
function page_admin_routine_action(string $method): void
{
require_admin_page();
if ($method !== 'POST') {
redirect('/admin/routines');
}
csrf_require();
$routineId = (int) post_string('routine_id');
$action = post_string('action');
$routine = routine_fetch($routineId);
if ($routine === null) {
flash('error', 'Kür nicht gefunden.');
redirect('/admin/routines');
}
if ($action === 'hide' || $action === 'publish') {
routine_set_status($routineId, $action === 'publish' ? 'published' : 'hidden');
flash('success', 'Status geändert.');
} elseif ($action === 'delete') {
if (($_POST['confirm'] ?? '') !== '1') {
flash('error', 'Löschen muss bestätigt werden.');
redirect('/admin/routines');
}
routine_delete($routineId);
flash('success', 'Kür endgültig gelöscht.');
} else {
flash('error', 'Unbekannte Aktion.');
}
redirect('/admin/routines');
}
function audit_list(int $limit = 200): array
{
$limit = max(1, min($limit, 500));
return db()->query(
"SELECT a.*, u.username AS actor_name
FROM audit_log a LEFT JOIN users u ON u.id = a.actor_id
ORDER BY a.created_at DESC, a.id DESC LIMIT $limit"
)->fetchAll();
}