add
wangpengfei
2023-08-26 aca83ef7ccda31adc3eb2c057d4120c112115076
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package utils
 
import (
    "github.com/gin-gonic/gin"
    "github.com/gofrs/uuid/v5"
    "srm/global"
    systemReq "srm/model/system/request"
)
 
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, err
}
 
// GetUserID 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserID(c *gin.Context) uint {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return 0
        } else {
            return cl.BaseClaims.ID
        }
    } else {
        waitUse := claims.(*systemReq.CustomClaims)
        return waitUse.BaseClaims.ID
    }
}
 
// GetUserUuid 从Gin的Context中获取从jwt解析出来的用户UUID
func GetUserUuid(c *gin.Context) uuid.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
    }
}
 
// GetUserAuthorityId 从Gin的Context中获取从jwt解析出来的用户角色id
func GetUserAuthorityId(c *gin.Context) uint {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return 0
        } else {
            return cl.AuthorityId
        }
    } else {
        waitUse := claims.(*systemReq.CustomClaims)
        return waitUse.AuthorityId
    }
}
 
// GetUserInfo 从Gin的Context中获取从jwt解析出来的用户角色id
func GetUserInfo(c *gin.Context) *systemReq.CustomClaims {
    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
    }
}
 
// GetUserName 从Gin的Context中获取从jwt解析出来的用户名
func GetUserName(c *gin.Context) string {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return ""
        } else {
            return cl.Username
        }
    } else {
        waitUse := claims.(*systemReq.CustomClaims)
        return waitUse.Username
    }
}