user_token.go
1.3 KB
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
package contextdata
import (
"context"
"encoding/json"
"github.com/zeromicro/go-zero/core/logx"
)
var (
CtxKeyJwtUserId = "UserId"
CtxKeyJwtCompanyId = "CompanyId"
CtxKeyJwtEmployeeId = "EmployeeId"
)
func GetInt64FromCtx(ctx context.Context, key string) int64 {
var uid int64
if jsonUid, ok := ctx.Value(key).(json.Number); ok {
if int64Uid, err := jsonUid.Int64(); err == nil {
uid = int64Uid
} else {
logx.WithContext(ctx).Errorf("GetUidFromCtx err : %+v", err)
}
}
return uid
}
func getStringFromCtx(ctx context.Context, key string) string {
var uid string
if jsonUid, ok := ctx.Value(key).(string); ok {
return jsonUid
}
return uid
}
func getArrayInt64FromCtx(ctx context.Context, key string) []int64 {
values := ctx.Value(key)
var ids = make([]int64, 0)
if values == nil {
return ids
}
if list, ok := values.([]interface{}); ok {
for _, item := range list {
if jsonId, ok := item.(json.Number); ok {
id, _ := jsonId.Int64()
ids = append(ids, id)
}
}
}
return ids
}
func GetUserTokenFromCtx(ctx context.Context) UserToken {
return UserToken{
UserId: GetInt64FromCtx(ctx, CtxKeyJwtUserId),
CompanyId: GetInt64FromCtx(ctx, CtxKeyJwtCompanyId),
EmployeeId: GetInt64FromCtx(ctx, CtxKeyJwtEmployeeId),
}
}