75 lines
2.6 KiB
Go
75 lines
2.6 KiB
Go
// Package audit 提供了用户操作审计相关的功能
|
|
package service
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
|
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
|
|
)
|
|
|
|
// AuditRequestContext 封装了审计日志所需的请求上下文信息
|
|
type AuditRequestContext struct {
|
|
ClientIP string
|
|
HTTPPath string
|
|
HTTPMethod string
|
|
}
|
|
|
|
// AuditService 定义了审计服务的接口
|
|
type AuditService interface {
|
|
LogAction(ctx context.Context, user *models.User, reqCtx AuditRequestContext, actionType, description string, targetResource interface{}, status models.AuditStatus, resultDetails string)
|
|
}
|
|
|
|
// auditService 是 AuditService 接口的实现
|
|
type auditService struct {
|
|
ctx context.Context
|
|
userActionLogRepository repository.UserActionLogRepository
|
|
}
|
|
|
|
// NewAuditService 创建一个新的审计服务实例
|
|
func NewAuditService(ctx context.Context, repo repository.UserActionLogRepository) AuditService {
|
|
return &auditService{
|
|
ctx: ctx,
|
|
userActionLogRepository: repo,
|
|
}
|
|
}
|
|
|
|
// LogAction 记录一个用户操作。它在一个新的 goroutine 中异步执行,以避免阻塞主请求。
|
|
func (s *auditService) LogAction(ctx context.Context, user *models.User, reqCtx AuditRequestContext, actionType, description string, targetResource interface{}, status models.AuditStatus, resultDetails string) {
|
|
serviceCtx, logger := logs.Trace(ctx, s.ctx, "LogAction")
|
|
|
|
// 不再从 context 中获取用户信息,直接使用传入的 user 对象
|
|
if user == nil {
|
|
logger.Warnw("无法记录审计日志:传入的用户对象为 nil")
|
|
return
|
|
}
|
|
|
|
log := &models.UserActionLog{
|
|
Time: time.Now(),
|
|
UserID: user.ID,
|
|
Username: user.Username, // 用户名快照
|
|
SourceIP: reqCtx.ClientIP,
|
|
ActionType: actionType,
|
|
Description: description,
|
|
Status: status,
|
|
HTTPPath: reqCtx.HTTPPath,
|
|
HTTPMethod: reqCtx.HTTPMethod,
|
|
ResultDetails: resultDetails,
|
|
}
|
|
|
|
// 使用模型提供的方法来设置 TargetResource
|
|
if err := log.SetTargetResource(targetResource); err != nil {
|
|
logger.Errorw("无法记录审计日志:序列化 targetResource 失败", "error", err)
|
|
// 即使序列化失败,我们可能仍然希望记录操作本身,所以不在此处 return
|
|
}
|
|
|
|
// 异步写入数据库,不阻塞当前请求
|
|
go func() {
|
|
if err := s.userActionLogRepository.Create(serviceCtx, log); err != nil {
|
|
logger.Errorw("异步保存审计日志失败", "error", err)
|
|
}
|
|
}()
|
|
}
|