25c11ed649
- cmd/main.go: 集成 logger.Init 和日志中间件,替换标准 log 包 - handler 层: 5xx 错误记录完整日志,返回通用消息(防内部信息泄露) - service 层: LLM/图片生成/存储/认证等关键操作补充结构化日志 - auth 中间件: 记录认证失败原因 - generate.go: 后台管线任务使用带 task_id 的 logger
54 lines
1.6 KiB
Go
54 lines
1.6 KiB
Go
package mildware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"gen2d/internal/logger"
|
|
"gen2d/internal/model"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
// AuthMiddleware 返回 JWT 认证中间件,校验 Bearer token 并注入 userID 到上下文。
|
|
func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
logger.FromCtx(c.Request.Context()).Warn("auth failed: no token")
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "未提供认证令牌"))
|
|
return
|
|
}
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
if tokenString == authHeader {
|
|
logger.FromCtx(c.Request.Context()).Warn("auth failed: invalid format")
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "认证格式错误,需为 Bearer <token>"))
|
|
return
|
|
}
|
|
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(jwtSecret), nil
|
|
})
|
|
if err != nil || !token.Valid {
|
|
logger.FromCtx(c.Request.Context()).Warn("auth failed: invalid token", "error", err)
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "令牌无效或已过期"))
|
|
return
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
logger.FromCtx(c.Request.Context()).Warn("auth failed: parse claims")
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "令牌解析失败"))
|
|
return
|
|
}
|
|
|
|
if sub, ok := claims["sub"]; ok {
|
|
c.Set("userID", sub)
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|