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.

68 lines
1.3 KiB
Go

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