66 lines
1.8 KiB
PHP
66 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use PDO;
|
|
|
|
final class AuditService
|
|
{
|
|
public function __construct(private readonly PDO $pdo)
|
|
{
|
|
}
|
|
|
|
public function log(
|
|
?int $tenantId,
|
|
?int $actorUserId,
|
|
string $action,
|
|
string $targetType,
|
|
?int $targetId,
|
|
string $result,
|
|
array $meta = []
|
|
): void {
|
|
$statement = $this->pdo->prepare(
|
|
'INSERT INTO audit_events (
|
|
tenant_id,
|
|
actor_user_id,
|
|
action,
|
|
target_type,
|
|
target_id,
|
|
result,
|
|
request_id,
|
|
ip_hash,
|
|
user_agent_hash,
|
|
meta_json
|
|
) VALUES (
|
|
:tenant_id,
|
|
:actor_user_id,
|
|
:action,
|
|
:target_type,
|
|
:target_id,
|
|
:result,
|
|
:request_id,
|
|
:ip_hash,
|
|
:user_agent_hash,
|
|
:meta_json
|
|
)'
|
|
);
|
|
|
|
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
|
|
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
|
|
$requestId = $_SERVER['HTTP_X_REQUEST_ID'] ?? bin2hex(random_bytes(18));
|
|
|
|
$statement->execute([
|
|
'tenant_id' => $tenantId,
|
|
'actor_user_id' => $actorUserId,
|
|
'action' => $action,
|
|
'target_type' => $targetType,
|
|
'target_id' => $targetId,
|
|
'result' => $result,
|
|
'request_id' => substr($requestId, 0, 36),
|
|
'ip_hash' => $ip !== '' ? hash('sha256', $ip) : null,
|
|
'user_agent_hash' => $userAgent !== '' ? hash('sha256', $userAgent) : null,
|
|
'meta_json' => $meta !== [] ? json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : null,
|
|
]);
|
|
}
|
|
}
|