-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
102 lines (82 loc) · 2.57 KB
/
redis.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
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"strconv"
"time"
"github.com/duo-labs/webauthn/webauthn"
"github.com/go-redis/redis/v8"
)
// RIPInfo is ipinfo key in redis
func RIPInfo(key string) string {
return "ipinfo_" + key
}
// RChallenge is challenge key in redis
// It is Terminal
func RChallenge(key string) string {
return "challenge_" + key
}
// RToken is token key in redis
// It is int, is user id
func RToken(key string) string {
return "token_" + key
}
// RTerminal is terminal key in redis
func RTerminal(key string) string {
return "terminal_" + key
}
// RUser is terminal key in redis
// It is map[int]string, map's key is terminal id, and map's value is terminal token
func RUser(userID int) string {
return "user_" + strconv.Itoa(userID)
}
// ===========================================================================
// GetUserTerminals returns user terminals in cache if have
func GetUserTerminals(userID int) (map[int]string, error) {
terminalMap := make(map[int]string)
result, err := rdb.Get(ctx, RUser(userID)).Result()
if err != nil {
return terminalMap, err
}
err = json.Unmarshal([]byte(result), &terminalMap)
if err != nil {
return nil, err
}
return terminalMap, nil
}
// SetWebAuthnSession is set webauthn session data
func SetWebAuthnSession(challenge string, seesinData *webauthn.SessionData) error {
return SetV2Redis("webauthn_"+challenge, seesinData, ExpireTimeChallengeConfirm)
}
// GetWebAuthnSession returns webauthn session data
func GetWebAuthnSession(challenge string) (seesinData webauthn.SessionData, err error) {
err = GetV4Redis("webauthn_"+challenge, &seesinData)
return
}
// ===========================================================================
// SetV2RedisPipe encodes the value as json, and
// then stores it in redis in the form of key-value pairs
func SetV2RedisPipe(pipe redis.Pipeliner, key string, v interface{}, duration time.Duration) error {
bs, err := json.Marshal(v)
if err != nil {
return err
}
return pipe.Set(ctx, key, string(bs), duration).Err()
}
// SetV2Redis encodes the value as json, and
// then stores it in redis in the form of key-value pairs
func SetV2Redis(key string, v interface{}, duration time.Duration) error {
bs, err := json.Marshal(v)
if err != nil {
return err
}
return rdb.Set(ctx, key, string(bs), duration).Err()
}
// GetV4Redis reads the value of the specified key from redis and
// decodes it into the v interface{}
func GetV4Redis(key string, v interface{}) error {
result, err := rdb.Get(ctx, key).Result()
if err != nil {
return err
}
return json.Unmarshal([]byte(result), v)
}