-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_jwt_check.go
89 lines (77 loc) · 2.3 KB
/
a_jwt_check.go
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
89
package pipe
import (
"github.com/kataras/iris/v12"
"github.com/pkg/errors"
"github.com/redis/rueidis"
"strings"
)
type JwtFlatBase struct {
UserId string `json:"user_id,omitempty"`
Env string `json:"env,omitempty"`
Raw string `json:"raw,omitempty"`
LoginTime string `json:"login_time,omitempty"`
}
func (c JwtFlatBase) IsShort() bool {
return strings.HasPrefix(c.Raw, JwtShortPrefix)
}
type JwtCheckDep struct {
FlatMap JwtFlatBase
Env string
Authorization string // Auth头
}
var (
// JwtCheck jwt验证
// 必传origin JwtCheckDep
// 必传db 为redis Client
JwtCheck = &RunnerContext[*JwtCheckDep, any, rueidis.Client, JwtFlatBase]{
Name: "jwt验证",
Key: "jwt_check",
call: func(ctx iris.Context, origin *JwtCheckDep, params any, db rueidis.Client, more ...any) *RunResp[JwtFlatBase] {
if origin == nil {
return NewPipeErr[JwtFlatBase](PipeDepError)
}
dep := origin
rdb := db
helper := NewJwtHelper(rdb)
pack := dep.FlatMap
if len(pack.UserId) < 1 {
return NewPipeErr[JwtFlatBase](errors.New("jwt数据包关键参数缺失"))
}
if len(pack.Env) < 1 {
return NewPipeErr[JwtFlatBase](errors.New("jwt数据包参数缺失"))
}
if len(pack.Raw) < 1 {
return NewPipeErr[JwtFlatBase](errors.New("jwt数据包结构错误"))
}
// jwt 中的数据集
raw := pack.Raw
// 进行安全校验
if pack.IsShort() {
// 获取最新的token
resp := rdb.Do(ctx, rdb.B().Get().Key(helper.JwtRedisGenKey(pack.UserId, dep.Env)).Build())
if resp.Error() != nil {
// 只要不是为空错误 则为其他错误都直接返回
if resp.Error() != rueidis.Nil {
return NewPipeErr[JwtFlatBase](resp.Error())
}
// 如果是为空 则是错误
return NewPipeErr[JwtFlatBase](errors.New("jwt数据获取失败"))
}
st, err := resp.ToString()
if err != nil {
return NewPipeErr[JwtFlatBase](err)
}
raw = strings.TrimPrefix(raw, JwtPrefix)
if raw != st {
return NewPipeErr[JwtFlatBase](errors.New("jwt数据包已过期"))
}
return NewPipeResult(pack)
}
// 完整判断环境是否正常
if dep.Env != pack.Env {
return NewPipeErr[JwtFlatBase](errors.New("jwt数据包环境校验失败"))
}
return NewPipeResult[JwtFlatBase](pack)
},
}
)