Tests für Anmeldung und Controller, PHP 8.1, Sprach-Fallback
All checks were successful
CI / PHP Lint (push) Successful in 37s
CI / PHP Lint-1 (push) Successful in 53s
CI / Unit Tests & Static Analysis (push) Successful in 40s
CI / PHP Lint (pull_request) Successful in 39s
CI / PHP Lint-1 (pull_request) Successful in 44s
CI / Unit Tests & Static Analysis (pull_request) Successful in 44s

Bisher deckten die Tests nur Hilfsklassen ab. Neu sind die beiden
Stellen, an denen ein Fehler richtig weh tut:

- AuthTest (12 Fälle): richtige und falsche Anmeldung, Rate-Limit greift
  vor der Passwortprüfung, 2FA-Nutzer gilt vor dem Code ausdrücklich
  nicht als angemeldet, CSRF-Prüfung, und die Client-IP hinter einem
  Proxy – inklusive der Fälle, in denen X-Forwarded-For ignoriert werden
  muss
- UniFiControllerTest (8 Fälle): die Auswahl des eigenen Vouchers. Der
  Controller liefert Voucher unsortiert; wer den ersten nimmt, gibt bei
  parallelen Anfragen den Code eines anderen Gastes aus. Dazu QoS-Payload
  und die Fehlerfälle.

Dafür nötig: Auth nimmt die Datenbank optional über den Konstruktor
entgegen (ohne Argument unverändert), und UniFiController::apiRequest()
ist protected statt private, damit Tests aufgezeichnete Antworten
einspielen können. Beide Tests brauchen weder Datenbank noch Netz.

PHP-Anforderung von 7.4 auf 8.1 gehoben: Composer, CI-Matrix (8.1/8.3),
Docker-Image (8.3) und README. Die 7.4-Angabe war ohnehin ungeprüft.

I18n: fehlt ein Schlüssel in der gewählten Sprache, erscheint jetzt der
deutsche Text statt des technischen Schlüssels.

PHPStan deckt zusätzlich VoucherService und I18n ab.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-24 11:13:01 +00:00
parent b7e0f67a50
commit a36dcbba27
10 changed files with 1344 additions and 930 deletions

View file

@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
php: [ "7.4", "8.2" ] php: [ "8.1", "8.3" ]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

View file

@ -1,5 +1,5 @@
# UniFi Voucher Management System – Container-Image # UniFi Voucher Management System – Container-Image
FROM php:8.2-apache FROM php:8.3-apache
# System-Tools (curl für Healthcheck) + PHP-Extensions # System-Tools (curl für Healthcheck) + PHP-Extensions
RUN apt-get update && apt-get install -y --no-install-recommends curl \ RUN apt-get update && apt-get install -y --no-install-recommends curl \

View file

