// Copyright 2020 github.com. All rights reserved. // Use of this source code is governed by github.com. package middleware import ( "github.com/tidwall/gjson" "net/http" "property-device-gateway/errors" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "git.getensh.com/common/gopkgs/jwtwrapper" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // 响应数据 type Response struct { Code codes.Code `json:"code" default:"1"` Message string `json:"message" default:"success"` } // JWT is jwt middleware func Jwt() gin.HandlerFunc { return func(c *gin.Context) { s := status.New(1, "内部服务错误") token := c.GetHeader("token") if token == "" { if v, ok := status.FromError(errors.NoTokenError); ok { s = v } c.JSON(http.StatusOK, Response{s.Code(), s.Message()}) c.Abort() return } // 解析token claims, err := jwtwrapper.ParseToken(token) if err != nil { switch err.(*jwt.ValidationError).Errors { case jwt.ValidationErrorExpired: if v, ok := status.FromError(errors.TokenExpiredError); ok { s = v } default: if v, ok := status.FromError(errors.TokenFailedError); ok { s = v } } c.JSON(http.StatusOK, Response{s.Code(), s.Message()}) c.Abort() return } // 将claims信息保存到上下文,为后续使用 c.Set("claims", claims) /* supper := gjson.GetBytes(utils.StrToBytes(claims.Subject), "supper").Bool() if c.Request.Method == "PUT" || c.Request.Method == "POST" || c.Request.Method == "DELETE" { if supper == false && strings.Contains(c.Request.RequestURI, "/user") == false { c.JSON(http.StatusOK, Response{10008, "权限不足"}) } } */ // 进行下一次处理 if gjson.GetBytes([]byte(claims.Subject), "tmp_token").Bool() { c.JSON(http.StatusOK, Response{10008, "无效凭据"}) c.Abort() } c.Next() } }