- Konten bekommen eine E-Mail-Adresse (Mein Konto und Benutzerverwaltung). Neue Adressen gelten erst nach Klick auf den Bestaetigungslink (/admin/email-bestaetigen, 48 h gueltig, Token nur als SHA-256 gespeichert). - Login: mit Authenticator-App wie bisher TOTP; sonst bei bestaetigter E-Mail ein 6-stelliger Code per Mail (10 Min, 5 Versuche, neu senden nach 30 s). Konten ohne beides und Server ohne eingerichteten Mailversand melden sich weiter nur mit Passwort an. - Versand ueber die SMTP-Einstellungen des Kontaktformulars (Mailer). - Neue Spalten in Schema.php (Auto-Migration) und schema.sql, Export der Konten um email/email_verified_at ergaenzt. Build neu. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W444hnfrfEXf9f84YRuZtH
362 lines
14 KiB
PHP
362 lines
14 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Config\Database;
|
|
use App\Middleware\AuthMiddleware;
|
|
use App\Support\AccountEmail;
|
|
use App\Support\Http;
|
|
use App\Support\RecoveryCodes;
|
|
use App\Support\Totp;
|
|
|
|
class AuthController
|
|
{
|
|
public static function login(): void
|
|
{
|
|
$body = Http::jsonBody();
|
|
$username = trim($body['username'] ?? '');
|
|
$password = (string) ($body['password'] ?? '');
|
|
|
|
if ($username === '' || $password === '') {
|
|
Http::error('Benutzername und Passwort erforderlich', 422);
|
|
}
|
|
|
|
$stmt = Database::connection()->prepare(
|
|
'SELECT id, username, password_hash, two_factor_enabled, email, email_verified_at FROM admin_users WHERE username = ?'
|
|
);
|
|
$stmt->execute([$username]);
|
|
$user = $stmt->fetch();
|
|
|
|
if (!$user || !password_verify($password, $user['password_hash'])) {
|
|
Http::error('Benutzername oder Passwort falsch', 401);
|
|
}
|
|
|
|
if ((bool) $user['two_factor_enabled']) {
|
|
session_regenerate_id(true);
|
|
$_SESSION['pending_2fa_user_id'] = (int) $user['id'];
|
|
$_SESSION['pending_2fa_method'] = 'totp';
|
|
unset($_SESSION['admin_id'], $_SESSION['admin_username']);
|
|
Http::send(['requires_2fa' => true, 'method' => 'totp']);
|
|
return;
|
|
}
|
|
|
|
// Ohne Authenticator-App, aber mit bestaetigter E-Mail: Code per Mail als zweiter Faktor.
|
|
// Konten ohne beides melden sich wie bisher nur mit Passwort an.
|
|
if (!empty($user['email']) && !empty($user['email_verified_at'])) {
|
|
session_regenerate_id(true);
|
|
unset($_SESSION['admin_id'], $_SESSION['admin_username']);
|
|
$_SESSION['pending_2fa_user_id'] = (int) $user['id'];
|
|
$_SESSION['pending_2fa_method'] = 'email';
|
|
$_SESSION['email_code_sends'] = 0;
|
|
if (self::issueEmailCode($user['email'], $user['username'])) {
|
|
Http::send(['requires_2fa' => true, 'method' => 'email', 'email_hint' => AccountEmail::mask($user['email'])]);
|
|
return;
|
|
}
|
|
// Mailversand nicht eingerichtet oder fehlgeschlagen: nicht aussperren, sondern wie
|
|
// ohne E-Mail anmelden (der Fehler steht im PHP-Error-Log).
|
|
}
|
|
|
|
self::completeLogin((int) $user['id'], $user['username']);
|
|
}
|
|
|
|
public static function resendLoginCode(): void
|
|
{
|
|
if (empty($_SESSION['pending_2fa_user_id']) || ($_SESSION['pending_2fa_method'] ?? '') !== 'email') {
|
|
Http::error('Keine ausstehende Anmeldung. Bitte erneut einloggen.', 400);
|
|
}
|
|
if (time() - (int) ($_SESSION['email_code_sent_at'] ?? 0) < 30) {
|
|
Http::error('Bitte warte kurz, bevor du einen neuen Code anforderst.', 429);
|
|
}
|
|
if ((int) ($_SESSION['email_code_sends'] ?? 0) >= 5) {
|
|
Http::error('Zu viele Codes angefordert. Bitte melde dich erneut an.', 429);
|
|
}
|
|
|
|
$stmt = Database::connection()->prepare('SELECT username, email FROM admin_users WHERE id = ?');
|
|
$stmt->execute([(int) $_SESSION['pending_2fa_user_id']]);
|
|
$user = $stmt->fetch();
|
|
if (!$user || empty($user['email']) || !self::issueEmailCode($user['email'], $user['username'])) {
|
|
Http::error('Der Code konnte nicht gesendet werden. Bitte später erneut versuchen.', 500);
|
|
}
|
|
|
|
Http::send(['ok' => true]);
|
|
}
|
|
|
|
private static function issueEmailCode(string $email, string $username): bool
|
|
{
|
|
if (!AccountEmail::mailConfigured()) {
|
|
return false;
|
|
}
|
|
$code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
|
try {
|
|
AccountEmail::sendLoginCode($email, $username, $code);
|
|
} catch (\Throwable $e) {
|
|
error_log('Login-Code konnte nicht gesendet werden: ' . $e->getMessage());
|
|
return false;
|
|
}
|
|
$_SESSION['email_code_hash'] = password_hash($code, PASSWORD_DEFAULT);
|
|
$_SESSION['email_code_expires'] = time() + AccountEmail::LOGIN_CODE_MINUTES * 60;
|
|
$_SESSION['email_code_attempts'] = 0;
|
|
$_SESSION['email_code_sent_at'] = time();
|
|
$_SESSION['email_code_sends'] = (int) ($_SESSION['email_code_sends'] ?? 0) + 1;
|
|
|
|
return true;
|
|
}
|
|
|
|
private static function verifyEmailCode(string $code): bool
|
|
{
|
|
$attempts = (int) ($_SESSION['email_code_attempts'] ?? 0) + 1;
|
|
$_SESSION['email_code_attempts'] = $attempts;
|
|
if ($attempts > AccountEmail::LOGIN_CODE_MAX_ATTEMPTS) {
|
|
self::clearPendingLogin();
|
|
Http::error('Zu viele Fehlversuche. Bitte melde dich erneut an.', 429);
|
|
}
|
|
if (time() > (int) ($_SESSION['email_code_expires'] ?? 0)) {
|
|
Http::error('Der Code ist abgelaufen. Fordere einen neuen an.', 401);
|
|
}
|
|
|
|
return password_verify(preg_replace('/\s+/', '', $code), (string) ($_SESSION['email_code_hash'] ?? ''));
|
|
}
|
|
|
|
private static function clearPendingLogin(): void
|
|
{
|
|
unset(
|
|
$_SESSION['pending_2fa_user_id'], $_SESSION['pending_2fa_method'], $_SESSION['email_code_hash'],
|
|
$_SESSION['email_code_expires'], $_SESSION['email_code_attempts'], $_SESSION['email_code_sent_at'],
|
|
$_SESSION['email_code_sends']
|
|
);
|
|
}
|
|
|
|
public static function verifyTwoFactor(): void
|
|
{
|
|
if (empty($_SESSION['pending_2fa_user_id'])) {
|
|
Http::error('Keine ausstehende Anmeldung. Bitte erneut einloggen.', 400);
|
|
}
|
|
$userId = (int) $_SESSION['pending_2fa_user_id'];
|
|
$body = Http::jsonBody();
|
|
$code = trim($body['code'] ?? '');
|
|
|
|
if ($code === '') {
|
|
Http::error('Code erforderlich', 422);
|
|
}
|
|
|
|
$stmt = Database::connection()->prepare(
|
|
'SELECT username, two_factor_secret, two_factor_recovery_codes FROM admin_users WHERE id = ?'
|
|
);
|
|
$stmt->execute([$userId]);
|
|
$user = $stmt->fetch();
|
|
|
|
if (!$user) {
|
|
Http::error('Benutzer nicht gefunden', 404);
|
|
}
|
|
|
|
if (($_SESSION['pending_2fa_method'] ?? 'totp') === 'email') {
|
|
if (!self::verifyEmailCode($code)) {
|
|
Http::error('Code ungültig', 401);
|
|
}
|
|
self::completeLogin($userId, $user['username']);
|
|
}
|
|
|
|
$valid = Totp::verifyCode($user['two_factor_secret'] ?? '', $code);
|
|
|
|
if (!$valid) {
|
|
$hashes = $user['two_factor_recovery_codes'] ? json_decode($user['two_factor_recovery_codes'], true) : [];
|
|
$remaining = RecoveryCodes::consume($hashes, $code);
|
|
if ($remaining !== null) {
|
|
$valid = true;
|
|
$update = Database::connection()->prepare(
|
|
'UPDATE admin_users SET two_factor_recovery_codes = ? WHERE id = ?'
|
|
);
|
|
$update->execute([json_encode($remaining), $userId]);
|
|
}
|
|
}
|
|
|
|
if (!$valid) {
|
|
Http::error('Code ungültig oder abgelaufen', 401);
|
|
}
|
|
|
|
self::completeLogin($userId, $user['username']);
|
|
}
|
|
|
|
public static function changePassword(): void
|
|
{
|
|
$userId = AuthMiddleware::requireAdmin();
|
|
$body = Http::jsonBody();
|
|
$currentPassword = (string) ($body['current_password'] ?? '');
|
|
$newPassword = (string) ($body['new_password'] ?? '');
|
|
$newPasswordConfirmation = (string) ($body['new_password_confirmation'] ?? '');
|
|
$twoFactorCode = trim((string) ($body['two_factor_code'] ?? ''));
|
|
|
|
if ($currentPassword === '' || $newPassword === '' || $newPasswordConfirmation === '') {
|
|
Http::error('Bitte alle Felder ausfüllen', 422);
|
|
}
|
|
if (strlen($newPassword) < 8) {
|
|
Http::error('Das neue Passwort muss mindestens 8 Zeichen lang sein', 422);
|
|
}
|
|
if ($newPassword !== $newPasswordConfirmation) {
|
|
Http::error('Die neuen Passwörter stimmen nicht überein', 422);
|
|
}
|
|
|
|
$stmt = Database::connection()->prepare(
|
|
'SELECT password_hash, two_factor_enabled, two_factor_secret, two_factor_recovery_codes FROM admin_users WHERE id = ?'
|
|
);
|
|
$stmt->execute([$userId]);
|
|
$user = $stmt->fetch();
|
|
|
|
if (!$user || !password_verify($currentPassword, $user['password_hash'])) {
|
|
Http::error('Aktuelles Passwort ist falsch', 401);
|
|
}
|
|
|
|
if ((bool) $user['two_factor_enabled']) {
|
|
if ($twoFactorCode === '') {
|
|
Http::error('Bitte deinen 2FA-Code eingeben', 422);
|
|
}
|
|
|
|
$valid = Totp::verifyCode($user['two_factor_secret'] ?? '', $twoFactorCode);
|
|
|
|
if (!$valid) {
|
|
$hashes = $user['two_factor_recovery_codes'] ? json_decode($user['two_factor_recovery_codes'], true) : [];
|
|
$remaining = RecoveryCodes::consume($hashes, $twoFactorCode);
|
|
if ($remaining !== null) {
|
|
$valid = true;
|
|
$update = Database::connection()->prepare(
|
|
'UPDATE admin_users SET two_factor_recovery_codes = ? WHERE id = ?'
|
|
);
|
|
$update->execute([json_encode($remaining), $userId]);
|
|
}
|
|
}
|
|
|
|
if (!$valid) {
|
|
Http::error('2FA-Code ungültig oder abgelaufen', 401);
|
|
}
|
|
}
|
|
|
|
$newHash = password_hash($newPassword, PASSWORD_DEFAULT);
|
|
$update = Database::connection()->prepare('UPDATE admin_users SET password_hash = ? WHERE id = ?');
|
|
$update->execute([$newHash, $userId]);
|
|
|
|
Http::send(['ok' => true]);
|
|
}
|
|
|
|
public static function changeEmail(): void
|
|
{
|
|
$userId = AuthMiddleware::requireAdmin();
|
|
$body = Http::jsonBody();
|
|
$email = trim((string) ($body['email'] ?? ''));
|
|
self::requirePassword($userId, (string) ($body['password'] ?? ''));
|
|
|
|
try {
|
|
AccountEmail::requestChange($userId, $email);
|
|
} catch (\InvalidArgumentException $e) {
|
|
Http::error($e->getMessage(), 422);
|
|
} catch (\Throwable $e) {
|
|
error_log('Bestaetigungsmail fehlgeschlagen: ' . $e->getMessage());
|
|
AccountEmail::cancelPending($userId);
|
|
Http::error($e instanceof \RuntimeException
|
|
? $e->getMessage()
|
|
: 'Die Bestätigungsmail konnte nicht gesendet werden. Bitte die E-Mail-Einstellungen prüfen.', 500);
|
|
}
|
|
|
|
Http::send(['ok' => true] + AccountEmail::status($userId));
|
|
}
|
|
|
|
public static function resendEmailVerification(): void
|
|
{
|
|
$userId = AuthMiddleware::requireAdmin();
|
|
try {
|
|
AccountEmail::resend($userId);
|
|
} catch (\InvalidArgumentException $e) {
|
|
Http::error($e->getMessage(), 422);
|
|
} catch (\Throwable $e) {
|
|
error_log('Bestaetigungsmail fehlgeschlagen: ' . $e->getMessage());
|
|
Http::error('Die Bestätigungsmail konnte nicht gesendet werden. Bitte die E-Mail-Einstellungen prüfen.', 500);
|
|
}
|
|
Http::send(['ok' => true] + AccountEmail::status($userId));
|
|
}
|
|
|
|
public static function cancelEmailChange(): void
|
|
{
|
|
$userId = AuthMiddleware::requireAdmin();
|
|
AccountEmail::cancelPending($userId);
|
|
Http::send(['ok' => true] + AccountEmail::status($userId));
|
|
}
|
|
|
|
public static function removeEmail(): void
|
|
{
|
|
$userId = AuthMiddleware::requireAdmin();
|
|
self::requirePassword($userId, (string) (Http::jsonBody()['password'] ?? ''));
|
|
AccountEmail::remove($userId);
|
|
Http::send(['ok' => true] + AccountEmail::status($userId));
|
|
}
|
|
|
|
/** Oeffentlich: der Link aus der Bestaetigungsmail funktioniert auch ohne Anmeldung. */
|
|
public static function confirmEmail(): void
|
|
{
|
|
$username = AccountEmail::confirm(trim((string) (Http::jsonBody()['token'] ?? '')));
|
|
if ($username === null) {
|
|
Http::error('Der Link ist ungültig oder abgelaufen. Bitte fordere im Adminbereich unter „Mein Konto“ einen neuen an.', 410);
|
|
}
|
|
Http::send(['ok' => true, 'username' => $username]);
|
|
}
|
|
|
|
private static function requirePassword(int $userId, string $password): void
|
|
{
|
|
$stmt = Database::connection()->prepare('SELECT password_hash FROM admin_users WHERE id = ?');
|
|
$stmt->execute([$userId]);
|
|
$hash = $stmt->fetchColumn();
|
|
if (!$hash || !password_verify($password, $hash)) {
|
|
Http::error('Passwort falsch', 401);
|
|
}
|
|
}
|
|
|
|
public static function logout(): void
|
|
{
|
|
$_SESSION = [];
|
|
// Ohne Login-Zustand startet index.php keine (bzw. keine offene) Session.
|
|
if (session_status() === PHP_SESSION_ACTIVE) {
|
|
session_destroy();
|
|
}
|
|
Http::send(['ok' => true]);
|
|
}
|
|
|
|
public static function me(): void
|
|
{
|
|
// Bewusst kein 401 hier: /auth/me wird auf JEDER oeffentlichen Seite aufgerufen,
|
|
// um den Login-Status zu pruefen - "nicht angemeldet" ist der Normalfall fuer
|
|
// Besucher, kein Fehler. Ein 401 erzeugt in der Browser-Konsole/DevTools trotz
|
|
// JS-seitigem catch() einen sichtbaren Netzwerk-Fehler (bemaengelt u.a. Lighthouse).
|
|
if (empty($_SESSION['admin_id'])) {
|
|
Http::send(['authenticated' => false]);
|
|
}
|
|
Http::send(self::userPayload((int) $_SESSION['admin_id'], $_SESSION['admin_username']));
|
|
}
|
|
|
|
private static function completeLogin(int $id, string $username): void
|
|
{
|
|
session_regenerate_id(true);
|
|
$_SESSION['admin_id'] = $id;
|
|
$_SESSION['admin_username'] = $username;
|
|
$_SESSION['last_active_touched_at'] = time();
|
|
self::clearPendingLogin();
|
|
|
|
Database::connection()
|
|
->prepare('UPDATE admin_users SET last_active_at = NOW() WHERE id = ?')
|
|
->execute([$id]);
|
|
|
|
Http::send(self::userPayload($id, $username));
|
|
}
|
|
|
|
private static function userPayload(int $id, string $username): array
|
|
{
|
|
$stmt = Database::connection()->prepare('SELECT two_factor_enabled FROM admin_users WHERE id = ?');
|
|
$stmt->execute([$id]);
|
|
$row = $stmt->fetch();
|
|
|
|
return [
|
|
'id' => $id,
|
|
'username' => $username,
|
|
'is_super_admin' => AuthMiddleware::isSuperAdmin($id),
|
|
'two_factor_enabled' => (bool) ($row['two_factor_enabled'] ?? false),
|
|
'permissions' => AuthMiddleware::effectivePermissions($id),
|
|
] + AccountEmail::status($id);
|
|
}
|
|
}
|