-
Notifications
You must be signed in to change notification settings - Fork 0
/
default_token_whitelist_checker.go
78 lines (67 loc) · 1.94 KB
/
default_token_whitelist_checker.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
package auth
import (
"context"
"errors"
"strconv"
"time"
)
type DefaultTokenWhitelistChecker struct {
Secret string
TokenIp string
TokenPrefix string
VerifyToken func(tokenString string, secret string) (map[string]interface{}, int64, int64, error)
CachePort CachePort
Level int
}
func NewTokenWhitelistChecker(secret string, tokenIp string, keyPrefix string, verifyToken func(tokenString string, secret string) (map[string]interface{}, int64, int64, error), cacheService CachePort, level int) *DefaultTokenWhitelistChecker {
return &DefaultTokenWhitelistChecker{secret, tokenIp, keyPrefix, verifyToken, cacheService, level}
}
func (b *DefaultTokenWhitelistChecker) generateKey(token string) string {
return b.TokenPrefix + "::token::" + token
}
func (b *DefaultTokenWhitelistChecker) generateKeyForId(id string) string {
return b.TokenPrefix + "::token::" + id
}
func (b *DefaultTokenWhitelistChecker) Add(ctx context.Context, id string, token string) error {
_, _, eta, err := b.VerifyToken(token, b.Secret)
if err != nil {
return err
}
now := time.Now()
if eta <= now.Unix() {
return errors.New("token expired")
}
expire := time.Unix(eta, 0)
dur := expire.Sub(now)
key := b.generateKeyForId(id)
return b.CachePort.Put(ctx, key, token, dur)
}
func (b *DefaultTokenWhitelistChecker) Check(ctx context.Context, id string, token string) bool {
key := b.generateKeyForId(id)
value, err := b.CachePort.Get(ctx, key)
if err != nil {
return false
}
if len(value) > 0 {
tokenStore, _ := strconv.Unquote(value)
if b.Level != 0 {
if tokenStore != token {
return false
}
return true
}
payloadStore, _, _, err1 := b.VerifyToken(tokenStore, b.Secret)
payload, _, _, err2 := b.VerifyToken(token, b.Secret)
if err1 != nil || err2 != nil {
return false
}
ipStore, ok1 := payloadStore[b.TokenIp]
ip, ok2 := payload[b.TokenIp]
if ok1 && ok2 {
if ip == ipStore {
return true
}
}
}
return false
}