You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.0 KiB
73 lines
2.0 KiB
|
3 days ago
|
<?php
|
||
|
|
|
||
|
|
namespace App\Http\Middleware;
|
||
|
|
|
||
|
|
use App\Models\AuditLog;
|
||
|
|
use Closure;
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
use Symfony\Component\HttpFoundation\Response;
|
||
|
|
|
||
|
|
class AuditLogMiddleware
|
||
|
|
{
|
||
|
|
public function handle(Request $request, Closure $next): Response
|
||
|
|
{
|
||
|
|
/** @var Response $response */
|
||
|
|
$response = $next($request);
|
||
|
|
|
||
|
|
if (!$this->shouldLog($request)) {
|
||
|
|
return $response;
|
||
|
|
}
|
||
|
|
|
||
|
|
$user = $request->user();
|
||
|
|
AuditLog::create([
|
||
|
|
'user_id' => $user?->id,
|
||
|
|
'username' => $user?->username ?: $user?->name,
|
||
|
|
'role' => $user?->role,
|
||
|
|
'method' => strtoupper($request->method()),
|
||
|
|
'path' => '/'.ltrim($request->path(), '/'),
|
||
|
|
'action' => strtoupper($request->method()).' '.$request->path(),
|
||
|
|
'status_code' => (int) $response->getStatusCode(),
|
||
|
|
'ip' => $request->ip(),
|
||
|
|
'user_agent' => substr((string) $request->userAgent(), 0, 500),
|
||
|
|
'request_payload' => $this->sanitizePayload($request->all()),
|
||
|
|
]);
|
||
|
|
|
||
|
|
return $response;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function shouldLog(Request $request): bool
|
||
|
|
{
|
||
|
|
if ($request->isMethod('GET')) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($request->is('api/audit-logs*')) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function sanitizePayload(array $payload): array
|
||
|
|
{
|
||
|
|
$sensitive = ['password', 'password_confirmation', 'token', 'access_token'];
|
||
|
|
$walk = function ($value) use (&$walk, $sensitive) {
|
||
|
|
if (!is_array($value)) {
|
||
|
|
return $value;
|
||
|
|
}
|
||
|
|
$result = [];
|
||
|
|
foreach ($value as $k => $v) {
|
||
|
|
if (is_string($k) && in_array(strtolower($k), $sensitive, true)) {
|
||
|
|
$result[$k] = '***';
|
||
|
|
} else {
|
||
|
|
$result[$k] = $walk($v);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return $result;
|
||
|
|
};
|
||
|
|
|
||
|
|
return $walk($payload);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|