2024-09-27 10:44:43 +08:00

74 lines
1.4 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 middlewares
import (
"github.com/gin-gonic/gin"
"knowledge/consts"
"knowledge/global"
"knowledge/utils"
"net/http"
"strconv"
"strings"
)
// Jwt jwt认证
func Jwt() gin.HandlerFunc {
return func(c *gin.Context) {
authorization := c.Request.Header.Get("Authorization")
if authorization == "" || !strings.HasPrefix(authorization, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{
"message": "请求未授权",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
// 去除Bearer
authorization = authorization[7:] // 截取字符
// 检测是否存在黑名单
res, _ := global.Redis.Get(c, "jwt_black_"+authorization).Result()
if res != "" {
c.JSON(http.StatusOK, gin.H{
"message": "token错误/过期",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
// 解析jwt
t, err := utils.ParseJwt(authorization)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"message": "token错误/过期",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
// 转换类型
userId, err := strconv.ParseInt(t.UserId, 10, 64)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"message": "token错误",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
c.Set("UserId", userId) // 用户id
c.Set("Client", t.Client) // 客户端1:前台 2:后台)
c.Next()
}
}