42 lines
1.2 KiB
PHP
42 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Auth;
|
|
|
|
use App\Models\AuthAuditLog;
|
|
use App\Models\User;
|
|
use Illuminate\Http\Request;
|
|
|
|
class AuthAuditLogger
|
|
{
|
|
public function log(
|
|
string $eventType,
|
|
?Request $request,
|
|
string $status,
|
|
?string $reason = null,
|
|
?string $identifier = null,
|
|
User|int|null $user = null,
|
|
array $metadata = [],
|
|
): AuthAuditLog {
|
|
$userId = $user instanceof User ? $user->getKey() : $user;
|
|
$cleanMetadata = array_filter($metadata, static fn (mixed $value): bool => $value !== null && $value !== '');
|
|
|
|
return AuthAuditLog::query()->create([
|
|
'event_type' => $eventType,
|
|
'identifier' => $this->normalizeIdentifier($identifier),
|
|
'user_id' => $userId,
|
|
'ip' => $request?->ip(),
|
|
'user_agent' => $request?->userAgent(),
|
|
'status' => $status,
|
|
'reason' => $reason,
|
|
'metadata' => $cleanMetadata === [] ? null : $cleanMetadata,
|
|
'created_at' => now(),
|
|
]);
|
|
}
|
|
|
|
private function normalizeIdentifier(?string $identifier): ?string
|
|
{
|
|
$identifier = trim((string) $identifier);
|
|
|
|
return $identifier === '' ? null : mb_strtolower($identifier);
|
|
}
|
|
} |