47 lines
1.6 KiB
Go
47 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"bytes"
|
|
"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) {
|
|
c.Next()
|
|
if strings.Contains(c.Request.URL.Path, "/sysError/") || c.Writer.Status() >= 300 && c.Writer.Status() < 500 {
|
|
return
|
|
}
|
|
var response httpx.Response
|
|
var body []byte
|
|
if value, ok := c.Get(ctxRespBufferKey); ok {
|
|
if buffer, valid := value.(*bytes.Buffer); valid {
|
|
body = buffer.Bytes()
|
|
}
|
|
}
|
|
if json.Unmarshal(body, &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")})
|
|
}
|
|
}
|
|
|
|
func expectedClientFailure(message string) bool {
|
|
for _, value := range []string{"参数错误", "请输入用户名和密码", "验证码错误", "用户名不存在或者密码错误", "用户被禁止登录", "账号已锁定", "权限不足", "密码已过期", "未登录", "token", "令牌失效"} {
|
|
if strings.Contains(message, value) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|