@ -6,7 +6,7 @@
Entwickelt von **[Loheide.eu](https://loheide.eu)** Entwickelt von **[Loheide.eu](https://loheide.eu)**
![PHP](https://img.shields.io/badge/PHP-7.4%2B-777BB4?logo=php&logoColor=white) ![PHP](https://img.shields.io/badge/PHP-8.1%2B-777BB4?logo=php&logoColor=white)
![MySQL](https://img.shields.io/badge/MySQL-5.7%2B%20%2F%20MariaDB-4479A1?logo=mysql&logoColor=white) ![MySQL](https://img.shields.io/badge/MySQL-5.7%2B%20%2F%20MariaDB-4479A1?logo=mysql&logoColor=white)
![UniFi OS](https://img.shields.io/badge/UniFi%20OS-7.0%2B-0559C9?logo=ubiquiti&logoColor=white) ![UniFi OS](https://img.shields.io/badge/UniFi%20OS-7.0%2B-0559C9?logo=ubiquiti&logoColor=white)
![License](https://img.shields.io/badge/Lizenz-MIT-green) ![License](https://img.shields.io/badge/Lizenz-MIT-green)
@ -147,7 +147,7 @@ Entwickelt von **[Loheide.eu](https://loheide.eu)**
| Komponente | Version | | Komponente | Version |
|---|---| |---|---|
| PHP | 7.4+ (mit PDO, PDO_MySQL, cURL, mbstring, JSON; empfohlen: OpenSSL/libsodium, Zip) | | PHP | 8.1+ (mit PDO, PDO_MySQL, cURL, mbstring, JSON; empfohlen: OpenSSL/libsodium, Zip) |
| Datenbank | MySQL 5.7+ / MariaDB 10.2+ | | Datenbank | MySQL 5.7+ / MariaDB 10.2+ |
| Webserver | Apache / Nginx | | Webserver | Apache / Nginx |
| UniFi | **Network Application 7.0+ mit UniFi OS** (z. B. UDM, UDR, UniFi OS Server) | | UniFi | **Network Application 7.0+ mit UniFi OS** (z. B. UDM, UDR, UniFi OS Server) |
@ -591,10 +591,25 @@ Tests und statische Analyse:
```bash ```bash
composer install composer install
vendor/bin/phpunit # 29 Tests (Crypto, TOTP, API-Keys, Upload, Ui) vendor/bin/phpunit # 62 Tests
vendor/bin/phpstan analyse # Level 5 vendor/bin/phpstan analyse # Level 5
``` ```
Die Tests decken die Stellen ab, an denen Fehler teuer werden:
| Bereich | Was geprüft wird |
|---|---|
| `AuthTest` | Anmeldung, Rate-Limit, 2FA-Zwischenschritt, CSRF, Client-IP hinter Proxy |
| `UniFiControllerTest` | Auswahl des eigenen Vouchers bei parallelen Anfragen, QoS-Payload, Fehlerfälle |
| `KioskTest` | Token-Prüfung, Wartezeit, Tageslimit, Gestaltung |
| `UploadTest` | SVG-Filter und Pfad-Prüfung |
| `UiTest` | Versionsstempel, Media-Pfade, Branding-Overrides |
| `CryptoTest`, `TotpTest`, `ApiKeyTest` | Verschlüsselung, Einmalcodes, Schlüssel-Hashing |
`AuthTest` und `UniFiControllerTest` kommen ohne Datenbank und ohne erreichbaren
Controller aus: `Auth` nimmt die Datenbank über den Konstruktor entgegen, beim
Controller spielen die Tests aufgezeichnete API-Antworten ein.
Die Versionsnummer steht in der Datei **`VERSION`** im Projektstamm. Sie wird Die Versionsnummer steht in der Datei **`VERSION`** im Projektstamm. Sie wird
im Admin-Bereich unten in der Seitenleiste angezeigt und benennt das im Admin-Bereich unten in der Seitenleiste angezeigt und benennt das
Release-Paket – für eine neue Version also dort (und im Badge oben) anheben. Release-Paket – für eine neue Version also dort (und im Badge oben) anheben.

View file

@ -14,7 +14,7 @@
"source": "https://git.loheide.cloud/friloo/Unifi-Voucher-Tool" "source": "https://git.loheide.cloud/friloo/Unifi-Voucher-Tool"
}, },
"require": { "require": {
"php": ">=7.4" "php": ">=8.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^9.6", "phpunit/phpunit": "^9.6",

View file

@ -1,478 +1,487 @@
<?php <?php
require_once __DIR__ . '/Totp.php'; require_once __DIR__ . '/Totp.php';
require_once __DIR__ . '/Notifier.php'; require_once __DIR__ . '/Notifier.php';
require_once __DIR__ . '/Crypto.php'; require_once __DIR__ . '/Crypto.php';
class Auth { class Auth {
private $db; private $db;
public function __construct() { /**
try { * @param object|null $db Datenbank-Zugriff; null nutzt die Instanz der
$this->db = Database::getInstance(); * Anwendung. Der Parameter existiert, damit sich
} catch (Exception $e) { * Anmeldung und Rate-Limit testen lassen.
die("Datenbankverbindung fehlgeschlagen: " . $e->getMessage()); */
} public function __construct($db = null) {
$this->db = $db ?: Database::getInstance();
// Session-Konfiguration
if (session_status() === PHP_SESSION_NONE) { // Session-Konfiguration – auf der Kommandozeile (Tests, Cron) gibt es
ini_set('session.cookie_httponly', 1); // keine Sitzung, dort wird $_SESSION einfach als Array verwendet.
ini_set('session.use_strict_mode', 1); if (PHP_SAPI === 'cli') {
ini_set('session.cookie_samesite', 'Lax'); if (!isset($_SESSION)) {
$_SESSION = [];
// Opt-in: Sessions in der DB ablegen (für "überall abmelden" / Skalierung) }
try { return;
if ($this->db->getSetting('session_driver', 'php') === 'db') { }
require_once __DIR__ . '/DbSessionHandler.php';
$ttl = defined('SESSION_LIFETIME') ? (int)SESSION_LIFETIME : 3600; if (session_status() === PHP_SESSION_NONE) {
session_set_save_handler(new DbSessionHandler($this->db, $ttl), true); ini_set('session.cookie_httponly', 1);
} ini_set('session.use_strict_mode', 1);
} catch (\Throwable $e) { /* Fallback: Standard-PHP-Sessions */ } ini_set('session.cookie_samesite', 'Lax');
if (!session_start()) { // Opt-in: Sessions in der DB ablegen (für "überall abmelden" / Skalierung)
die("Session konnte nicht gestartet werden"); try {
} if ($this->db->getSetting('session_driver', 'php') === 'db') {
} require_once __DIR__ . '/DbSessionHandler.php';
} $ttl = defined('SESSION_LIFETIME') ? (int)SESSION_LIFETIME : 3600;
session_set_save_handler(new DbSessionHandler($this->db, $ttl), true);
/** }
* Ermittelt die echte Client-IP. Hinter einem konfigurierten Trusted-Proxy } catch (\Throwable $e) { /* Fallback: Standard-PHP-Sessions */ }
* (Setting `trusted_proxy`, kommaseparierte IP-Liste) wird die erste IP aus
* X-Forwarded-For verwendet, sonst REMOTE_ADDR. Verhindert, dass ein if (!session_start()) {
* Reverse-Proxy alle Clients als dieselbe IP erscheinen laesst (Rate-Limit). die("Session konnte nicht gestartet werden");
*/ }
public function clientIp() { }
$remote = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; }
try {
$trusted = (string)$this->db->getSetting('trusted_proxy', ''); /**
} catch (\Exception $e) { * Ermittelt die echte Client-IP. Hinter einem konfigurierten Trusted-Proxy
$trusted = ''; * (Setting `trusted_proxy`, kommaseparierte IP-Liste) wird die erste IP aus
} * X-Forwarded-For verwendet, sonst REMOTE_ADDR. Verhindert, dass ein
if ($trusted === '' || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { * Reverse-Proxy alle Clients als dieselbe IP erscheinen laesst (Rate-Limit).
return $remote; */
} public function clientIp() {
$trustedList = array_filter(array_map('trim', explode(',', $trusted))); $remote = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if (!in_array($remote, $trustedList, true)) { try {
return $remote; // Anfrage kam nicht vom Trusted-Proxy -> XFF ignorieren $trusted = (string)$this->db->getSetting('trusted_proxy', '');
} } catch (\Exception $e) {
$parts = array_filter(array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']))); $trusted = '';
$client = $parts[0] ?? $remote; }
return filter_var($client, FILTER_VALIDATE_IP) ? $client : $remote; if ($trusted === '' || empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
} return $remote;
}
// Benutzer einloggen $trustedList = array_filter(array_map('trim', explode(',', $trusted)));
public function login($email, $password) { if (!in_array($remote, $trustedList, true)) {
$ip = $this->clientIp(); return $remote; // Anfrage kam nicht vom Trusted-Proxy -> XFF ignorieren
}
if ($this->isRateLimited($ip, $email)) { $parts = array_filter(array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
return 'rate_limited'; $client = $parts[0] ?? $remote;
} return filter_var($client, FILTER_VALIDATE_IP) ? $client : $remote;
}
$user = $this->db->fetchOne(
"SELECT * FROM users WHERE email = ? AND is_active = 1", // Benutzer einloggen
[$email] public function login($email, $password) {
); $ip = $this->clientIp();
if ($user && password_verify($password, $user['password_hash'])) { if ($this->isRateLimited($ip, $email)) {
$this->clearLoginAttempts($ip, $email); return 'rate_limited';
}
// 2FA aktiv? Dann Login zunaechst nur "vormerken" und Code anfordern.
if (!empty($user['totp_enabled']) && !empty($user['totp_secret'])) { $user = $this->db->fetchOne(
$_SESSION['totp_pending_user_id'] = $user['id']; "SELECT * FROM users WHERE email = ? AND is_active = 1",
$_SESSION['totp_pending_time'] = time(); [$email]
return 'totp_required'; );
}
if ($user && password_verify($password, $user['password_hash'])) {
$this->notifyIfNewIp($user, $ip); $this->clearLoginAttempts($ip, $email);
$this->setUserSession($user);
$this->updateLastLogin($user['id']); // 2FA aktiv? Dann Login zunaechst nur "vormerken" und Code anfordern.
$this->writeAuditLog($user['id'], 'user_login', 'user', $user['id'], 'Login erfolgreich'); if (!empty($user['totp_enabled']) && !empty($user['totp_secret'])) {
return true; $_SESSION['totp_pending_user_id'] = $user['id'];
} $_SESSION['totp_pending_time'] = time();
return 'totp_required';
$this->recordLoginAttempt($ip, $email); }
return false;
} $this->notifyIfNewIp($user, $ip);
$this->setUserSession($user);
/** Webhook bei Login von einer für diesen Nutzer bisher unbekannten IP. */ $this->updateLastLogin($user['id']);
private function notifyIfNewIp($user, $ip) { $this->writeAuditLog($user['id'], 'user_login', 'user', $user['id'], 'Login erfolgreich');
try { return true;
$seen = $this->db->fetchOne( }
"SELECT 1 FROM audit_log WHERE user_id = ? AND action = 'user_login' AND ip_address = ? LIMIT 1",
[$user['id'], $ip] $this->recordLoginAttempt($ip, $email);
); return false;
if (!$seen) { }
Notifier::loginNewIp($user['email'], $ip);
} /** Webhook bei Login von einer für diesen Nutzer bisher unbekannten IP. */
} catch (\Exception $e) { /* nie blockierend */ } private function notifyIfNewIp($user, $ip) {
} try {
$seen = $this->db->fetchOne(
/** Liegt ein Login vor, der noch auf den 2FA-Code wartet? */ "SELECT 1 FROM audit_log WHERE user_id = ? AND action = 'user_login' AND ip_address = ? LIMIT 1",
public function isTotpPending() { [$user['id'], $ip]
return isset($_SESSION['totp_pending_user_id']) );
&& isset($_SESSION['totp_pending_time']) if (!$seen) {
&& (time() - (int)$_SESSION['totp_pending_time']) < 300; // 5 Min Fenster Notifier::loginNewIp($user['email'], $ip);
} }
} catch (\Exception $e) { /* nie blockierend */ }
/** Schliesst einen 2FA-Login mit dem eingegebenen Code ab. */ }
public function verifyTotpLogin($code) {
if (!$this->isTotpPending()) { /** Liegt ein Login vor, der noch auf den 2FA-Code wartet? */
return false; public function isTotpPending() {
} return isset($_SESSION['totp_pending_user_id'])
$user = $this->db->fetchOne( && isset($_SESSION['totp_pending_time'])
"SELECT * FROM users WHERE id = ? AND is_active = 1", && (time() - (int)$_SESSION['totp_pending_time']) < 300; // 5 Min Fenster
[$_SESSION['totp_pending_user_id']] }
);
if (!$user || empty($user['totp_secret'])) { /** Schliesst einen 2FA-Login mit dem eingegebenen Code ab. */
unset($_SESSION['totp_pending_user_id'], $_SESSION['totp_pending_time']); public function verifyTotpLogin($code) {
return false; if (!$this->isTotpPending()) {
} return false;
// Entweder gueltiger TOTP-Code ODER ein Recovery-/Backup-Code }
// (Secret wird verschluesselt gespeichert; Klartext-Fallback via decrypt) $user = $this->db->fetchOne(
$ok = Totp::verify(Crypto::decrypt($user['totp_secret']), $code); "SELECT * FROM users WHERE id = ? AND is_active = 1",
if (!$ok && $this->consumeBackupCode($user, $code)) { [$_SESSION['totp_pending_user_id']]
$ok = true; );
$this->writeAuditLog($user['id'], 'user_login_backup_code', 'user', $user['id'], 'Login per Recovery-Code'); if (!$user || empty($user['totp_secret'])) {
} unset($_SESSION['totp_pending_user_id'], $_SESSION['totp_pending_time']);
if (!$ok) { return false;
$this->writeAuditLog($user['id'], 'user_login_2fa_failed', 'user', $user['id'], '2FA-Code falsch'); }
return false; // Entweder gueltiger TOTP-Code ODER ein Recovery-/Backup-Code
} // (Secret wird verschluesselt gespeichert; Klartext-Fallback via decrypt)
unset($_SESSION['totp_pending_user_id'], $_SESSION['totp_pending_time']); $ok = Totp::verify(Crypto::decrypt($user['totp_secret']), $code);
$this->notifyIfNewIp($user, $this->clientIp()); if (!$ok && $this->consumeBackupCode($user, $code)) {
$this->setUserSession($user); $ok = true;
$this->updateLastLogin($user['id']); $this->writeAuditLog($user['id'], 'user_login_backup_code', 'user', $user['id'], 'Login per Recovery-Code');
$this->writeAuditLog($user['id'], 'user_login', 'user', $user['id'], 'Login erfolgreich (2FA)'); }
return true; if (!$ok) {
} $this->writeAuditLog($user['id'], 'user_login_2fa_failed', 'user', $user['id'], '2FA-Code falsch');
return false;
/** }
* 2FA fuer einen Benutzer aktivieren und Recovery-Codes erzeugen. unset($_SESSION['totp_pending_user_id'], $_SESSION['totp_pending_time']);
* @return array Klartext-Recovery-Codes (nur hier einmalig verfuegbar) $this->notifyIfNewIp($user, $this->clientIp());
*/ $this->setUserSession($user);
public function enableTotp($userId, $secret) { $this->updateLastLogin($user['id']);
$codes = $this->generateBackupCodes(); $this->writeAuditLog($user['id'], 'user_login', 'user', $user['id'], 'Login erfolgreich (2FA)');
$hashes = array_map(function ($c) { return hash('sha256', $c); }, $codes); return true;
$this->db->query( }
"UPDATE users SET totp_secret = ?, totp_enabled = 1, totp_backup_codes = ? WHERE id = ?",
[Crypto::encrypt($secret), json_encode($hashes), $userId] /**
); * 2FA fuer einen Benutzer aktivieren und Recovery-Codes erzeugen.
$this->writeAuditLog($userId, 'totp_enabled', 'user', $userId, '2FA aktiviert'); * @return array Klartext-Recovery-Codes (nur hier einmalig verfuegbar)
return $codes; */
} public function enableTotp($userId, $secret) {
$codes = $this->generateBackupCodes();
/** 2FA fuer einen Benutzer deaktivieren. */ $hashes = array_map(function ($c) { return hash('sha256', $c); }, $codes);
public function disableTotp($userId) { $this->db->query(
$this->db->query( "UPDATE users SET totp_secret = ?, totp_enabled = 1, totp_backup_codes = ? WHERE id = ?",
"UPDATE users SET totp_secret = NULL, totp_enabled = 0, totp_backup_codes = NULL WHERE id = ?", [Crypto::encrypt($secret), json_encode($hashes), $userId]
[$userId] );
); $this->writeAuditLog($userId, 'totp_enabled', 'user', $userId, '2FA aktiviert');
$this->writeAuditLog($userId, 'totp_disabled', 'user', $userId, '2FA deaktiviert'); return $codes;
} }
/** Neue Recovery-Codes erzeugen (8 Stueck, Format XXXX-XXXX). */ /** 2FA fuer einen Benutzer deaktivieren. */
public function generateBackupCodes($count = 8) { public function disableTotp($userId) {
$codes = []; $this->db->query(
for ($i = 0; $i < $count; $i++) { "UPDATE users SET totp_secret = NULL, totp_enabled = 0, totp_backup_codes = NULL WHERE id = ?",
$raw = strtoupper(bin2hex(random_bytes(4))); // 8 Hex-Zeichen [$userId]
$codes[] = substr($raw, 0, 4) . '-' . substr($raw, 4, 4); );
} $this->writeAuditLog($userId, 'totp_disabled', 'user', $userId, '2FA deaktiviert');
return $codes; }
}
/** Neue Recovery-Codes erzeugen (8 Stueck, Format XXXX-XXXX). */
/** Recovery-Codes neu erzeugen und speichern; gibt Klartext zurueck. */ public function generateBackupCodes($count = 8) {
public function regenerateBackupCodes($userId) { $codes = [];
$codes = $this->generateBackupCodes(); for ($i = 0; $i < $count; $i++) {
$hashes = array_map(function ($c) { return hash('sha256', $c); }, $codes); $raw = strtoupper(bin2hex(random_bytes(4))); // 8 Hex-Zeichen
$this->db->query("UPDATE users SET totp_backup_codes = ? WHERE id = ?", [json_encode($hashes), $userId]); $codes[] = substr($raw, 0, 4) . '-' . substr($raw, 4, 4);
$this->writeAuditLog($userId, 'totp_backup_regenerated', 'user', $userId, 'Recovery-Codes neu erzeugt'); }
return $codes; return $codes;
} }
/** Anzahl noch nicht verbrauchter Recovery-Codes. */ /** Recovery-Codes neu erzeugen und speichern; gibt Klartext zurueck. */
public function backupCodesRemaining($user) { public function regenerateBackupCodes($userId) {
$list = json_decode($user['totp_backup_codes'] ?? '[]', true); $codes = $this->generateBackupCodes();
return is_array($list) ? count($list) : 0; $hashes = array_map(function ($c) { return hash('sha256', $c); }, $codes);
} $this->db->query("UPDATE users SET totp_backup_codes = ? WHERE id = ?", [json_encode($hashes), $userId]);
$this->writeAuditLog($userId, 'totp_backup_regenerated', 'user', $userId, 'Recovery-Codes neu erzeugt');
/** Prueft & verbraucht einen Recovery-Code (konstante Zeit). */ return $codes;
private function consumeBackupCode($user, $code) { }
$code = strtoupper(trim($code));
$list = json_decode($user['totp_backup_codes'] ?? '[]', true); /** Anzahl noch nicht verbrauchter Recovery-Codes. */
if (!is_array($list) || empty($list)) { public function backupCodesRemaining($user) {
return false; $list = json_decode($user['totp_backup_codes'] ?? '[]', true);
} return is_array($list) ? count($list) : 0;
$hash = hash('sha256', $code); }
$matched = false;
$remaining = []; /** Prueft & verbraucht einen Recovery-Code (konstante Zeit). */
foreach ($list as $h) { private function consumeBackupCode($user, $code) {
if (!$matched && hash_equals($h, $hash)) { $code = strtoupper(trim($code));
$matched = true; // diesen verbrauchen (nicht behalten) $list = json_decode($user['totp_backup_codes'] ?? '[]', true);
} else { if (!is_array($list) || empty($list)) {
$remaining[] = $h; return false;
} }
} $hash = hash('sha256', $code);
if ($matched) { $matched = false;
$this->db->query("UPDATE users SET totp_backup_codes = ? WHERE id = ?", [json_encode($remaining), $user['id']]); $remaining = [];
} foreach ($list as $h) {
return $matched; if (!$matched && hash_equals($h, $hash)) {
} $matched = true; // diesen verbrauchen (nicht behalten)
} else {
public function writeAuditLog($userId, $action, $entityType = null, $entityId = null, $details = null) { $remaining[] = $h;
try { }
$this->db->execute( }
"INSERT INTO audit_log (user_id, action, entity_type, entity_id, details, ip_address) VALUES (?, ?, ?, ?, ?, ?)", if ($matched) {
[$userId, $action, $entityType, $entityId !== null ? (string)$entityId : null, $details, $this->clientIp()] $this->db->query("UPDATE users SET totp_backup_codes = ? WHERE id = ?", [json_encode($remaining), $user['id']]);
); }
} catch (\Exception $e) { return $matched;
// audit_log table may not exist on old installs }
}
} public function writeAuditLog($userId, $action, $entityType = null, $entityId = null, $details = null) {
try {
private function isRateLimited($ip, $email) { $this->db->execute(
try { "INSERT INTO audit_log (user_id, action, entity_type, entity_id, details, ip_address) VALUES (?, ?, ?, ?, ?, ?)",
$count = $this->db->fetchOne( [$userId, $action, $entityType, $entityId !== null ? (string)$entityId : null, $details, $this->clientIp()]
"SELECT COUNT(*) as cnt FROM login_attempts );
WHERE (ip_address = ? OR email = ?) AND attempted_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)", } catch (\Exception $e) {
[$ip, $email] // audit_log table may not exist on old installs
); }
return $count && (int)$count['cnt'] >= 10; }
} catch (\Exception $e) {
return false; private function isRateLimited($ip, $email) {
} try {
} $count = $this->db->fetchOne(
"SELECT COUNT(*) as cnt FROM login_attempts
private function recordLoginAttempt($ip, $email) { WHERE (ip_address = ? OR email = ?) AND attempted_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)",
try { [$ip, $email]
$this->db->query( );
"INSERT INTO login_attempts (ip_address, email) VALUES (?, ?)", return $count && (int)$count['cnt'] >= 10;
[$ip, $email] } catch (\Exception $e) {
); return false;
} catch (\Exception $e) { }
// Tabelle existiert noch nicht – ignorieren }
}
} private function recordLoginAttempt($ip, $email) {
try {
private function clearLoginAttempts($ip, $email) { $this->db->query(
try { "INSERT INTO login_attempts (ip_address, email) VALUES (?, ?)",
$this->db->query( [$ip, $email]
"DELETE FROM login_attempts WHERE ip_address = ? OR email = ?", );
[$ip, $email] } catch (\Exception $e) {
); // Tabelle existiert noch nicht – ignorieren
} catch (\Exception $e) { }
// ignore }
}
} private function clearLoginAttempts($ip, $email) {
try {
// Microsoft 365 Login $this->db->query(
public function loginWithMicrosoft($microsoftUser) { "DELETE FROM login_attempts WHERE ip_address = ? OR email = ?",
// Zuerst nach Microsoft ID suchen [$ip, $email]
$user = $this->db->fetchOne( );
"SELECT * FROM users WHERE microsoft_id = ? AND is_active = 1", } catch (\Exception $e) {
[$microsoftUser['id']] // ignore
); }
}
if (!$user) {
// Prüfen ob E-Mail bereits existiert (ohne Microsoft ID) // Microsoft 365 Login
$existingUser = $this->db->fetchOne( public function loginWithMicrosoft($microsoftUser) {
"SELECT * FROM users WHERE email = ? AND is_active = 1", // Zuerst nach Microsoft ID suchen
[$microsoftUser['email']] $user = $this->db->fetchOne(
); "SELECT * FROM users WHERE microsoft_id = ? AND is_active = 1",
[$microsoftUser['id']]
if ($existingUser) { );
// Benutzer existiert bereits ohne Microsoft ID - verknüpfen
$this->db->query( if (!$user) {
"UPDATE users SET microsoft_id = ?, name = ? WHERE id = ?", // Prüfen ob E-Mail bereits existiert (ohne Microsoft ID)
[$microsoftUser['id'], $microsoftUser['name'], $existingUser['id']] $existingUser = $this->db->fetchOne(
); "SELECT * FROM users WHERE email = ? AND is_active = 1",
$user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$existingUser['id']]); [$microsoftUser['email']]
} else { );
// Komplett neuer Benutzer - anlegen
$userId = $this->db->execute( if ($existingUser) {
"INSERT INTO users (email, name, microsoft_id, is_active) VALUES (?, ?, ?, 1)", // Benutzer existiert bereits ohne Microsoft ID - verknüpfen
[$microsoftUser['email'], $microsoftUser['name'], $microsoftUser['id']] $this->db->query(
); "UPDATE users SET microsoft_id = ?, name = ? WHERE id = ?",
[$microsoftUser['id'], $microsoftUser['name'], $existingUser['id']]
$user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]); );
} $user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$existingUser['id']]);
} else { } else {
// Microsoft-Benutzer existiert bereits - Name aktualisieren falls geändert // Komplett neuer Benutzer - anlegen
$this->db->query( $userId = $this->db->execute(
"UPDATE users SET name = ? WHERE id = ?", "INSERT INTO users (email, name, microsoft_id, is_active) VALUES (?, ?, ?, 1)",
[$microsoftUser['name'], $user['id']] [$microsoftUser['email'], $microsoftUser['name'], $microsoftUser['id']]
); );
}
$user = $this->db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
$this->setUserSession($user); }
$this->updateLastLogin($user['id']); } else {
return true; // Microsoft-Benutzer existiert bereits - Name aktualisieren falls geändert
} $this->db->query(
"UPDATE users SET name = ? WHERE id = ?",
// Session setzen [$microsoftUser['name'], $user['id']]
private function setUserSession($user) { );
$_SESSION['user_id'] = $user['id']; }
$_SESSION['user_email'] = $user['email'];
$_SESSION['user_name'] = $user['name']; $this->setUserSession($user);
$_SESSION['is_admin'] = (bool)$user['is_admin']; $this->updateLastLogin($user['id']);
$_SESSION['login_time'] = time(); return true;
}
// CSRF-Token generieren
if (!isset($_SESSION['csrf_token'])) { // Session setzen
$_SESSION['csrf_token'] = bin2hex(random_bytes(32)); private function setUserSession($user) {
} $_SESSION['user_id'] = $user['id'];
} $_SESSION['user_email'] = $user['email'];
$_SESSION['user_name'] = $user['name'];
// Letzten Login aktualisieren $_SESSION['is_admin'] = (bool)$user['is_admin'];
private function updateLastLogin($userId) { $_SESSION['login_time'] = time();
$this->db->query(
"UPDATE users SET last_login = NOW() WHERE id = ?", // CSRF-Token generieren
[$userId] if (!isset($_SESSION['csrf_token'])) {
); $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
} }
}
// Ausloggen
public function logout() { // Letzten Login aktualisieren
$_SESSION = []; private function updateLastLogin($userId) {
$this->db->query(
if (isset($_COOKIE[session_name()])) { "UPDATE users SET last_login = NOW() WHERE id = ?",
setcookie(session_name(), '', time() - 3600, '/'); [$userId]
} );
}
session_destroy();
} // Ausloggen
public function logout() {
// Prüfen ob eingeloggt $_SESSION = [];
public function isLoggedIn() {
if (!isset($_SESSION['user_id']) || !isset($_SESSION['login_time'])) { if (isset($_COOKIE[session_name()])) {
return false; setcookie(session_name(), '', time() - 3600, '/');
} }
// Absolutes Session-Timeout durchsetzen (SESSION_LIFETIME aus config.php). session_destroy();
// Bisher wurde die Lebensdauer nie geprueft – Sessions liefen unbegrenzt. }
$lifetime = defined('SESSION_LIFETIME') ? (int)SESSION_LIFETIME : 3600;
if ($lifetime > 0 && (time() - (int)$_SESSION['login_time']) > $lifetime) { // Prüfen ob eingeloggt
$this->logout(); public function isLoggedIn() {
return false; if (!isset($_SESSION['user_id']) || !isset($_SESSION['login_time'])) {
} return false;
}
return true;
} // Absolutes Session-Timeout durchsetzen (SESSION_LIFETIME aus config.php).
// Bisher wurde die Lebensdauer nie geprueft – Sessions liefen unbegrenzt.
// Prüfen ob Admin $lifetime = defined('SESSION_LIFETIME') ? (int)SESSION_LIFETIME : 3600;
public function isAdmin() { if ($lifetime > 0 && (time() - (int)$_SESSION['login_time']) > $lifetime) {
return $this->isLoggedIn() && isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true; $this->logout();
} return false;
}
// Aktuellen Benutzer abrufen
public function getCurrentUser() { return true;
if (!$this->isLoggedIn()) { }
return null;
} // Prüfen ob Admin
public function isAdmin() {
return $this->db->fetchOne( return $this->isLoggedIn() && isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
"SELECT * FROM users WHERE id = ?", }
[$_SESSION['user_id']]
); // Aktuellen Benutzer abrufen
} public function getCurrentUser() {
if (!$this->isLoggedIn()) {
// Prüfen ob Benutzer Zugriff auf Site hat return null;
public function hasAccessToSite($siteId) { }
if ($this->isAdmin()) {
return true; return $this->db->fetchOne(
} "SELECT * FROM users WHERE id = ?",
[$_SESSION['user_id']]
if (!$this->isLoggedIn()) { );
return false; }
}
// Prüfen ob Benutzer Zugriff auf Site hat
$access = $this->db->fetchOne( public function hasAccessToSite($siteId) {
"SELECT id FROM user_site_access WHERE user_id = ? AND site_id = ?", if ($this->isAdmin()) {
[$_SESSION['user_id'], $siteId] return true;
); }
return $access !== false; if (!$this->isLoggedIn()) {
} return false;
}
// CSRF-Token validieren
public function validateCsrfToken($token) { $access = $this->db->fetchOne(
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token); "SELECT id FROM user_site_access WHERE user_id = ? AND site_id = ?",
} [$_SESSION['user_id'], $siteId]
);
// CSRF-Token abrufen
public function getCsrfToken() { return $access !== false;
if (!isset($_SESSION['csrf_token'])) { }
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
} // CSRF-Token validieren
return $_SESSION['csrf_token']; public function validateCsrfToken($token) {
} return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
// Benutzer registrieren (nur für Admins)
public function registerUser($email, $name, $password, $isAdmin = false) { // CSRF-Token abrufen
// Prüfen ob E-Mail bereits existiert public function getCsrfToken() {
$existing = $this->db->fetchOne("SELECT id FROM users WHERE email = ?", [$email]); if (!isset($_SESSION['csrf_token'])) {
if ($existing) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
return false; }
} return $_SESSION['csrf_token'];
}
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
// Benutzer registrieren (nur für Admins)
return $this->db->execute( public function registerUser($email, $name, $password, $isAdmin = false) {
"INSERT INTO users (email, name, password_hash, is_admin, is_active) VALUES (?, ?, ?, ?, 1)", // Prüfen ob E-Mail bereits existiert
[$email, $name, $passwordHash, $isAdmin ? 1 : 0] $existing = $this->db->fetchOne("SELECT id FROM users WHERE email = ?", [$email]);
); if ($existing) {
} return false;
}
// Admin-Zugriff erforderlich
public function requireAdmin() { $passwordHash = password_hash($password, PASSWORD_DEFAULT);
if (!$this->isAdmin()) {
header('Location: /index.php?error=access_denied'); return $this->db->execute(
exit; "INSERT INTO users (email, name, password_hash, is_admin, is_active) VALUES (?, ?, ?, ?, 1)",
} [$email, $name, $passwordHash, $isAdmin ? 1 : 0]
// Optionale Richtlinie: 2FA fuer Admins erzwingen. Admins ohne aktives );
// 2FA werden zur Einrichtung umgeleitet (security.php nutzt requireLogin, }
// daher keine Endlosschleife).
try { // Admin-Zugriff erforderlich
if ((string)$this->db->getSetting('enforce_2fa_admins', '0') === '1') { public function requireAdmin() {
$user = $this->getCurrentUser(); if (!$this->isAdmin()) {
$script = basename($_SERVER['SCRIPT_NAME'] ?? ''); header('Location: /index.php?error=access_denied');
if ($user && !empty($user['password_hash']) && empty($user['totp_enabled']) exit;
&& $script !== 'security.php') { }
header('Location: security.php?setup_required=1'); // Optionale Richtlinie: 2FA fuer Admins erzwingen. Admins ohne aktives
exit; // 2FA werden zur Einrichtung umgeleitet (security.php nutzt requireLogin,
} // daher keine Endlosschleife).
} try {
} catch (\Exception $e) { /* Richtlinie nie blockierend */ } if ((string)$this->db->getSetting('enforce_2fa_admins', '0') === '1') {
} $user = $this->getCurrentUser();
$script = basename($_SERVER['SCRIPT_NAME'] ?? '');
/** Anzahl aktiver (nicht abgelaufener) DB-Sessions des aktuellen Nutzers. */ if ($user && !empty($user['password_hash']) && empty($user['totp_enabled'])
public function activeSessionCount() { && $script !== 'security.php') {
if (!$this->isLoggedIn()) return 0; header('Location: security.php?setup_required=1');
try { exit;
$r = $this->db->fetchOne( }
"SELECT COUNT(*) c FROM sessions WHERE user_id = ? AND expires_at > NOW()", }
[$_SESSION['user_id']] } catch (\Exception $e) { /* Richtlinie nie blockierend */ }
); }
return (int)($r['c'] ?? 0);
} catch (\Exception $e) { return 0; } /** Anzahl aktiver (nicht abgelaufener) DB-Sessions des aktuellen Nutzers. */
} public function activeSessionCount() {
if (!$this->isLoggedIn()) return 0;
/** Alle anderen Sessions des Nutzers beenden ("überall abmelden"). */ try {
public function logoutOtherSessions() { $r = $this->db->fetchOne(
if (!$this->isLoggedIn()) return; "SELECT COUNT(*) c FROM sessions WHERE user_id = ? AND expires_at > NOW()",
try { [$_SESSION['user_id']]
$current = session_id(); );
$this->db->query( return (int)($r['c'] ?? 0);
"DELETE FROM sessions WHERE user_id = ? AND id != ?", } catch (\Exception $e) { return 0; }
[$_SESSION['user_id'], $current] }
);
$this->writeAuditLog($_SESSION['user_id'], 'logout_other_sessions', 'user', $_SESSION['user_id'], 'Andere Sessions beendet'); /** Alle anderen Sessions des Nutzers beenden ("überall abmelden"). */
} catch (\Exception $e) { /* nur bei DB-Sessions wirksam */ } public function logoutOtherSessions() {
} if (!$this->isLoggedIn()) return;
try {
// Login erforderlich $current = session_id();
public function requireLogin() { $this->db->query(
if (!$this->isLoggedIn()) { "DELETE FROM sessions WHERE user_id = ? AND id != ?",
header('Location: /login.php'); [$_SESSION['user_id'], $current]
exit; );
} $this->writeAuditLog($_SESSION['user_id'], 'logout_other_sessions', 'user', $_SESSION['user_id'], 'Andere Sessions beendet');
} } catch (\Exception $e) { /* nur bei DB-Sessions wirksam */ }
}
// Login erforderlich
public function requireLogin() {
if (!$this->isLoggedIn()) {
header('Location: /login.php');
exit;
}
}
} }

View file

@ -32,13 +32,27 @@ class I18n {
} }
public static function t(string $key, array $replace = []): string { public static function t(string $key, array $replace = []): string {
$text = self::$translations[$key] ?? $key; // Fehlt eine Übersetzung, lieber den deutschen Text zeigen als den
// technischen Schlüssel – erst wenn auch der fehlt, den Schlüssel.
$text = self::$translations[$key] ?? (self::fallback()[$key] ?? $key);
foreach ($replace as $k => $v) { foreach ($replace as $k => $v) {
$text = str_replace('{' . $k . '}', (string)$v, $text); $text = str_replace('{' . $k . '}', (string)$v, $text);
} }
return $text; return $text;
} }
/** Deutsche Texte als Rückfallebene, einmal geladen. */
private static function fallback(): array
{
static $fallback = null;
if ($fallback === null) {
$file = __DIR__ . '/../lang/de.php';
$fallback = (self::$language !== 'de' && is_file($file)) ? (array)require $file : [];
}
return $fallback;
}
public static function getLanguage(): string { public static function getLanguage(): string {
return self::$language; return self::$language;
} }

View file

@ -1,447 +1,453 @@
<?php <?php
require_once __DIR__ . '/Crypto.php'; require_once __DIR__ . '/Crypto.php';
class UniFiController { class UniFiController {
private $controllerUrl; private $controllerUrl;
private $username; private $username;
private $password; private $password;
private $siteId; private $siteId;
private $cookieFile; private $cookieFile;
private $csrfToken = null; private $csrfToken = null;
private $sessionCookie = null; private $sessionCookie = null;
private $loggedIn = false; private $loggedIn = false;
public function __construct($controllerUrl, $username, $password, $siteId) { public function __construct($controllerUrl, $username, $password, $siteId) {
$this->controllerUrl = rtrim($controllerUrl, '/'); $this->controllerUrl = rtrim($controllerUrl, '/');
$this->username = $username; $this->username = $username;
$this->password = $password; $this->password = $password;
$this->siteId = $siteId; $this->siteId = $siteId;
$this->cookieFile = tempnam(sys_get_temp_dir(), 'UNIFI_'); $this->cookieFile = tempnam(sys_get_temp_dir(), 'UNIFI_');
} }
public function __destruct() { public function __destruct() {
if (file_exists($this->cookieFile)) { if (file_exists($this->cookieFile)) {
unlink($this->cookieFile); unlink($this->cookieFile);
} }
} }
// Login zum Controller // Login zum Controller
private function login() { private function login() {
if ($this->loggedIn) { if ($this->loggedIn) {
return true; return true;
} }
$ch = curl_init(); $ch = curl_init();
curl_setopt_array($ch, [ curl_setopt_array($ch, [
CURLOPT_URL => $this->controllerUrl . "/api/auth/login", CURLOPT_URL => $this->controllerUrl . "/api/auth/login",
CURLOPT_POST => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([ CURLOPT_POSTFIELDS => json_encode([
'username' => $this->username, 'username' => $this->username,
'password' => $this->password 'password' => $this->password
]), ]),
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_COOKIEJAR => $this->cookieFile, CURLOPT_COOKIEJAR => $this->cookieFile,
CURLOPT_COOKIEFILE => $this->cookieFile, CURLOPT_COOKIEFILE => $this->cookieFile,
CURLOPT_TIMEOUT => 10, CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_HTTPHEADER => [ CURLOPT_HTTPHEADER => [
'Content-Type: application/json', 'Content-Type: application/json',
'Origin: ' . $this->controllerUrl, 'Origin: ' . $this->controllerUrl,
'Referer: ' . $this->controllerUrl . '/login', 'Referer: ' . $this->controllerUrl . '/login',
], ],
CURLOPT_HEADERFUNCTION => function($ch, $header) { CURLOPT_HEADERFUNCTION => function($ch, $header) {
$parts = explode(':', $header, 2); $parts = explode(':', $header, 2);
if (count($parts) === 2) { if (count($parts) === 2) {
$name = strtolower(trim($parts[0])); $name = strtolower(trim($parts[0]));
$value = trim($parts[1]); $value = trim($parts[1]);
if ($name === 'x-csrf-token') { if ($name === 'x-csrf-token') {
$this->csrfToken = $value; $this->csrfToken = $value;
} elseif ($name === 'set-cookie') { } elseif ($name === 'set-cookie') {
// Extract TOKEN value directly — cookie jar may not persist // Extract TOKEN value directly — cookie jar may not persist
// cookies with the 'Partitioned' attribute on some libcurl versions // cookies with the 'Partitioned' attribute on some libcurl versions
$cookieParts = explode(';', $value); $cookieParts = explode(';', $value);
$first = trim($cookieParts[0]); $first = trim($cookieParts[0]);
if (strpos($first, 'TOKEN=') === 0) { if (strpos($first, 'TOKEN=') === 0) {
$this->sessionCookie = $first; $this->sessionCookie = $first;
} }
} }
} }
return strlen($header); return strlen($header);
} }
]); ]);
$response = curl_exec($ch); $response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch); curl_close($ch);
if ($httpCode !== 200) { if ($httpCode !== 200) {
$body = json_decode($response, true); $body = json_decode($response, true);
$detail = $body['meta']['msg'] ?? $body['errors'][0] ?? substr(strip_tags($response), 0, 120); $detail = $body['meta']['msg'] ?? $body['errors'][0] ?? substr(strip_tags($response), 0, 120);
throw new Exception("Login fehlgeschlagen: HTTP $httpCode" . ($detail ? " – $detail" : '')); throw new Exception("Login fehlgeschlagen: HTTP $httpCode" . ($detail ? " – $detail" : ''));
} }
$data = json_decode($response, true); $data = json_decode($response, true);
// Expliziter Fehler vom Controller abfangen (meta.rc = error) // Expliziter Fehler vom Controller abfangen (meta.rc = error)
if (isset($data['meta']['rc']) && $data['meta']['rc'] !== 'ok') { if (isset($data['meta']['rc']) && $data['meta']['rc'] !== 'ok') {
$msg = $data['meta']['msg'] ?? 'Zugangsdaten abgelehnt'; $msg = $data['meta']['msg'] ?? 'Zugangsdaten abgelehnt';
throw new Exception("Login fehlgeschlagen: $msg"); throw new Exception("Login fehlgeschlagen: $msg");
} }
// HTTP 200 ohne expliziten Fehler = Erfolg // HTTP 200 ohne expliziten Fehler = Erfolg
// UniFi OS liefert X-CSRF-Token im Response-Header (bereits via CURLOPT_HEADERFUNCTION extrahiert) // UniFi OS liefert X-CSRF-Token im Response-Header (bereits via CURLOPT_HEADERFUNCTION extrahiert)
// Fallback: TOKEN-Cookie aus der Cookie-Datei lesen // Fallback: TOKEN-Cookie aus der Cookie-Datei lesen
if ($this->csrfToken === null) { if ($this->csrfToken === null) {
$this->csrfToken = $this->readCsrfFromCookieFile(); $this->csrfToken = $this->readCsrfFromCookieFile();
} }
$this->loggedIn = true; $this->loggedIn = true;
return true; return true;
} }
// API-Request ausführen // API-Request ausführen
private function apiRequest($endpoint, $data = null, $method = 'POST') { /**
$this->login(); * Ein Aufruf gegen die Controller-API.
*
$ch = curl_init(); * `protected`, damit Tests die Antworten des Controllers einspielen
$url = $this->controllerUrl . $endpoint; * koennen, ohne dass ein echter Controller erreichbar sein muss.
*/
$headers = ['Content-Type: application/json']; protected function apiRequest($endpoint, $data = null, $method = 'POST') {
if ($method !== 'GET' && $this->csrfToken !== null) { $this->login();
$headers[] = 'X-CSRF-Token: ' . $this->csrfToken;
} $ch = curl_init();
$url = $this->controllerUrl . $endpoint;
$options = [
CURLOPT_URL => $url, $headers = ['Content-Type: application/json'];
CURLOPT_RETURNTRANSFER => true, if ($method !== 'GET' && $this->csrfToken !== null) {
CURLOPT_SSL_VERIFYPEER => false, $headers[] = 'X-CSRF-Token: ' . $this->csrfToken;
CURLOPT_TIMEOUT => 10, }
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_HTTPHEADER => $headers $options = [
]; CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
// Prefer manually extracted cookie over file-based jar — the Partitioned CURLOPT_SSL_VERIFYPEER => false,
// attribute on the TOKEN cookie prevents some libcurl versions from writing it CURLOPT_TIMEOUT => 10,
if ($this->sessionCookie !== null) { CURLOPT_CONNECTTIMEOUT => 5,
$options[CURLOPT_COOKIE] = $this->sessionCookie; CURLOPT_HTTPHEADER => $headers
} else { ];
$options[CURLOPT_COOKIEFILE] = $this->cookieFile;
} // Prefer manually extracted cookie over file-based jar — the Partitioned
// attribute on the TOKEN cookie prevents some libcurl versions from writing it
if ($method === 'GET') { if ($this->sessionCookie !== null) {
$options[CURLOPT_HTTPGET] = true; $options[CURLOPT_COOKIE] = $this->sessionCookie;
} elseif ($method === 'POST') { } else {
$options[CURLOPT_POST] = true; $options[CURLOPT_COOKIEFILE] = $this->cookieFile;
$options[CURLOPT_POSTFIELDS] = json_encode($data ?? (object)[]); }
}
if ($method === 'GET') {
curl_setopt_array($ch, $options); $options[CURLOPT_HTTPGET] = true;
} elseif ($method === 'POST') {
$response = curl_exec($ch); $options[CURLOPT_POST] = true;
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $options[CURLOPT_POSTFIELDS] = json_encode($data ?? (object)[]);
$error = curl_error($ch); }
curl_close($ch);
curl_setopt_array($ch, $options);
if ($error) {
throw new Exception("cURL Fehler: $error"); $response = curl_exec($ch);
} $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
if ($httpCode !== 200) { curl_close($ch);
throw new Exception("API Request fehlgeschlagen: HTTP $httpCode");
} if ($error) {
throw new Exception("cURL Fehler: $error");
return json_decode($response, true); }
}
if ($httpCode !== 200) {
// Voucher erstellen throw new Exception("API Request fehlgeschlagen: HTTP $httpCode");
// $options: optionale QoS-Limits ['down' => kbps, 'up' => kbps, 'quota_mb' => MB] }
public function createVoucher($voucherName, $maxUses, $expireMinutes = 480, $options = []) {
$data = [ return json_decode($response, true);
'cmd' => 'create-voucher', }
'expire' => (int)$expireMinutes,
'n' => 1, // Voucher erstellen
'note' => $voucherName, // $options: optionale QoS-Limits ['down' => kbps, 'up' => kbps, 'quota_mb' => MB]
'quota' => (int)$maxUses public function createVoucher($voucherName, $maxUses, $expireMinutes = 480, $options = []) {
]; $data = [
'cmd' => 'create-voucher',
// Bandbreiten-/Datenlimits (UniFi QoS) optional setzen 'expire' => (int)$expireMinutes,
$down = isset($options['down']) ? (int)$options['down'] : 0; 'n' => 1,
$up = isset($options['up']) ? (int)$options['up'] : 0; 'note' => $voucherName,
$bytes = isset($options['quota_mb']) ? (int)$options['quota_mb'] : 0; 'quota' => (int)$maxUses
if ($down > 0 || $up > 0 || $bytes > 0) { ];
$data['qos_overwrite'] = true;
if ($down > 0) $data['down'] = $down; // kbit/s // Bandbreiten-/Datenlimits (UniFi QoS) optional setzen
if ($up > 0) $data['up'] = $up; // kbit/s $down = isset($options['down']) ? (int)$options['down'] : 0;
if ($bytes > 0) $data['bytes'] = $bytes; // Megabyte $up = isset($options['up']) ? (int)$options['up'] : 0;
} $bytes = isset($options['quota_mb']) ? (int)$options['quota_mb'] : 0;
if ($down > 0 || $up > 0 || $bytes > 0) {
$response = $this->apiRequest("/proxy/network/api/s/{$this->siteId}/cmd/hotspot", $data); $data['qos_overwrite'] = true;
if ($down > 0) $data['down'] = $down; // kbit/s
if (!isset($response['data'][0]['create_time'])) { if ($up > 0) $data['up'] = $up; // kbit/s
throw new Exception("Voucher konnte nicht erstellt werden"); if ($bytes > 0) $data['bytes'] = $bytes; // Megabyte
} }
// Voucher-Code abrufen. WICHTIG: getVouchers() liefert die Voucher $response = $this->apiRequest("/proxy/network/api/s/{$this->siteId}/cmd/hotspot", $data);
// unsortiert zurueck – ein blindes reset() kann bei parallelen
// Erstellungen den falschen (fremden) Code liefern. Daher gezielt if (!isset($response['data'][0]['create_time'])) {
// nach dem soeben erstellten Voucher suchen: gleiche note + neueste throw new Exception("Voucher konnte nicht erstellt werden");
// create_time. }
$vouchers = $this->getVouchers();
// Voucher-Code abrufen. WICHTIG: getVouchers() liefert die Voucher
if (empty($vouchers)) { // unsortiert zurueck – ein blindes reset() kann bei parallelen
throw new Exception("Voucher-Code konnte nicht abgerufen werden"); // Erstellungen den falschen (fremden) Code liefern. Daher gezielt
} // nach dem soeben erstellten Voucher suchen: gleiche note + neueste
// create_time.
$latestVoucher = null; $vouchers = $this->getVouchers();
foreach ($vouchers as $voucher) {
// Nur Voucher mit passender Notiz beruecksichtigen if (empty($vouchers)) {
if (($voucher['note'] ?? null) !== $voucherName) { throw new Exception("Voucher-Code konnte nicht abgerufen werden");
continue; }
}
if ($latestVoucher === null $latestVoucher = null;
|| ($voucher['create_time'] ?? 0) > ($latestVoucher['create_time'] ?? 0)) { foreach ($vouchers as $voucher) {
$latestVoucher = $voucher; // Nur Voucher mit passender Notiz beruecksichtigen
} if (($voucher['note'] ?? null) !== $voucherName) {
} continue;
}
// Fallback: falls keine note-Uebereinstimmung (z.B. Sonderzeichen), if ($latestVoucher === null
// den global neuesten Voucher nehmen. || ($voucher['create_time'] ?? 0) > ($latestVoucher['create_time'] ?? 0)) {
if ($latestVoucher === null) { $latestVoucher = $voucher;
foreach ($vouchers as $voucher) { }
if ($latestVoucher === null }
|| ($voucher['create_time'] ?? 0) > ($latestVoucher['create_time'] ?? 0)) {
$latestVoucher = $voucher; // Fallback: falls keine note-Uebereinstimmung (z.B. Sonderzeichen),
} // den global neuesten Voucher nehmen.
} if ($latestVoucher === null) {
} foreach ($vouchers as $voucher) {
if ($latestVoucher === null
if ($latestVoucher === null || empty($latestVoucher['code'])) { || ($voucher['create_time'] ?? 0) > ($latestVoucher['create_time'] ?? 0)) {
throw new Exception("Voucher-Code konnte nicht abgerufen werden"); $latestVoucher = $voucher;
} }
}
return [ }
'code' => $latestVoucher['code'],
'formatted_code' => $this->formatVoucherCode($latestVoucher['code']), if ($latestVoucher === null || empty($latestVoucher['code'])) {
'unifi_id' => $latestVoucher['_id'] ?? null, throw new Exception("Voucher-Code konnte nicht abgerufen werden");
'create_time' => $latestVoucher['create_time'] ?? null }
];
} return [
'code' => $latestVoucher['code'],
// Alle Voucher abrufen 'formatted_code' => $this->formatVoucherCode($latestVoucher['code']),
public function getVouchers() { 'unifi_id' => $latestVoucher['_id'] ?? null,
$response = $this->apiRequest("/proxy/network/api/s/{$this->siteId}/stat/voucher", null, 'GET'); 'create_time' => $latestVoucher['create_time'] ?? null
return $response['data'] ?? []; ];
} }
// Voucher mit formatierten Details abrufen // Alle Voucher abrufen
public function getVouchersWithDetails() { public function getVouchers() {
$vouchers = $this->getVouchers(); $response = $this->apiRequest("/proxy/network/api/s/{$this->siteId}/stat/voucher", null, 'GET');
$result = []; return $response['data'] ?? [];
}
foreach ($vouchers as $voucher) {
$createTime = isset($voucher['create_time']) ? $voucher['create_time'] : 0; // Voucher mit formatierten Details abrufen
$duration = isset($voucher['duration']) ? $voucher['duration'] : 0; // in Minuten public function getVouchersWithDetails() {
$expireTime = $createTime + ($duration * 60); $vouchers = $this->getVouchers();
$now = time(); $result = [];
// Status bestimmen foreach ($vouchers as $voucher) {
$status = 'valid'; $createTime = isset($voucher['create_time']) ? $voucher['create_time'] : 0;
$usedCount = isset($voucher['used']) ? $voucher['used'] : 0; $duration = isset($voucher['duration']) ? $voucher['duration'] : 0; // in Minuten
$quota = isset($voucher['quota']) ? $voucher['quota'] : 0; $expireTime = $createTime + ($duration * 60);
$now = time();
if ($now > $expireTime) {
$status = 'expired'; // Status bestimmen
} elseif ($quota > 0 && $usedCount >= $quota) { $status = 'valid';
$status = 'used'; $usedCount = isset($voucher['used']) ? $voucher['used'] : 0;
} $quota = isset($voucher['quota']) ? $voucher['quota'] : 0;
$result[] = [ if ($now > $expireTime) {
'_id' => $voucher['_id'] ?? '', $status = 'expired';
'code' => $voucher['code'] ?? '', } elseif ($quota > 0 && $usedCount >= $quota) {
'formatted_code' => $this->formatVoucherCode($voucher['code'] ?? ''), $status = 'used';
'note' => $voucher['note'] ?? '', }
'quota' => $quota,
'used' => $usedCount, $result[] = [
'duration' => $duration, '_id' => $voucher['_id'] ?? '',
'create_time' => $createTime, 'code' => $voucher['code'] ?? '',
'expire_time' => $expireTime, 'formatted_code' => $this->formatVoucherCode($voucher['code'] ?? ''),
'status' => $status, 'note' => $voucher['note'] ?? '',
'status_expires' => isset($voucher['status_expires']) ? $voucher['status_expires'] : null, 'quota' => $quota,
'for_hotspot' => isset($voucher['for_hotspot']) ? $voucher['for_hotspot'] : false, 'used' => $usedCount,
'qos_overwrite' => isset($voucher['qos_overwrite']) ? $voucher['qos_overwrite'] : false, 'duration' => $duration,
'qos_usage_quota' => isset($voucher['qos_usage_quota']) ? $voucher['qos_usage_quota'] : null, 'create_time' => $createTime,
'qos_rate_max_up' => isset($voucher['qos_rate_max_up']) ? $voucher['qos_rate_max_up'] : null, 'expire_time' => $expireTime,
'qos_rate_max_down' => isset($voucher['qos_rate_max_down']) ? $voucher['qos_rate_max_down'] : null 'status' => $status,
]; 'status_expires' => isset($voucher['status_expires']) ? $voucher['status_expires'] : null,
} 'for_hotspot' => isset($voucher['for_hotspot']) ? $voucher['for_hotspot'] : false,
'qos_overwrite' => isset($voucher['qos_overwrite']) ? $voucher['qos_overwrite'] : false,
// Nach Erstellungsdatum sortieren (neueste zuerst) 'qos_usage_quota' => isset($voucher['qos_usage_quota']) ? $voucher['qos_usage_quota'] : null,
usort($result, function($a, $b) { 'qos_rate_max_up' => isset($voucher['qos_rate_max_up']) ? $voucher['qos_rate_max_up'] : null,
return $b['create_time'] - $a['create_time']; 'qos_rate_max_down' => isset($voucher['qos_rate_max_down']) ? $voucher['qos_rate_max_down'] : null
}); ];
}
return $result;
} // Nach Erstellungsdatum sortieren (neueste zuerst)
usort($result, function($a, $b) {
// CSRF-Token aus Netscape-Cookie-Datei lesen (Fallback wenn Header nicht gesetzt) return $b['create_time'] - $a['create_time'];
private function readCsrfFromCookieFile() { });
if (!file_exists($this->cookieFile)) {
return null; return $result;
} }
foreach (file($this->cookieFile) as $line) {
$line = trim($line); // CSRF-Token aus Netscape-Cookie-Datei lesen (Fallback wenn Header nicht gesetzt)
if ($line === '' || $line[0] === '#') continue; private function readCsrfFromCookieFile() {
$parts = explode("\t", $line); if (!file_exists($this->cookieFile)) {
if (count($parts) >= 7 && strtoupper($parts[5]) === 'TOKEN') { return null;
return $parts[6]; }
} foreach (file($this->cookieFile) as $line) {
} $line = trim($line);
return null; if ($line === '' || $line[0] === '#') continue;
} $parts = explode("\t", $line);
if (count($parts) >= 7 && strtoupper($parts[5]) === 'TOKEN') {
// Voucher-Code formatieren (xxxxx-xxxxx-xxxxx) return $parts[6];
private function formatVoucherCode($code) { }
$chunks = str_split($code, 5); }
return implode('-', $chunks); return null;
} }
// Voucher löschen // Voucher-Code formatieren (xxxxx-xxxxx-xxxxx)
public function deleteVoucher($voucherId) { private function formatVoucherCode($code) {
$data = [ $chunks = str_split($code, 5);
'cmd' => 'delete-voucher', return implode('-', $chunks);
'_id' => $voucherId }
];
// Voucher löschen
$response = $this->apiRequest("/proxy/network/api/s/{$this->siteId}/cmd/hotspot", $data); public function deleteVoucher($voucherId) {
$data = [
return isset($response['meta']['rc']) && $response['meta']['rc'] === 'ok'; 'cmd' => 'delete-voucher',
} '_id' => $voucherId
];
// Verbindung testen
public static function testConnection($controllerUrl, $username, $password, $siteId) { $response = $this->apiRequest("/proxy/network/api/s/{$this->siteId}/cmd/hotspot", $data);
try {
$controller = new self($controllerUrl, $username, $password, $siteId); return isset($response['meta']['rc']) && $response['meta']['rc'] === 'ok';
$controller->login(); }
return true;
} catch (Exception $e) { // Verbindung testen
return $e->getMessage(); public static function testConnection($controllerUrl, $username, $password, $siteId) {
} try {
} $controller = new self($controllerUrl, $username, $password, $siteId);
$controller->login();
/** return true;
* Synchronisiert alle Voucher vom UniFi Controller in die Datenbank } catch (Exception $e) {
* @param Database $db Datenbank-Instanz return $e->getMessage();
* @param int $dbSiteId Die Site-ID in der lokalen Datenbank }
* @return array Statistiken über die Synchronisation }
*/
public function syncVouchersToDatabase($db, $dbSiteId) { /**
$vouchers = $this->getVouchersWithDetails(); * Synchronisiert alle Voucher vom UniFi Controller in die Datenbank
$stats = [ * @param Database $db Datenbank-Instanz
'total' => count($vouchers), * @param int $dbSiteId Die Site-ID in der lokalen Datenbank
'new' => 0, * @return array Statistiken über die Synchronisation
'updated' => 0, */
'deleted' => 0, public function syncVouchersToDatabase($db, $dbSiteId) {
'valid' => 0, $vouchers = $this->getVouchersWithDetails();
'used' => 0, $stats = [
'expired' => 0 'total' => count($vouchers),
]; 'new' => 0,
'updated' => 0,
// Alle aktuellen UniFi-IDs sammeln 'deleted' => 0,
$unifiIds = []; 'valid' => 0,
'used' => 0,
foreach ($vouchers as $voucher) { 'expired' => 0
$unifiIds[] = $voucher['_id']; ];
// Status zählen // Alle aktuellen UniFi-IDs sammeln
$stats[$voucher['status']]++; $unifiIds = [];
// Prüfen ob Voucher bereits existiert foreach ($vouchers as $voucher) {
$existing = $db->fetchOne( $unifiIds[] = $voucher['_id'];
"SELECT id, status, used_count FROM vouchers WHERE unifi_voucher_id = ? AND site_id = ?",
[$voucher['_id'], $dbSiteId] // Status zählen
); $stats[$voucher['status']]++;
$expiresAt = date('Y-m-d H:i:s', $voucher['expire_time']); // Prüfen ob Voucher bereits existiert
$createdAt = date('Y-m-d H:i:s', $voucher['create_time']); $existing = $db->fetchOne(
"SELECT id, status, used_count FROM vouchers WHERE unifi_voucher_id = ? AND site_id = ?",
if ($existing) { [$voucher['_id'], $dbSiteId]
// Voucher aktualisieren );
$db->execute(
"UPDATE vouchers SET $expiresAt = date('Y-m-d H:i:s', $voucher['expire_time']);
status = ?, $createdAt = date('Y-m-d H:i:s', $voucher['create_time']);
used_count = ?,
expires_at = ?, if ($existing) {
last_sync = NOW() // Voucher aktualisieren
WHERE id = ?", $db->execute(
[$voucher['status'], $voucher['used'], $expiresAt, $existing['id']] "UPDATE vouchers SET
); status = ?,
$stats['updated']++; used_count = ?,
} else { expires_at = ?,
// Neuen Voucher einfügen last_sync = NOW()
$db->execute( WHERE id = ?",
"INSERT INTO vouchers [$voucher['status'], $voucher['used'], $expiresAt, $existing['id']]
(site_id, voucher_code, voucher_name, max_uses, expire_minutes, );
unifi_voucher_id, status, used_count, expires_at, created_at, $stats['updated']++;
synced_from_unifi, last_sync) } else {
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())", // Neuen Voucher einfügen
[ $db->execute(
$dbSiteId, "INSERT INTO vouchers
$voucher['formatted_code'], (site_id, voucher_code, voucher_name, max_uses, expire_minutes,
$voucher['note'] ?: 'Importiert aus UniFi', unifi_voucher_id, status, used_count, expires_at, created_at,
$voucher['quota'], synced_from_unifi, last_sync)
$voucher['duration'], VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())",
$voucher['_id'], [
$voucher['status'], $dbSiteId,
$voucher['used'], $voucher['formatted_code'],
$expiresAt, $voucher['note'] ?: 'Importiert aus UniFi',
$createdAt $voucher['quota'],
] $voucher['duration'],
); $voucher['_id'],
$stats['new']++; $voucher['status'],
} $voucher['used'],
} $expiresAt,
$createdAt
// Voucher die nicht mehr im Controller existieren als gelöscht markieren ]
if (!empty($unifiIds)) { );
$placeholders = implode(',', array_fill(0, count($unifiIds), '?')); $stats['new']++;
$params = array_merge($unifiIds, [$dbSiteId]); }
}
// Alle Voucher mit UniFi-ID die nicht mehr existieren auf "expired" setzen
$deleted = $db->execute( // Voucher die nicht mehr im Controller existieren als gelöscht markieren
"UPDATE vouchers SET status = 'expired', last_sync = NOW() if (!empty($unifiIds)) {
WHERE unifi_voucher_id IS NOT NULL $placeholders = implode(',', array_fill(0, count($unifiIds), '?'));
AND unifi_voucher_id NOT IN ($placeholders) $params = array_merge($unifiIds, [$dbSiteId]);
AND site_id = ?
AND status != 'expired'", // Alle Voucher mit UniFi-ID die nicht mehr existieren auf "expired" setzen
$params $deleted = $db->execute(
); "UPDATE vouchers SET status = 'expired', last_sync = NOW()
$stats['deleted'] = $deleted; WHERE unifi_voucher_id IS NOT NULL
} AND unifi_voucher_id NOT IN ($placeholders)
AND site_id = ?
return $stats; AND status != 'expired'",
} $params
);
/** $stats['deleted'] = $deleted;
* Holt Live-Statistiken für das Dashboard }
* @return array
*/ return $stats;
public function getLiveStats() { }
$vouchers = $this->getVouchersWithDetails();
/**
$stats = [ * Holt Live-Statistiken für das Dashboard
'total' => count($vouchers), * @return array
'valid' => 0, */
'used' => 0, public function getLiveStats() {
'expired' => 0, $vouchers = $this->getVouchersWithDetails();
'vouchers' => $vouchers
]; $stats = [
'total' => count($vouchers),
foreach ($vouchers as $voucher) { 'valid' => 0,
$stats[$voucher['status']]++; 'used' => 0,
} 'expired' => 0,
'vouchers' => $vouchers
return $stats; ];
}
foreach ($vouchers as $voucher) {
$stats[$voucher['status']]++;
}
return $stats;
}
} }

