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.

46 lines
923 B
Go

package middleware
import (
"github.com/gin-gonic/gin"
"gold-shop/service"
"gold-shop/utils"
"net/http"
"time"
)
func JwtMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Request.Header.Get("Authorization")
result := utils.Result{}
if token == "" {
result.Code = utils.Error
result.Message = "TOKEN过期"
c.JSON(http.StatusOK, result)
c.Abort()
return
}
claims, isValid := utils.CheckToken(token)
if !isValid {
result.Code = utils.ErrorTokenWrong
result.Message = "TOKEN验证失败"
c.JSON(http.StatusOK, result)
c.Abort()
return
}
// 判断token是否过期
if time.Now().Unix() > claims.ExpiresAt.Unix() {
result.Code = utils.ErrorTokenExpired
result.Message = "TOKEN过期"
c.JSON(http.StatusOK, result)
c.Abort()
return
}
user := service.UserService.GetUserInfo(claims.Identity)
c.Set("user", user)
c.Next()
}
}