Merge pull request 'Tests für Anmeldung und Controller, PHP 8.1, Sprach-Fallback' (#10) from test/coverage into main
Some checks are pending
CI / PHP Lint (push) Waiting to run
CI / PHP Lint-1 (push) Waiting to run
CI / Unit Tests & Static Analysis (push) Waiting to run
Release-Paket / ZIP bauen und veröffentlichen (push) Waiting to run

This commit is contained in:
Friederich Loheide 2026-09-24 11:13:16 +00:00
commit 88f40a3d21
10 changed files with 1344 additions and 930 deletions

View file

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

View file

@ -1,5 +1,5 @@
# UniFi Voucher Management System – Container-Image
FROM php:8.2-apache
FROM php:8.3-apache
# System-Tools (curl für Healthcheck) + PHP-Extensions
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)**
![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)
![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)
@ -147,7 +147,7 @@ Entwickelt von **[Loheide.eu](https://loheide.eu)**
| 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+ |
| Webserver | Apache / Nginx |
| UniFi | **Network Application 7.0+ mit UniFi OS** (z. B. UDM, UDR, UniFi OS Server) |
@ -591,10 +591,25 @@ Tests und statische Analyse:
```bash
composer install
vendor/bin/phpunit # 29 Tests (Crypto, TOTP, API-Keys, Upload, Ui)
vendor/bin/phpunit # 62 Tests
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
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.

View file

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

View file

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

View file

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