Files
ai_wht_wechat/go_backend/middleware/auth.go

69 lines
1.7 KiB
Go
Raw Normal View History

2025-12-19 22:36:48 +08:00
package middleware
import (
"ai_xhs/common"
"ai_xhs/utils"
2026-01-06 19:36:42 +08:00
"context"
2025-12-19 22:36:48 +08:00
"strings"
"github.com/gin-gonic/gin"
)
// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头获取token
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
common.Error(c, common.CodeUnauthorized, "未登录或token为空")
c.Abort()
return
}
// 检查token格式
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
common.Error(c, common.CodeUnauthorized, "token格式错误")
c.Abort()
return
}
// 解析token
claims, err := utils.ParseToken(parts[1])
if err != nil {
common.Error(c, common.CodeUnauthorized, "无效的token")
c.Abort()
return
}
2026-01-06 19:36:42 +08:00
// 新增验证token是否在Redis中存在校验是否被禁用
ctx := context.Background()
if err := utils.ValidateTokenInRedis(ctx, claims.EmployeeID, parts[1]); err != nil {
common.Error(c, common.CodeUnauthorized, err.Error())
c.Abort()
return
}
2025-12-19 22:36:48 +08:00
// 将员工ID存入上下文
c.Set("employee_id", claims.EmployeeID)
c.Next()
}
}
// CORS 跨域中间件
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}