42 lines
1.5 KiB
Go
42 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"strings"
|
|
|
|
"kra/internal/server/httpx"
|
|
"kra/internal/service"
|
|
"kra/internal/service/dto"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ErrorAudit supplies the database sink that the Error-level logging core
|
|
// provides. Expected authentication, permission and input failures are not
|
|
// system errors and therefore are not inserted into sys_error.
|
|
func ErrorAudit(audit *service.AuditRecorder) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
writer := &captureWriter{ResponseWriter: c.Writer, maxBytes: 1 << 20}
|
|
c.Writer = writer
|
|
c.Next()
|
|
if strings.Contains(c.Request.URL.Path, "/sysError/") || c.Writer.Status() >= 300 && c.Writer.Status() < 500 {
|
|
return
|
|
}
|
|
var response httpx.Response
|
|
if json.Unmarshal(writer.body.Bytes(), &response) != nil || response.Code == httpx.CodeSuccess || expectedClientFailure(response.Msg) {
|
|
return
|
|
}
|
|
requestID, _ := c.Get("request_id")
|
|
_ = audit.CreateErrorRequest(c.Request.Context(), &dto.ErrorRecordRequest{Form: c.Request.URL.Path, Info: response.Msg, Level: "error", RequestID: stringValue(requestID), TraceID: stringValueFromContext(c, "trace_id"), Status: "未解决"})
|
|
}
|
|
}
|
|
|
|
func expectedClientFailure(message string) bool {
|
|
for _, value := range []string{"参数错误", "请输入用户名和密码", "验证码错误", "用户名不存在或者密码错误", "用户被禁止登录", "账号已锁定", "权限不足", "密码已过期", "未登录", "token", "令牌失效"} {
|
|
if strings.Contains(message, value) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|