This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtoken_cache_redis.go
75 lines (59 loc) · 1.74 KB
/
token_cache_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
package gcpvault
import (
"context"
"encoding/json"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
"time"
)
type TokenCacheRedis struct {
cfg *Config
}
func (t TokenCacheRedis) GetToken(ctx context.Context) (*Token, error) {
if t.cfg.TokenCache != nil {
redisAddr := t.cfg.TokenCacheStorageRedis
tokenKey := t.cfg.TokenCacheKeyName
tokenDB := t.cfg.TokenCacheStorageRedisDB
opts := []redis.DialOption{redis.DialConnectTimeout(time.Second * time.Duration(t.cfg.TokenCacheCtxTimeout)), redis.DialDatabase(tokenDB)}
conn, err := redis.Dial("tcp", redisAddr, opts...)
if err != nil {
return nil, errors.Wrap(err, "error connecting")
}
defer conn.Close()
data, err := redis.String(conn.Do("GET", tokenKey))
if err != nil {
// swallowing the error here since we may not have cached a token yet
return nil, nil
}
var token Token
err = json.Unmarshal([]byte(data), &token)
if err != nil {
return nil, errors.Wrap(err, "error unmarshalling data")
}
return &token, nil
}
return nil, nil
}
func (t TokenCacheRedis) SaveToken(ctx context.Context, token Token) error {
if t.cfg.TokenCache != nil {
redisAddr := t.cfg.TokenCacheStorageRedis
tokenKey := t.cfg.TokenCacheKeyName
tokenDB := t.cfg.TokenCacheStorageRedisDB
opts := []redis.DialOption{redis.DialConnectTimeout(time.Second * time.Duration(t.cfg.TokenCacheCtxTimeout)), redis.DialDatabase(tokenDB)}
conn, err := redis.Dial("tcp", redisAddr, opts...)
if err != nil {
return errors.Wrap(err, "Error connecting")
}
defer conn.Close()
payload, err := json.Marshal(&token)
if err != nil {
return err
}
_, err = redis.String(conn.Do("SET", tokenKey, payload))
if err != nil {
return err
}
return nil
}
return nil
}