Browse Source

从头部获取用户信息的方法整理 增加不鉴权模式下的信息获取

main
蒋吉兆 3 years ago
parent
commit
1ab07c18a4
  1. 1
      server/middleware/jwt.go
  2. 50
      server/utils/clamis.go

1
server/middleware/jwt.go

@ -66,6 +66,7 @@ func JWTAuth() gin.HandlerFunc {
_ = jwtService.SetRedisJWT(newToken, newClaims.Username) _ = jwtService.SetRedisJWT(newToken, newClaims.Username)
} }
} }
c.Set("claims", claims)
c.Next() c.Next()
} }
} }

50
server/utils/clamis.go

@ -7,33 +7,69 @@ import (
uuid "github.com/satori/go.uuid" 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") token := c.Request.Header.Get("x-token")
j := NewJWT() j := NewJWT()
claims, err := j.ParseToken(token) claims, err := j.ParseToken(token)
if err != nil { if err != nil {
global.GVA_LOG.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构") global.GVA_LOG.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构")
} }
return claims
return claims,err
} }
// 从Gin的Context中获取从jwt解析出来的用户ID // 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserID(c *gin.Context) uint { 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 // 从Gin的Context中获取从jwt解析出来的用户UUID
func GetUserUuid(c *gin.Context) uuid.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 // 从Gin的Context中获取从jwt解析出来的用户角色id
func GetUserAuthorityId(c *gin.Context) string { 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 // 从Gin的Context中获取从jwt解析出来的用户角色id
func GetUserInfo(c *gin.Context) *systemReq.CustomClaims { 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
}
} }
Loading…
Cancel
Save