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

88 lines
2.4 KiB
Go

// audit.go Day 29:审计拦截中间件——受保护组的敏感写操作(POST/PUT/DELETE)
// 与导出类 GET(path 含 export)在响应 2xx/3xx 后留痕;who=claims,what=路由模板,
// when=时间(库侧 autoCreateTime),IP=ClientIP;记录失败不影响响应。
package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"go-sms/internal/service/audit"
)
// AuditTrail 敏感操作审计:recorder 为 nil 时直通(降级)。
func AuditTrail(recorder *audit.Service) gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if recorder == nil {
return
}
if !auditWorthy(c.Request.Method, c.FullPath()) {
return
}
if c.Writer.Status() >= http.StatusBadRequest {
return // 失败请求(含 401/403/4xx/5xx)不留操作日志,避免噪音
}
e := &audit.Entry{
IP: c.ClientIP(),
Module: moduleOf(c.FullPath()),
Action: actionOf(c.Request.Method, c.FullPath()),
Target: c.Param("id"),
Detail: fmt.Sprintf("%s %s -> %d", c.Request.Method, c.Request.URL.Path, c.Writer.Status()),
}
if v, ok := c.Get(ContextKeyClaims); ok {
if claims, _ := v.(*Claims); claims != nil {
e.Operator, e.AccountID = claims.Username, claims.AccountID
}
}
// 尽力而为:审计失败不影响业务响应
_ = recorder.Record(c.Request.Context(), e)
}
}
// auditWorthy 是否值得留痕:写方法或导出类 GET。
func auditWorthy(method, fullPath string) bool {
switch method {
case http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch:
return true
case http.MethodGet:
return strings.Contains(fullPath, "export")
}
return false
}
// moduleOf 路由模板首段(如 /api/v1/accounts/:id → accounts→account 域)。
func moduleOf(fullPath string) string {
if fullPath == "" {
return "unknown"
}
parts := strings.Split(strings.Trim(fullPath, "/"), "/")
// 跳过 api/v1 前缀
for _, p := range parts {
if p == "api" || p == "v1" {
continue
}
return strings.TrimSuffix(p, "s")
}
return "unknown"
}
// actionOf 动作名:方法+路径尾段(去掉参数)。
func actionOf(method, fullPath string) string {
parts := strings.Split(strings.Trim(fullPath, "/"), "/")
tail := ""
for i := len(parts) - 1; i >= 0; i-- {
if !strings.HasPrefix(parts[i], ":") && parts[i] != "" {
tail = parts[i]
break
}
}
if tail == "" {
return strings.ToLower(method)
}
return tail + ":" + strings.ToLower(method)
}