105 lines
3.1 KiB
PHP
105 lines
3.1 KiB
PHP
<?php
|
||
|
||
namespace App\Services;
|
||
|
||
use App\Models\Document;
|
||
use App\Models\User;
|
||
use Illuminate\Support\Facades\Log;
|
||
|
||
/**
|
||
* 安全日志记录服务
|
||
* 用于记录系统中的安全相关事件
|
||
*/
|
||
class SecurityLogger
|
||
{
|
||
/**
|
||
* 记录未授权的文档访问尝试
|
||
* 需求:7.3
|
||
*
|
||
* @param User $user 尝试访问的用户
|
||
* @param Document $document 被访问的文档
|
||
* @param string $action 尝试的操作 (view, download, update, delete 等)
|
||
* @param string|null $ipAddress IP 地址
|
||
* @return void
|
||
*/
|
||
public function logUnauthorizedAccess(
|
||
User $user,
|
||
Document $document,
|
||
string $action,
|
||
?string $ipAddress = null
|
||
): void {
|
||
$ipAddress = $ipAddress ?? request()->ip();
|
||
|
||
Log::channel('security')->warning('未授权访问尝试', [
|
||
'event' => 'unauthorized_access',
|
||
'action' => $action,
|
||
'user_id' => $user->id,
|
||
'user_name' => $user->name,
|
||
'user_email' => $user->email,
|
||
'document_id' => $document->id,
|
||
'document_title' => $document->title,
|
||
'document_knowledge_base_id' => $document->knowledge_base_id,
|
||
'ip_address' => $ipAddress,
|
||
'timestamp' => now()->toIso8601String(),
|
||
'user_agent' => request()->userAgent(),
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* 记录权限验证失败
|
||
*
|
||
* @param User $user 用户
|
||
* @param string $resource 资源类型
|
||
* @param int|null $resourceId 资源 ID
|
||
* @param string $action 操作
|
||
* @param string|null $reason 失败原因
|
||
* @return void
|
||
*/
|
||
public function logAuthorizationFailure(
|
||
User $user,
|
||
string $resource,
|
||
?int $resourceId,
|
||
string $action,
|
||
?string $reason = null
|
||
): void {
|
||
Log::channel('security')->warning('权限验证失败', [
|
||
'event' => 'authorization_failure',
|
||
'user_id' => $user->id,
|
||
'user_name' => $user->name,
|
||
'user_email' => $user->email,
|
||
'resource' => $resource,
|
||
'resource_id' => $resourceId,
|
||
'action' => $action,
|
||
'reason' => $reason,
|
||
'ip_address' => request()->ip(),
|
||
'timestamp' => now()->toIso8601String(),
|
||
'user_agent' => request()->userAgent(),
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* 记录可疑的访问模式
|
||
*
|
||
* @param User $user 用户
|
||
* @param string $pattern 可疑模式描述
|
||
* @param array $context 额外的上下文信息
|
||
* @return void
|
||
*/
|
||
public function logSuspiciousActivity(
|
||
User $user,
|
||
string $pattern,
|
||
array $context = []
|
||
): void {
|
||
Log::channel('security')->alert('检测到可疑活动', array_merge([
|
||
'event' => 'suspicious_activity',
|
||
'user_id' => $user->id,
|
||
'user_name' => $user->name,
|
||
'user_email' => $user->email,
|
||
'pattern' => $pattern,
|
||
'ip_address' => request()->ip(),
|
||
'timestamp' => now()->toIso8601String(),
|
||
'user_agent' => request()->userAgent(),
|
||
], $context));
|
||
}
|
||
}
|