完成任务3
This commit is contained in:
@@ -63,13 +63,15 @@ func SendErrorWithStatus(c echo.Context, httpStatus int, code ResponseCode, mess
|
||||
|
||||
// --- 带审计功能的响应函数 ---
|
||||
|
||||
// setAuditDetails 是一个内部辅助函数,用于在 echo.Context 中设置业务相关的审计信息。
|
||||
func setAuditDetails(c echo.Context, actionType, description string, targetResource interface{}) {
|
||||
// setAuditDetails 是一个内部辅助函数,用于在 echo.Context 中统一设置所有业务相关的审计信息。
|
||||
func setAuditDetails(c echo.Context, actionType, description string, targetResource interface{}, status models.AuditStatus, resultDetails string) {
|
||||
// 只有当 actionType 不为空时,才设置审计信息,这作为触发审计的标志
|
||||
if actionType != "" {
|
||||
c.Set(models.ContextAuditActionType.String(), actionType)
|
||||
c.Set(models.ContextAuditDescription.String(), description)
|
||||
c.Set(models.ContextAuditTargetResource.String(), targetResource)
|
||||
c.Set(models.ContextAuditStatus.String(), status)
|
||||
c.Set(models.ContextAuditResultDetails.String(), resultDetails)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +87,7 @@ func SendSuccessWithAudit(
|
||||
targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识
|
||||
) error {
|
||||
// 1. 设置审计信息
|
||||
setAuditDetails(c, actionType, description, targetResource)
|
||||
setAuditDetails(c, actionType, description, targetResource, models.AuditStatusSuccess, "")
|
||||
// 2. 发送响应
|
||||
return SendResponse(c, code, message, data)
|
||||
}
|
||||
@@ -101,7 +103,7 @@ func SendErrorWithAudit(
|
||||
targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识
|
||||
) error {
|
||||
// 1. 设置审计信息
|
||||
setAuditDetails(c, actionType, description, targetResource)
|
||||
setAuditDetails(c, actionType, description, targetResource, models.AuditStatusFailed, message)
|
||||
// 2. 发送响应
|
||||
return SendErrorResponse(c, code, message)
|
||||
}
|
||||
|
||||
@@ -1,117 +1,59 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strconv"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/domain/audit"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type auditResponse struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
// AuditLogMiddleware 创建一个Echo中间件,用于在请求结束后记录用户操作审计日志。
|
||||
// 它依赖于控制器通过调用 SendSuccessWithAudit 或 SendErrorWithAudit 在上下文中设置的审计信息。
|
||||
func AuditLogMiddleware(auditService audit.Service) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// 首先执行请求链中的后续处理程序(即业务控制器)
|
||||
err := next(c)
|
||||
|
||||
// AuditLogMiddleware 创建一个Gin中间件,用于在请求结束后记录用户操作审计日志
|
||||
func AuditLogMiddleware(auditService audit.Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 使用自定义的 response body writer 来捕获响应体
|
||||
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
|
||||
c.Writer = blw
|
||||
// --- 在这里,请求已经处理完毕 ---
|
||||
|
||||
// 首先执行请求链中的后续处理程序(即业务控制器)
|
||||
c.Next()
|
||||
|
||||
// --- 在这里,请求已经处理完毕 ---
|
||||
|
||||
// 从上下文中尝试获取由控制器设置的业务审计信息
|
||||
actionType, exists := c.Get(models.ContextAuditActionType.String())
|
||||
if !exists {
|
||||
// 如果上下文中没有 actionType,说明此接口无需记录审计日志,直接返回
|
||||
return
|
||||
}
|
||||
|
||||
// 从 Gin Context 中获取用户对象
|
||||
userCtx, userExists := c.Get(models.ContextUserKey.String())
|
||||
var user *models.User
|
||||
if userExists {
|
||||
user, _ = userCtx.(*models.User)
|
||||
}
|
||||
|
||||
// 构建 RequestContext
|
||||
reqCtx := audit.RequestContext{
|
||||
ClientIP: c.ClientIP(),
|
||||
HTTPPath: c.Request.URL.Path,
|
||||
HTTPMethod: c.Request.Method,
|
||||
}
|
||||
|
||||
// 获取其他审计信息
|
||||
description, _ := c.Get(models.ContextAuditDescription.String())
|
||||
targetResource, _ := c.Get(models.ContextAuditTargetResource.String())
|
||||
|
||||
// 默认操作状态为成功
|
||||
status := models.AuditStatusSuccess
|
||||
resultDetails := ""
|
||||
|
||||
// 尝试从捕获的响应体中解析平台响应
|
||||
var platformResponse auditResponse
|
||||
if err := json.Unmarshal(blw.body.Bytes(), &platformResponse); err == nil {
|
||||
// 如果解析成功,根据平台状态码判断操作是否失败
|
||||
// 成功状态码范围是 2000-2999
|
||||
if platformResponse.Code < 2000 || platformResponse.Code >= 3000 {
|
||||
status = models.AuditStatusFailed
|
||||
resultDetails = platformResponse.Message
|
||||
// 从上下文中尝试获取由控制器设置的业务审计信息
|
||||
actionType, exists := c.Get(models.ContextAuditActionType.String()).(string)
|
||||
if !exists || actionType == "" {
|
||||
// 如果上下文中没有 actionType,说明此接口无需记录审计日志,直接返回
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// 如果响应体不是预期的平台响应格式,或者解析失败,则记录原始HTTP状态码作为详情
|
||||
// 并且如果HTTP状态码不是2xx,则标记为失败
|
||||
if c.Writer.Status() < 200 || c.Writer.Status() >= 300 {
|
||||
status = models.AuditStatusFailed
|
||||
}
|
||||
resultDetails = "HTTP Status: " + strconv.Itoa(c.Writer.Status()) + ", Body Parse Error: " + err.Error()
|
||||
}
|
||||
|
||||
// 调用审计服务记录日志(异步)
|
||||
auditService.LogAction(
|
||||
user,
|
||||
reqCtx,
|
||||
actionType.(string),
|
||||
description.(string),
|
||||
targetResource,
|
||||
status,
|
||||
resultDetails,
|
||||
)
|
||||
// 从 Context 中获取用户对象
|
||||
var user *models.User
|
||||
if userCtx := c.Get(models.ContextUserKey.String()); userCtx != nil {
|
||||
user, _ = userCtx.(*models.User)
|
||||
}
|
||||
|
||||
// 构建 RequestContext
|
||||
reqCtx := audit.RequestContext{
|
||||
ClientIP: c.RealIP(),
|
||||
HTTPPath: c.Request().URL.Path,
|
||||
HTTPMethod: c.Request().Method,
|
||||
}
|
||||
|
||||
// 直接从上下文中获取所有其他审计信息
|
||||
description, _ := c.Get(models.ContextAuditDescription.String()).(string)
|
||||
targetResource := c.Get(models.ContextAuditTargetResource.String())
|
||||
status, _ := c.Get(models.ContextAuditStatus.String()).(models.AuditStatus)
|
||||
resultDetails, _ := c.Get(models.ContextAuditResultDetails.String()).(string)
|
||||
|
||||
// 调用审计服务记录日志(异步)
|
||||
auditService.LogAction(
|
||||
user,
|
||||
reqCtx,
|
||||
actionType,
|
||||
description,
|
||||
targetResource,
|
||||
status,
|
||||
resultDetails,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// bodyLogWriter 是一个自定义的 gin.ResponseWriter,用于捕获响应体
|
||||
// 这对于在操作失败时记录详细的错误信息非常有用
|
||||
type bodyLogWriter struct {
|
||||
gin.ResponseWriter
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
func (w bodyLogWriter) Write(b []byte) (int, error) {
|
||||
w.body.Write(b)
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (w bodyLogWriter) WriteString(s string) (int, error) {
|
||||
w.body.WriteString(s)
|
||||
return w.ResponseWriter.WriteString(s)
|
||||
}
|
||||
|
||||
// ReadBody 用于安全地读取请求体,并防止其被重复读取
|
||||
func ReadBody(c *gin.Context) ([]byte, error) {
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 将读取的内容放回 Body 中,以便后续的处理函数可以再次读取
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
||||
return bodyBytes, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user