fix
wangpengfei
2023-08-25 ca955e049d8a2f8a7d79fe6f791cb87a79b891b1
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
package utils
 
import (
    "aps_crm/model/request"
    "aps_crm/pkg/logx"
    "github.com/gin-gonic/gin"
    "strings"
)
 
func GetClaims(c *gin.Context) (*request.CustomClaims, error) {
    token := c.Request.Header.Get("Authorization")
    logx.Infof("GetClaims token:%v", token)
    slices := strings.Split(token, " ")
    if len(slices) == 2 {
        token = slices[1]
    }
    j := NewJWT()
    claims, err := j.ParseToken(token)
    if err != nil {
        logx.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构")
    }
    return claims, err
}
 
// GetUserID 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserID(c *gin.Context) string {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return ""
        } else {
            return cl.UserId
        }
    } else {
        waitUse := claims.(*request.CustomClaims)
        return waitUse.UserId
    }
}
 
// GetUserInfo 从Gin的Context中获取从jwt解析出来的用户信息
func GetUserInfo(c *gin.Context) *request.CustomClaims {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return nil
        } else {
            return cl
        }
    } else {
        waitUse := claims.(*request.CustomClaims)
        return waitUse
    }
}