39 lines
895 B
Go
39 lines
895 B
Go
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
|
|
"everypublish/server/internal/api/response"
|
|
"everypublish/server/internal/models"
|
|
)
|
|
|
|
// Audit 审计埋点:处理器调用 response.Audit(c, action, resource, detail) 声明,
|
|
// 本中间件在请求成功(2xx)后落库。
|
|
func Audit(db *gorm.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
metaRaw, exists := c.Get("audit")
|
|
if !exists {
|
|
return
|
|
}
|
|
meta, ok := metaRaw.(response.AuditMeta)
|
|
if !ok || c.Writer.Status() >= http.StatusBadRequest {
|
|
return
|
|
}
|
|
detail, _ := json.Marshal(meta.Detail)
|
|
log := models.AuditLog{
|
|
WorkspaceID: c.GetUint64("wsid"),
|
|
UserID: c.GetUint64("uid"),
|
|
Action: meta.Action,
|
|
Resource: meta.Resource,
|
|
Detail: string(detail),
|
|
IP: c.ClientIP(),
|
|
}
|
|
_ = db.Create(&log).Error
|
|
}
|
|
}
|