potato/internal/middleware/jwt.go

66 lines
1.3 KiB
Go
Raw Normal View History

2021-03-23 00:55:26 +08:00
/*
* @Date: 2021-03-21 19:54:57
* @LastEditors: viletyy
2021-06-10 15:37:36 +08:00
* @LastEditTime: 2021-06-10 15:20:29
* @FilePath: /potato/internal/middleware/jwt.go
2021-03-23 00:55:26 +08:00
*/
package middleware
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/viletyy/potato/global"
2021-06-10 15:37:36 +08:00
"github.com/viletyy/potato/pkg"
2021-03-23 00:55:26 +08:00
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Request.Header.Get("Authorization")
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "请求参数错误",
})
c.Abort()
2021-03-24 11:29:15 +08:00
return
2021-03-23 00:55:26 +08:00
} else {
2021-06-10 15:37:36 +08:00
claims, err := pkg.ParseToken(token)
2021-03-23 00:55:26 +08:00
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token验证失败",
})
c.Abort()
2021-03-24 11:29:15 +08:00
return
2021-03-23 00:55:26 +08:00
} else if time.Now().Unix() > claims.ExpiresAt {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token已超时",
})
c.Abort()
2021-03-24 11:29:15 +08:00
return
2021-03-23 00:55:26 +08:00
}
if claims != nil {
userId := claims.UserId
loginUUID := claims.StandardClaims.Id
val, _ := global.GO_REDIS.Get("login:" + loginUUID).Result()
if val != strconv.Itoa(int(userId)) {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token鉴权失败",
})
c.Abort()
2021-03-24 11:29:15 +08:00
return
2021-03-23 00:55:26 +08:00
}
} else {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token鉴权失败",
})
c.Abort()
2021-03-24 11:29:15 +08:00
return
2021-03-23 00:55:26 +08:00
}
}
c.Next()
}
}