zhangqian
2024-03-23 b68185aed1a86536b01fdfbca6b2cca7bd71a50f
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
package jwt
 
import (
    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
    "outsourcing/conf"
    "outsourcing/pkg/logx"
    "strings"
)
 
type OutsideUserClaims struct {
    UserId      string
    Username    string
    ParentId    string
    CompanyId   uint
    CompanyName string
    BufferTime  int64
    jwt.StandardClaims
}
 
func GetClaims(c *gin.Context) (*OutsideUserClaims, 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 := NewOutsideJWT(conf.WebConf.JWTKey)
    claims, err := j.ParseToken(token)
    if err != nil {
        logx.Error("从Gin的Context中获取从jwt解析信息失败, 请检查请求头是否存在x-token且claims是否为规定结构")
    }
    return claims, err
}
 
// GetCompanyID 从Gin的Context中获取从jwt解析出来的公司ID
func GetCompanyID(c *gin.Context) uint {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return 0
        } else {
            return cl.CompanyId
        }
    } else {
        waitUse := claims.(*OutsideUserClaims)
        return waitUse.CompanyId
    }
}
 
// GetUserInfo 从Gin的Context中获取从jwt解析出来的用户信息
func GetUserInfo(c *gin.Context) *OutsideUserClaims {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return nil
        } else {
            return cl
        }
    } else {
        waitUse := claims.(*OutsideUserClaims)
        return waitUse
    }
}