123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- // Copyright 2020 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package middleware
- import (
- "fmt"
- "git.getensh.com/common/gopkgs/cache"
- "git.getensh.com/common/gopkgs/jwtwrapper"
- "github.com/dgrijalva/jwt-go"
- "github.com/gin-gonic/gin"
- "github.com/tidwall/gjson"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
- "net/http"
- "property-household-gateway/errors"
- )
- // 响应数据
- type Response struct {
- Code codes.Code `json:"code" default:"1"`
- Message string `json:"message" default:"success"`
- }
- const TokenUidKey = "household_token_uid"
- func cacheTokenUid(uid string) {
- if uid == "" {
- return
- }
- key := fmt.Sprintf("%s%s", TokenUidKey, uid)
- cache.Redis().SetEx(key, 600, "1")
- }
- func tokenUidExist(uid string) bool {
- key := fmt.Sprintf("%s%s", TokenUidKey, uid)
- r, _ := cache.Redis().Get(key)
- return r == "1"
- }
- // 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 claims != nil && tokenUidExist(claims.Id) {
- if v, ok := status.FromError(errors.TokenNeedRefresh); ok {
- s = v
- }
- } else {
- if v, ok := status.FromError(errors.TokenExpiredError); ok {
- s = v
- }
- }*/
- if v, ok := status.FromError(errors.TokenNeedRefresh); ok {
- s = v
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- default:
- if v, ok := status.FromError(errors.TokenFailedError); ok {
- s = v
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- }
- }
- //cacheTokenUid(claims.Id)
- // 将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()
- }
- }
|