- Mit Authenticator-App und bestaetigter E-Mail laesst sich auf der Code-Seite zwischen beiden umschalten (POST /auth/2fa-method). - "Passwort vergessen" auf der Login-Seite: Link an die bestaetigte E-Mail (60 Min, einmalig, hoechstens einer pro Minute), Seite /admin/passwort-zuruecksetzen. Antwort verraet nicht, ob es das Konto gibt. - Neue Spalten password_reset_hash/_expires_at (Auto-Migration). Build neu. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W444hnfrfEXf9f84YRuZtH
288 lines
13 KiB
PHP
288 lines
13 KiB
PHP
<?php
|
||
|
||
namespace App\Support;
|
||
|
||
use App\Config\Database;
|
||
|
||
/**
|
||
* E-Mail-Adresse eines Admin-Kontos: neue Adressen werden erst nach Klick auf einen
|
||
* Bestaetigungslink aktiv (bis dahin in pending_email), und eine bestaetigte Adresse
|
||
* dient beim Login als zweiter Faktor, solange keine Authenticator-App (TOTP) eingerichtet ist.
|
||
* Versand ueber dieselbe SMTP-Konfiguration wie das Kontaktformular (Mailer).
|
||
*/
|
||
class AccountEmail
|
||
{
|
||
private const TOKEN_HOURS = 48;
|
||
private const RESET_MINUTES = 60;
|
||
public const LOGIN_CODE_MINUTES = 10;
|
||
public const LOGIN_CODE_MAX_ATTEMPTS = 5;
|
||
|
||
public static function isValid(string $email): bool
|
||
{
|
||
return strlen($email) <= 190 && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
|
||
}
|
||
|
||
public static function mailConfigured(): bool
|
||
{
|
||
$config = Mailer::resolveConfig();
|
||
return !empty($config['host']) && !empty($config['from_email']);
|
||
}
|
||
|
||
/**
|
||
* Merkt die Adresse als ausstehend vor und verschickt den Bestaetigungslink. Die bisher
|
||
* bestaetigte Adresse bleibt bis zum Klick aktiv. Wirft bei Versandfehlern, damit der
|
||
* Aufrufer eine verstaendliche Meldung zeigen kann.
|
||
*/
|
||
public static function requestChange(int $userId, string $email): void
|
||
{
|
||
if (!self::isValid($email)) {
|
||
throw new \InvalidArgumentException('Bitte eine gültige E-Mail-Adresse eingeben');
|
||
}
|
||
$taken = Database::connection()->prepare(
|
||
'SELECT 1 FROM admin_users WHERE id != ? AND (email = ? OR pending_email = ?)'
|
||
);
|
||
$taken->execute([$userId, $email, $email]);
|
||
if ($taken->fetch()) {
|
||
throw new \InvalidArgumentException('Diese E-Mail-Adresse gehört schon zu einem anderen Konto');
|
||
}
|
||
if (!self::mailConfigured()) {
|
||
throw new \RuntimeException('Der E-Mail-Versand ist noch nicht eingerichtet (Einstellungen > E-Mail).');
|
||
}
|
||
|
||
$token = bin2hex(random_bytes(32));
|
||
Database::connection()
|
||
->prepare(
|
||
'UPDATE admin_users SET pending_email = ?, email_token_hash = ?,
|
||
email_token_expires_at = DATE_ADD(NOW(), INTERVAL ' . self::TOKEN_HOURS . ' HOUR) WHERE id = ?'
|
||
)
|
||
->execute([$email, hash('sha256', $token), $userId]);
|
||
|
||
self::sendVerificationLink($userId, $email, $token);
|
||
}
|
||
|
||
/** Erneut senden: erzeugt einen neuen Link fuer die ausstehende Adresse. */
|
||
public static function resend(int $userId): void
|
||
{
|
||
$stmt = Database::connection()->prepare('SELECT pending_email FROM admin_users WHERE id = ?');
|
||
$stmt->execute([$userId]);
|
||
$pending = $stmt->fetchColumn();
|
||
if (!$pending) {
|
||
throw new \InvalidArgumentException('Es wartet keine E-Mail-Adresse auf Bestätigung');
|
||
}
|
||
self::requestChange($userId, $pending);
|
||
}
|
||
|
||
public static function cancelPending(int $userId): void
|
||
{
|
||
Database::connection()
|
||
->prepare('UPDATE admin_users SET pending_email = NULL, email_token_hash = NULL, email_token_expires_at = NULL WHERE id = ?')
|
||
->execute([$userId]);
|
||
}
|
||
|
||
public static function remove(int $userId): void
|
||
{
|
||
Database::connection()
|
||
->prepare(
|
||
'UPDATE admin_users SET email = NULL, email_verified_at = NULL, pending_email = NULL,
|
||
email_token_hash = NULL, email_token_expires_at = NULL WHERE id = ?'
|
||
)
|
||
->execute([$userId]);
|
||
}
|
||
|
||
/** Liefert den Benutzernamen bei Erfolg, sonst null (unbekannt oder abgelaufen). */
|
||
public static function confirm(string $token): ?string
|
||
{
|
||
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
|
||
return null;
|
||
}
|
||
$db = Database::connection();
|
||
$stmt = $db->prepare(
|
||
'SELECT id, username, pending_email FROM admin_users
|
||
WHERE email_token_hash = ? AND email_token_expires_at > NOW() AND pending_email IS NOT NULL'
|
||
);
|
||
$stmt->execute([hash('sha256', $token)]);
|
||
$user = $stmt->fetch();
|
||
if (!$user) {
|
||
return null;
|
||
}
|
||
$taken = $db->prepare('SELECT 1 FROM admin_users WHERE id != ? AND email = ?');
|
||
$taken->execute([$user['id'], $user['pending_email']]);
|
||
if ($taken->fetch()) {
|
||
return null;
|
||
}
|
||
|
||
$db->prepare(
|
||
'UPDATE admin_users SET email = pending_email, email_verified_at = NOW(), pending_email = NULL,
|
||
email_token_hash = NULL, email_token_expires_at = NULL WHERE id = ?'
|
||
)->execute([$user['id']]);
|
||
|
||
return $user['username'];
|
||
}
|
||
|
||
public static function status(int $userId): array
|
||
{
|
||
$stmt = Database::connection()->prepare(
|
||
'SELECT email, email_verified_at, pending_email FROM admin_users WHERE id = ?'
|
||
);
|
||
$stmt->execute([$userId]);
|
||
$row = $stmt->fetch() ?: [];
|
||
|
||
return [
|
||
'email' => $row['email'] ?? null,
|
||
'email_verified' => !empty($row['email']) && !empty($row['email_verified_at']),
|
||
'pending_email' => $row['pending_email'] ?? null,
|
||
];
|
||
}
|
||
|
||
/** "m***@example.de" fuer die Anzeige auf der Login-Seite. */
|
||
public static function mask(string $email): string
|
||
{
|
||
[$local, $domain] = array_pad(explode('@', $email, 2), 2, '');
|
||
return mb_substr($local, 0, 1) . str_repeat('*', max(2, min(6, mb_strlen($local) - 1))) . '@' . $domain;
|
||
}
|
||
|
||
public static function sendLoginCode(string $email, string $username, string $code): void
|
||
{
|
||
$minutes = self::LOGIN_CODE_MINUTES;
|
||
$text = "Hallo {$username},\n\n"
|
||
. "dein Anmeldecode für den HifiPlanet-Adminbereich lautet:\n\n"
|
||
. " {$code}\n\n"
|
||
. "Der Code ist {$minutes} Minuten gültig. Wenn du dich gerade nicht anmelden wolltest, "
|
||
. "ändere bitte dein Passwort – jemand kennt es offenbar.\n\n"
|
||
. "Dein HifiPlanet-Team";
|
||
$html = '<p>Hallo ' . self::e($username) . ',</p>'
|
||
. '<p>dein Anmeldecode für den HifiPlanet-Adminbereich lautet:</p>'
|
||
. '<p style="font-size:28px;font-weight:bold;letter-spacing:6px;font-family:monospace">' . self::e($code) . '</p>'
|
||
. "<p>Der Code ist {$minutes} Minuten gültig. Wenn du dich gerade nicht anmelden wolltest, "
|
||
. 'ändere bitte dein Passwort – jemand kennt es offenbar.</p>'
|
||
. '<p>Dein HifiPlanet-Team</p>';
|
||
|
||
self::send($email, $username, 'Dein Anmeldecode: ' . $code, $html, $text);
|
||
}
|
||
|
||
/**
|
||
* Link zum Zuruecksetzen des Passworts (1 h gueltig). Hoechstens ein Link pro Minute je
|
||
* Konto, damit sich das Postfach nicht von aussen fluten laesst.
|
||
*/
|
||
public static function sendPasswordReset(int $userId): void
|
||
{
|
||
$db = Database::connection();
|
||
$stmt = $db->prepare(
|
||
'SELECT username, email, password_reset_expires_at > DATE_ADD(NOW(), INTERVAL 59 MINUTE) AS recent
|
||
FROM admin_users WHERE id = ?'
|
||
);
|
||
$stmt->execute([$userId]);
|
||
$user = $stmt->fetch();
|
||
if (!$user || !empty($user['recent']) || !self::mailConfigured()) {
|
||
return;
|
||
}
|
||
|
||
$token = bin2hex(random_bytes(32));
|
||
$db->prepare(
|
||
'UPDATE admin_users SET password_reset_hash = ?,
|
||
password_reset_expires_at = DATE_ADD(NOW(), INTERVAL ' . self::RESET_MINUTES . ' MINUTE) WHERE id = ?'
|
||
)->execute([hash('sha256', $token), $userId]);
|
||
|
||
$link = self::baseUrl() . 'admin/passwort-zuruecksetzen?token=' . $token;
|
||
$username = $user['username'];
|
||
$minutes = self::RESET_MINUTES;
|
||
$text = "Hallo {$username},\n\n"
|
||
. "für dein Konto im HifiPlanet-Adminbereich wurde ein neues Passwort angefordert. "
|
||
. "Über diesen Link kannst du es festlegen:\n\n{$link}\n\n"
|
||
. "Der Link ist {$minutes} Minuten gültig und funktioniert einmal. "
|
||
. "Wenn du das nicht warst, ignoriere diese E-Mail einfach – dein Passwort bleibt dann unverändert.\n\n"
|
||
. "Dein HifiPlanet-Team";
|
||
$html = '<p>Hallo ' . self::e($username) . ',</p>'
|
||
. '<p>für dein Konto im HifiPlanet-Adminbereich wurde ein neues Passwort angefordert.</p>'
|
||
. '<p><a href="' . self::e($link) . '" style="display:inline-block;padding:10px 18px;background:#6ba626;color:#fff;'
|
||
. 'border-radius:6px;text-decoration:none;font-weight:bold">Neues Passwort festlegen</a></p>'
|
||
. '<p style="font-size:12px;color:#666">Oder diesen Link öffnen: ' . self::e($link) . '</p>'
|
||
. "<p>Der Link ist {$minutes} Minuten gültig und funktioniert einmal. "
|
||
. 'Wenn du das nicht warst, ignoriere diese E-Mail einfach – dein Passwort bleibt dann unverändert.</p>'
|
||
. '<p>Dein HifiPlanet-Team</p>';
|
||
|
||
self::send($user['email'], $username, 'Passwort zurücksetzen', $html, $text);
|
||
}
|
||
|
||
/** Setzt das Passwort per Link-Token; false, wenn der Link ungueltig oder abgelaufen ist. */
|
||
public static function resetPassword(string $token, string $password): bool
|
||
{
|
||
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
|
||
return false;
|
||
}
|
||
$db = Database::connection();
|
||
$stmt = $db->prepare(
|
||
'SELECT id FROM admin_users WHERE password_reset_hash = ? AND password_reset_expires_at > NOW()'
|
||
);
|
||
$stmt->execute([hash('sha256', $token)]);
|
||
$id = $stmt->fetchColumn();
|
||
if (!$id) {
|
||
return false;
|
||
}
|
||
$db->prepare(
|
||
'UPDATE admin_users SET password_hash = ?, password_reset_hash = NULL, password_reset_expires_at = NULL WHERE id = ?'
|
||
)->execute([password_hash($password, PASSWORD_DEFAULT), $id]);
|
||
|
||
return true;
|
||
}
|
||
|
||
private static function sendVerificationLink(int $userId, string $email, string $token): void
|
||
{
|
||
$stmt = Database::connection()->prepare('SELECT username FROM admin_users WHERE id = ?');
|
||
$stmt->execute([$userId]);
|
||
$username = (string) $stmt->fetchColumn();
|
||
|
||
$link = self::baseUrl() . 'admin/email-bestaetigen?token=' . $token;
|
||
$hours = self::TOKEN_HOURS;
|
||
$text = "Hallo {$username},\n\n"
|
||
. "diese Adresse soll für dein Konto im HifiPlanet-Adminbereich hinterlegt werden. "
|
||
. "Bitte bestätige das über diesen Link:\n\n{$link}\n\n"
|
||
. "Der Link ist {$hours} Stunden gültig. Danach bekommst du beim Login einen Code an diese Adresse.\n"
|
||
. "Wenn du das nicht warst, kannst du diese E-Mail einfach ignorieren.\n\n"
|
||
. "Dein HifiPlanet-Team";
|
||
$html = '<p>Hallo ' . self::e($username) . ',</p>'
|
||
. '<p>diese Adresse soll für dein Konto im HifiPlanet-Adminbereich hinterlegt werden. Bitte bestätige das:</p>'
|
||
. '<p><a href="' . self::e($link) . '" style="display:inline-block;padding:10px 18px;background:#6ba626;color:#fff;'
|
||
. 'border-radius:6px;text-decoration:none;font-weight:bold">E-Mail-Adresse bestätigen</a></p>'
|
||
. '<p style="font-size:12px;color:#666">Oder diesen Link öffnen: ' . self::e($link) . '</p>'
|
||
. "<p>Der Link ist {$hours} Stunden gültig. Danach bekommst du beim Login einen Code an diese Adresse.<br>"
|
||
. 'Wenn du das nicht warst, kannst du diese E-Mail einfach ignorieren.</p>'
|
||
. '<p>Dein HifiPlanet-Team</p>';
|
||
|
||
self::send($email, $username, 'E-Mail-Adresse bestätigen', $html, $text);
|
||
}
|
||
|
||
private static function send(string $to, string $name, string $subject, string $html, string $text): void
|
||
{
|
||
$mail = Mailer::build(Mailer::resolveConfig());
|
||
$mail->addAddress($to, $name);
|
||
$mail->Subject = $subject;
|
||
$mail->isHTML(true);
|
||
$mail->Body = $html;
|
||
$mail->AltBody = $text;
|
||
$mail->send();
|
||
}
|
||
|
||
/**
|
||
* Link-Basis aus der aktuellen Anfrage, damit der Link auf Testserver und Live-Seite
|
||
* jeweils auf die eigene Domain zeigt. site_url aus der Config nur als Rueckfall.
|
||
*/
|
||
private static function baseUrl(): string
|
||
{
|
||
$config = require __DIR__ . '/../../config/config.php';
|
||
$basePath = rtrim($config['app']['base_path'] ?? '/', '/') . '/';
|
||
$host = $_SERVER['HTTP_HOST'] ?? '';
|
||
if ($host === '' || !preg_match('/^[a-z0-9.\-]+(:\d+)?$/i', $host)) {
|
||
return rtrim($config['app']['site_url'] ?? '', '/') . $basePath;
|
||
}
|
||
$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|
||
|| strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
|
||
|
||
return ($https ? 'https' : 'http') . '://' . $host . $basePath;
|
||
}
|
||
|
||
private static function e(string $value): string
|
||
{
|
||
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
|
||
}
|
||
}
|