Files
go-sms-V2/internal/service/audit/audit.go
T

151 lines
4.1 KiB
Go

// Package audit 审计日志服务(Day 29):敏感操作留痕(SystemOperateLog)
// 与登录审计(SystemLoginLog);写入尽力而为(不阻断业务),查询按
// 操作人/账号/模块/IP/时间范围过滤分页。
package audit
import (
"context"
"time"
"gorm.io/gorm"
"go-sms/internal/model/entity"
)
// Service 审计服务。
type Service struct{ db *gorm.DB }
// NewService 构造。
func NewService(db *gorm.DB) *Service { return &Service{db: db} }
// Entry 敏感操作记录(中间件/业务方填充)。
type Entry struct {
Operator string // 登录账号名(无 claims 时留空)
AccountID int64
Module string // account/auth/channel...
Action string // login/recharge/delete/export...
Target string // 目标资源(如账号 ID)
Detail string // 摘要(方法+路径+状态,≤1024)
IP string
}
// Record 落一条操作日志(尽力而为;错误返回由调用方决定吞否)。
func (s *Service) Record(ctx context.Context, e *Entry) error {
return s.db.WithContext(ctx).Create(&entity.SystemOperateLog{
Operator: e.Operator, AccountID: e.AccountID, Module: e.Module,
Action: e.Action, Target: e.Target, Detail: e.Detail, IP: e.IP,
}).Error
}
// RecordLogin 落一条登录审计(成功/失败均记)。
// 注意:Ok 列带 gorm default:1,失败记录 Ok=0 为零值会被 GORM 忽略,
// 故用 map 创建绕过零值过滤(与业务开关同坑)。
func (s *Service) RecordLogin(ctx context.Context, username string, accountID int64, ip, userAgent, failReason string) error {
ok := 1
if failReason != "" {
ok = 0
}
return s.db.WithContext(ctx).Model(&entity.SystemLoginLog{}).Create(map[string]any{
"username": username, "account_id": accountID, "ip": ip,
"user_agent": userAgent, "ok": ok, "fail_reason": failReason,
}).Error
}
// OperateQuery 操作日志查询过滤。
type OperateQuery struct {
Page, PageSize int
Operator string // 精确
AccountID int64
Module string
Action string
IP string
Start, End *time.Time
}
// Query 操作日志分页查询(时间倒序)。
func (s *Service) Query(ctx context.Context, q *OperateQuery) ([]entity.SystemOperateLog, int64, error) {
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
tx := s.db.WithContext(ctx).Model(&entity.SystemOperateLog{})
if q.Operator != "" {
tx = tx.Where("operator = ?", q.Operator)
}
if q.AccountID > 0 {
tx = tx.Where("account_id = ?", q.AccountID)
}
if q.Module != "" {
tx = tx.Where("module = ?", q.Module)
}
if q.Action != "" {
tx = tx.Where("action = ?", q.Action)
}
if q.IP != "" {
tx = tx.Where("ip = ?", q.IP)
}
if q.Start != nil {
tx = tx.Where("created_at >= ?", *q.Start)
}
if q.End != nil {
tx = tx.Where("created_at <= ?", *q.End)
}
var total int64
if err := tx.Count(&total).Error; err != nil {
return nil, 0, err
}
var logs []entity.SystemOperateLog
if err := tx.Order("id DESC").
Offset((q.Page - 1) * q.PageSize).Limit(q.PageSize).Find(&logs).Error; err != nil {
return nil, 0, err
}
return logs, total, nil
}
// LoginQuery 登录审计查询过滤。
type LoginQuery struct {
Page, PageSize int
Username string
IP string
OnlyFailed bool
Start, End *time.Time
}
// QueryLogin 登录审计分页查询(时间倒序)。
func (s *Service) QueryLogin(ctx context.Context, q *LoginQuery) ([]entity.SystemLoginLog, int64, error) {
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
tx := s.db.WithContext(ctx).Model(&entity.SystemLoginLog{})
if q.Username != "" {
tx = tx.Where("username = ?", q.Username)
}
if q.IP != "" {
tx = tx.Where("ip = ?", q.IP)
}
if q.OnlyFailed {
tx = tx.Where("ok = 0")
}
if q.Start != nil {
tx = tx.Where("login_at >= ?", *q.Start)
}
if q.End != nil {
tx = tx.Where("login_at <= ?", *q.End)
}
var total int64
if err := tx.Count(&total).Error; err != nil {
return nil, 0, err
}
var logs []entity.SystemLoginLog
if err := tx.Order("id DESC").
Offset((q.Page - 1) * q.PageSize).Limit(q.PageSize).Find(&logs).Error; err != nil {
return nil, 0, err
}
return logs, total, nil
}