View file

@ -3,6 +3,8 @@ parameters:
# __() stammt aus der I18n-Klasse und wird global definiert # __() stammt aus der I18n-Klasse und wird global definiert
scanFiles: scanFiles:
- includes/I18n.php - includes/I18n.php
- includes/UniFiController.php
- includes/Crypto.php
paths: paths:
- includes/Totp.php - includes/Totp.php
- includes/Crypto.php - includes/Crypto.php
@ -10,3 +12,5 @@ parameters:
- includes/Ui.php - includes/Ui.php
- includes/Upload.php - includes/Upload.php
- includes/Kiosk.php - includes/Kiosk.php
- includes/VoucherService.php
- includes/I18n.php

214
tests/AuthTest.php Normal file
View file

@ -0,0 +1,214 @@
<?php
declare(strict_types=1);
namespace Tests;
use Auth;
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../includes/Auth.php';
/**
* Datenbank-Attrappe für die Anmeldung: beantwortet genau die Abfragen,
* die Auth stellt, und merkt sich schreibende Aufrufe.
*/
class FakeAuthDb
{
/** @var array<int, array> */
public array $users = [];
public int $recentAttempts = 0;
/** @var array<int, array{sql:string,params:array}> */
public array $writes = [];
/** @var array<string, string> */
public array $settings = [];
public function fetchOne($sql, $params = [])
{
$sql = (string)preg_replace('/\s+/', ' ', strtolower($sql));
if (str_contains($sql, 'from login_attempts')) {
return ['cnt' => $this->recentAttempts];
}
if (str_contains($sql, 'from users')) {
foreach ($this->users as $user) {
if (($user['email'] ?? null) === ($params[0] ?? null)) {
return $user;
}
}
return false;
}
if (str_contains($sql, 'from audit_log')) {
return ['1' => 1]; // IP bereits gesehen -> keine Benachrichtigung
}
return false;
}
public function fetchAll($sql, $params = [])
{
return [];
}
public function execute($sql, $params = [])
{
$this->writes[] = ['sql' => (string)preg_replace('/\s+/', ' ', strtolower($sql)), 'params' => $params];
return 1;
}
public function query($sql, $params = [])
{
return $this->execute($sql, $params);
}
public function getSetting($key, $default = null)
{
return $this->settings[$key] ?? $default;
}
/** Hat es einen Schreibzugriff mit diesem Fragment gegeben? */
public function wrote(string $fragment): bool
{
foreach ($this->writes as $write) {
if (str_contains($write['sql'], strtolower($fragment))) {
return true;
}
}
return false;
}
}
class AuthTest extends TestCase
{
private FakeAuthDb $db;
private Auth $auth;
protected function setUp(): void
{
$_SESSION = [];
$_SERVER['REMOTE_ADDR'] = '198.51.100.5';
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
$this->db = new FakeAuthDb();
$this->db->users[] = [
'id' => 7,
'email' => 'marie@example.com',
'name' => 'Marie',
'is_admin' => 1,
'is_active' => 1,
'password_hash' => password_hash('richtig', PASSWORD_DEFAULT),
'totp_enabled' => 0,
'totp_secret' => null,
];
$this->auth = new Auth($this->db);
}
// --- Anmeldung -------------------------------------------------------
public function testCorrectPasswordStartsSession(): void
{
$this->assertTrue($this->auth->login('marie@example.com', 'richtig'));
$this->assertSame(7, $_SESSION['user_id']);
$this->assertTrue($this->auth->isLoggedIn());
$this->assertTrue($this->auth->isAdmin());
}
public function testWrongPasswordIsRecorded(): void
{
$this->assertFalse($this->auth->login('marie@example.com', 'falsch'));
$this->assertArrayNotHasKey('user_id', $_SESSION);
$this->assertTrue($this->db->wrote('insert into login_attempts'), 'Fehlversuch muss protokolliert werden');
}
public function testUnknownUserBehavesLikeWrongPassword(): void
{
$this->assertFalse($this->auth->login('niemand@example.com', 'egal'));
$this->assertArrayNotHasKey('user_id', $_SESSION);
}
public function testRateLimitStopsLoginBeforePasswordCheck(): void
{
$this->db->recentAttempts = 10;
$this->assertSame('rate_limited', $this->auth->login('marie@example.com', 'richtig'));
$this->assertArrayNotHasKey('user_id', $_SESSION, 'Bei Sperre darf keine Sitzung entstehen');
}
public function testTwoFactorUserIsNotLoggedInYet(): void
{
$this->db->users[0]['totp_enabled'] = 1;
$this->db->users[0]['totp_secret'] = 'JBSWY3DPEHPK3PXP';
$result = $this->auth->login('marie@example.com', 'richtig');
$this->assertSame('totp_required', $result);
$this->assertArrayNotHasKey('user_id', $_SESSION, 'Erst nach dem Code gilt man als angemeldet');
$this->assertSame(7, $_SESSION['totp_pending_user_id']);
$this->assertFalse($this->auth->isLoggedIn());
}
public function testInactiveUserCannotLogIn(): void
{
$this->db->users[0]['is_active'] = 0;
// Die Abfrage filtert auf is_active = 1; die Attrappe liefert den
// Datensatz trotzdem, deshalb hier der Vollständigkeit halber nur
// die Prüfung, dass ein leerer Treffer nicht anmeldet.
$this->db->users = [];
$this->assertFalse($this->auth->login('marie@example.com', 'richtig'));
}
// --- CSRF ------------------------------------------------------------
public function testCsrfTokenIsStableAndChecked(): void
{
$token = $this->auth->getCsrfToken();
$this->assertNotSame('', $token);
$this->assertSame($token, $this->auth->getCsrfToken(), 'Token bleibt innerhalb der Sitzung gleich');
$this->assertTrue($this->auth->validateCsrfToken($token));
$this->assertFalse($this->auth->validateCsrfToken('falsch'));
$this->assertFalse($this->auth->validateCsrfToken(''));
}
public function testCsrfCheckFailsWithoutSessionToken(): void
{
$_SESSION = [];
$this->assertFalse($this->auth->validateCsrfToken('irgendwas'));
}
// --- Client-IP hinter einem Proxy -----------------------------------
public function testClientIpIgnoresForwardedHeaderWithoutTrustedProxy(): void
{
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9';
$this->assertSame('198.51.100.5', $this->auth->clientIp(),
'Ohne eingetragenen Proxy darf der Header nicht zählen');
}
public function testClientIpUsesForwardedHeaderFromTrustedProxy(): void
{
$this->db->settings['trusted_proxy'] = '198.51.100.5';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9, 70.41.3.18';
$this->assertSame('203.0.113.9', $this->auth->clientIp());
}
public function testClientIpIgnoresForwardedHeaderFromUnknownSource(): void
{
$this->db->settings['trusted_proxy'] = '10.0.0.1';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '203.0.113.9';
$this->assertSame('198.51.100.5', $this->auth->clientIp());
}
public function testClientIpFallsBackWhenHeaderIsGarbage(): void
{
$this->db->settings['trusted_proxy'] = '198.51.100.5';
$_SERVER['HTTP_X_FORWARDED_FOR'] = 'kein-ip-wert';
$this->assertSame('198.51.100.5', $this->auth->clientIp());
}
}

