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
68 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"insure/service"
|
|
"insure/utils"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func JwtMiddleware(role string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := c.Request.Header.Get("Authorization")
|
|
if token == "" {
|
|
token = c.Query("token")
|
|
}
|
|
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
|
|
}
|
|
|
|
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)
|
|
|
|
// 判断token是否过期
|
|
if time.Now().Unix() > claims.ExpiresAt.Unix() {
|
|
result.Code = utils.ErrorTokenExpired
|
|
result.Message = "TOKEN过期"
|
|
c.JSON(http.StatusOK, result)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if claims.Role == "user" {
|
|
user := service.UserService.GetInfo(claims.Identity)
|
|
c.Set("user", user)
|
|
} else if claims.Role == "admin" {
|
|
user := service.AdminService.GetInfo(claims.Identity)
|
|
c.Set("admin", user)
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|