Files
KnowledgeBase/app/Services/SecurityLogger.php
Knowledge Base System acf549c43c feat: 初始化知识库系统项目
- 实现基于 Laravel 11 和 Filament 3.X 的文档管理系统
- 添加用户认证和分组管理功能
- 实现文档上传、分类和权限控制
- 集成 Word 文档自动转换为 Markdown
- 集成 Meilisearch 全文搜索引擎
- 实现文档在线预览功能
- 添加安全日志和审计功能
- 完整的简体中文界面
- 包含完整的项目文档和部署指南

技术栈:
- Laravel 11.x
- Filament 3.X
- Meilisearch 1.5+
- Pandoc 文档转换
- Redis 队列系统
- Pest PHP 测试框架
2025-12-05 14:44:44 +08:00

106 lines
3.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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_type' => $document->type,
'document_group_id' => $document->group_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));
}
}