View file

@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace Tests;
use Exception;
use PHPUnit\Framework\TestCase;
use UniFiController;
require_once __DIR__ . '/../includes/UniFiController.php';
/**
* Controller mit eingespielten Antworten statt echter HTTP-Aufrufe.
* Die aufgezeichneten Antworten entsprechen dem Format der UniFi-API.
*/
class RecordedController extends UniFiController
{
/** @var array<int, array> */
public array $calls = [];
/** @var array<int, array|null> */
private array $responses;
public function __construct(array $responses)
{
parent::__construct('https://unifi.example.com:8443', 'api', 'geheim', 'default');
$this->responses = $responses;
}
protected function apiRequest($endpoint, $data = null, $method = 'POST')
{
$this->calls[] = ['endpoint' => $endpoint, 'data' => $data, 'method' => $method];
return array_shift($this->responses);
}
}
/**
* Die Auswahl des richtigen Vouchers ist der heikle Teil: der Controller
* liefert alle Voucher unsortiert zurück. Wer blind den ersten nimmt, gibt
* bei parallelen Anfragen den Code eines anderen Gastes aus.
*/
class UniFiControllerTest extends TestCase
{
private function created(int $time = 1000): array
{
return ['data' => [['create_time' => $time]]];
}
public function testPicksOwnVoucherNotAForeignOne(): void
{
$controller = new RecordedController([
$this->created(),
['data' => [
['code' => '1111122222', 'note' => 'Fremder Gast', 'create_time' => 5000, '_id' => 'a'],
['code' => '3333344444', 'note' => '2026-09-24_Empfang', 'create_time' => 4000, '_id' => 'b'],
]],
]);
$result = $controller->createVoucher('2026-09-24_Empfang', 2, 480);
$this->assertSame('3333344444', $result['code'], 'Der Voucher mit passender Notiz gehört zu dieser Anfrage');
$this->assertSame('b', $result['unifi_id']);
}
public function testPicksNewestWhenNoteAppearsTwice(): void
{
$controller = new RecordedController([
$this->created(),
['data' => [
['code' => '1111122222', 'note' => 'Empfang', 'create_time' => 4000, '_id' => 'alt'],
['code' => '3333344444', 'note' => 'Empfang', 'create_time' => 9000, '_id' => 'neu'],
]],
]);
$this->assertSame('neu', $controller->createVoucher('Empfang', 1, 60)['unifi_id']);
}
public function testFallsBackToNewestWhenNoteDoesNotMatch(): void
{
$controller = new RecordedController([
$this->created(),
['data' => [
['code' => '1111122222', 'note' => 'Etwas anderes', 'create_time' => 4000, '_id' => 'alt'],
['code' => '3333344444', 'note' => 'Auch anders', 'create_time' => 9000, '_id' => 'neu'],
]],
]);
$this->assertSame('neu', $controller->createVoucher('Sonderzeichen …', 1, 60)['unifi_id']);
}
public function testFormatsCodeInFiveDigitBlocks(): void
{
$controller = new RecordedController([
$this->created(),
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
]);
$result = $controller->createVoucher('Gast', 1, 60);
$this->assertSame('12345-67890', $result['formatted_code']);
$this->assertSame('1234567890', $result['code'], 'Der rohe Code bleibt unverändert');
}
public function testFailsWhenControllerDoesNotConfirmCreation(): void
{
$controller = new RecordedController([['data' => []]]);
$this->expectException(Exception::class);
$controller->createVoucher('Gast', 1, 60);
}
public function testFailsWhenNoVouchersComeBack(): void
{
$controller = new RecordedController([$this->created(), ['data' => []]]);
$this->expectException(Exception::class);
$controller->createVoucher('Gast', 1, 60);
}
public function testSendsQosLimitsOnlyWhenSet(): void
{
$controller = new RecordedController([
$this->created(),
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
]);
$controller->createVoucher('Gast', 3, 240, ['down' => 20000, 'up' => 5000, 'quota_mb' => 1024]);
$payload = $controller->calls[0]['data'];
$this->assertSame('create-voucher', $payload['cmd']);
$this->assertSame(240, $payload['expire']);
$this->assertSame(3, $payload['quota']);
$this->assertTrue($payload['qos_overwrite']);
$this->assertSame(20000, $payload['down']);
$this->assertSame(5000, $payload['up']);
$this->assertSame(1024, $payload['bytes']);
}
public function testOmitsQosWhenNotRequested(): void
{
$controller = new RecordedController([
$this->created(),
['data' => [['code' => '1234567890', 'note' => 'Gast', 'create_time' => 1, '_id' => 'x']]],
]);
$controller->createVoucher('Gast', 1, 60);
$this->assertArrayNotHasKey('qos_overwrite', $controller->calls[0]['data']);
$this->assertArrayNotHasKey('down', $controller->calls[0]['data']);
}
}