You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.5 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package middleware
import (
"github.com/exhibition-main/internal/model"
"github.com/exhibition-main/internal/msg"
"github.com/exhibition-main/internal/response"
"github.com/exhibition-main/pkg/jwt"
"github.com/gin-gonic/gin"
"strings"
)
// JWTAuthMiddleware 基于JWT的认证中间件
func JWTAuthMiddleware() func(c *gin.Context) {
return func(c *gin.Context) {
authHeader := c.Request.Header.Get("Authorization")
if authHeader == "" {
response.ResponseQuickMsg(c, msg.Fail, msg.NEED_LOGIN, nil)
c.Abort()
return
}
// 按空格分割
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
response.ResponseMsg(c, msg.StatusUnauthorized, model.Response{
Status: msg.Fail,
Data: nil,
Msg: msg.NEED_LOGIN,
})
c.Abort()
return
}
// parts[1]是获取到的tokenString我们使用之前定义好的解析JWT的函数来解析它
jwtInfo, err := jwt.ParseToken(parts[1])
if err != nil {
response.ResponseMsg(c, msg.StatusUnauthorized, model.Response{
Status: msg.Fail,
Data: nil,
Msg: msg.INVALID_TOKEN,
})
c.Abort()
return
}
// 将当前请求的userID信息保存到请求的上下文c上
c.Set(model.CTX_USER_INFO, jwt.MyClaims{
UserId: jwtInfo.UserId,
Nickname: jwtInfo.Nickname,
Phone: jwtInfo.Phone,
Openid: jwtInfo.Openid,
})
c.Next() // 后续的处理请求的函数中 可以用过c.Get(CtxUserIDKey) 来获取当前请求的用户信息
}
}