Tour-Anlage robuster machen und App-Logging erweitern

This commit is contained in:
torsten 2026-11-08 17:51:55 +01:00
parent 4c9a48e79f
commit c64fa427b3
8 changed files with 232 additions and 17 deletions

View file

@ -192,6 +192,46 @@ function redirect(string $url): void
exit;
}
/**
* Schreibt einen strukturierten Eintrag in storage/logs/app-YYYY-MM-DD.log.
* Dadurch bleiben auch Fehler nachvollziehbar, die nur zu einem Redirect führen.
*/
function app_log(string $level, string $message, array $context = []): void
{
$dir = storage_path('logs');
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$user = null;
try {
$user = \App\Core\Auth::user();
} catch (\Throwable $e) {
// Logging darf die eigentliche Anfrage nicht zusätzlich abbrechen.
}
$entry = array_merge([
'time' => date('c'),
'level' => strtoupper($level),
'message' => $message,
'user_id' => $user?->id,
'user_name' => $user?->name,
'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
'method' => $_SERVER['REQUEST_METHOD'] ?? null,
'uri' => $_SERVER['REQUEST_URI'] ?? null,
'referer' => $_SERVER['HTTP_REFERER'] ?? null,
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
], $context);
$line = json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
if ($line === false || @file_put_contents($dir . '/app-' . date('Y-m-d') . '.log', $line . PHP_EOL, FILE_APPEND | LOCK_EX) === false) {
error_log('app_log: ' . ($line !== false ? $line : $message));
}
}
/** Zurück zur vorherigen Seite (fallback auf '/'). */
function back(): void
{
@ -218,6 +258,9 @@ function csrf_token(): string
function verify_csrf(): void
{
if (empty($_SESSION['_csrf'])) {
app_log('warning', 'CSRF-Token fehlt', [
'post_fields' => array_keys($_POST),
]);
http_response_code(419);
exit('CSRF-Token fehlt (Seite erneut laden).');
}
@ -225,6 +268,10 @@ function verify_csrf(): void
$token = $_POST['_token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
if (!hash_equals($_SESSION['_csrf'], $token)) {
app_log('warning', 'CSRF-Token ungültig', [
'post_fields' => array_keys($_POST),
'has_token' => $token !== '',
]);
http_response_code(419);
exit('Ungültiges CSRF-Token.');
}
@ -413,6 +460,28 @@ function validate(array $rules): array
}
if ($errors !== []) {
$files = [];
foreach ($_FILES as $field => $file) {
if (!is_array($file) || empty($file['name'])) {
continue;
}
$name = basename((string) $file['name']);
$files[$field] = [
'name' => $name,
'ext' => strtolower(pathinfo($name, PATHINFO_EXTENSION)),
'size' => (int) ($file['size'] ?? 0),
'error' => (int) ($file['error'] ?? 0),
];
}
app_log('warning', 'Validierung fehlgeschlagen', [
'errors' => $errors,
'post_fields' => array_keys($_POST),
'files' => $files,
]);
$_SESSION['_errors'] = $errors;
$_SESSION['_old'] = $_POST;
back();