Files
2026-01-06 19:36:42 +08:00

69 lines
1.7 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"ai_xhs/common"
"ai_xhs/utils"
"context"
"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
}
// 新增验证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
}
// 将员工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()
}
}