95 lines
1.8 KiB
Go
95 lines
1.8 KiB
Go
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
|
||
}
|
||
|
||
var userId int64
|
||
var qaId int64
|
||
|
||
// 用户id
|
||
if t.UserId != "" {
|
||
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
|
||
}
|
||
}
|
||
|
||
// 知识问答id
|
||
if t.QaId != "" {
|
||
qaId, err = strconv.ParseInt(t.QaId, 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("QaId", qaId) // 知识问答id
|
||
c.Set("Client", t.Client) // 客户端(1:前台 2:后台)
|
||
c.Next()
|
||
}
|
||
}
|