lckt-server/plugin/customerservice/middleware/jwt.go

58 lines
1.6 KiB
Go
Raw 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 (
"git.echol.cn/loser/lckt/model/common/response"
"git.echol.cn/loser/lckt/plugin/customerservice/tools"
"git.echol.cn/loser/lckt/utils"
"github.com/gin-gonic/gin"
"strings"
)
func JWTAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头获取 token
authHeader := c.GetHeader("chat-token")
userHeader := c.GetHeader("x-token")
if userHeader == "" && authHeader == "" {
response.FailWithMessage("参数错误:"+"Authorization header is missing", c)
c.Abort()
return
}
if authHeader != "" {
// 按照格式 "Bearer <token>" 提取 token
tokenString := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
if tokenString == "" {
response.FailWithMessage("参数错误:"+"Token is missing", c)
c.Abort()
return
}
// 验证 token
claims, err := tools.ValidateToken(tokenString)
if err != nil {
response.FailWithMessage("Invalid token"+err.Error(), c)
c.Abort()
return
}
// 将用户信息存储在上下文中,便于后续处理
c.Set("service_id", claims.ServiceId)
//c.Request.URL.Query().Add("service_id", strconv.FormatInt(claims.ServiceId, 10))
c.Next() // 继续处理请求
} else {
//为了方便客服后台和前端客服聊天界面公用方法共用同一套jwt前端的jwt的值取的还是gva-shop的x-token
j := utils.NewJWT()
claims, err := j.ParseToken(userHeader)
if err != nil {
response.FailWithMessage("参数错误:"+"Token is error", c)
c.Abort()
return
}
c.Set("jwt_user_id", claims.BaseClaims.ID)
c.Next()
}
}
}