From 1ab07c18a4301d40cfa6897d76b8a0e13d81dde5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=92=8B=E5=90=89=E5=85=86?= <303176530@qq.com> Date: Mon, 25 Oct 2021 21:59:26 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=8E=E5=A4=B4=E9=83=A8=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E4=BF=A1=E6=81=AF=E7=9A=84=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E6=95=B4=E7=90=86=20=E5=A2=9E=E5=8A=A0=E4=B8=8D=E9=89=B4?= =?UTF-8?q?=E6=9D=83=E6=A8=A1=E5=BC=8F=E4=B8=8B=E7=9A=84=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/middleware/jwt.go | 1 + server/utils/clamis.go | 50 ++++++++++++++++++++++++++++++++++------ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/server/middleware/jwt.go b/server/middleware/jwt.go index 7f2decc4..576a3da4 100644 --- a/server/middleware/jwt.go +++ b/server/middleware/jwt.go @@ -66,6 +66,7 @@ func JWTAuth() gin.HandlerFunc { _ = jwtService.SetRedisJWT(newToken, newClaims.Username) } } + c.Set("claims", claims) c.Next() } } diff --git a/server/utils/clamis.go b/server/utils/clamis.go index f3c8bd33..b63919d2 100644 --- a/server/utils/clamis.go +++ b/server/utils/clamis.go @@ -7,33 +7,69 @@ import ( uuid "github.com/satori/go.uuid" ) -func GetClaims(c *gin.Context) *systemReq.CustomClaims { +func GetClaims(c *gin.Context) (*systemReq.CustomClaims,error) { token := c.Request.Header.Get("x-token") j := NewJWT() - claims, err := j.ParseToken(token) if err != nil { global.GVA_LOG.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构") } - return claims + return claims,err } // 从Gin的Context中获取从jwt解析出来的用户ID func GetUserID(c *gin.Context) uint { - return GetClaims(c).ID + if claims, exists := c.Get("claims"); !exists { + if cl,err:= GetClaims(c);err!=nil{ + return 0 + }else{ + return cl.ID + } + } else { + waitUse := claims.(*systemReq.CustomClaims) + return waitUse.ID + } + } // 从Gin的Context中获取从jwt解析出来的用户UUID func GetUserUuid(c *gin.Context) uuid.UUID { - return GetClaims(c).UUID + if claims, exists := c.Get("claims"); !exists { + if cl,err:= GetClaims(c);err!=nil{ + return uuid.UUID{} + }else{ + return cl.UUID + } + } else { + waitUse := claims.(*systemReq.CustomClaims) + return waitUse.UUID + } } // 从Gin的Context中获取从jwt解析出来的用户角色id func GetUserAuthorityId(c *gin.Context) string { - return GetClaims(c).AuthorityId + if claims, exists := c.Get("claims"); !exists { + if cl,err:= GetClaims(c);err!=nil{ + return "" + }else{ + return cl.AuthorityId + } + } else { + waitUse := claims.(*systemReq.CustomClaims) + return waitUse.AuthorityId + } } // 从Gin的Context中获取从jwt解析出来的用户角色id func GetUserInfo(c *gin.Context) *systemReq.CustomClaims { - return GetClaims(c) + if claims, exists := c.Get("claims"); !exists { + if cl,err:= GetClaims(c);err!=nil{ + return nil + }else{ + return cl + } + } else { + waitUse := claims.(*systemReq.CustomClaims) + return waitUse + } }