-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
256 lines (216 loc) · 6.08 KB
/
store.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package otpgateway
import (
"errors"
"fmt"
"time"
"github.com/gomodule/redigo/redis"
"github.com/zplzpl/otpgateway/models"
)
// ErrNotExist is thrown when an OTP (requested by namespace / ID)
// does not exist.
var ErrNotExist = errors.New("the OTP does not exist")
// Store represents a storage backend where OTP data is stored.
type Store interface {
// Set sets an OTP against an ID. Every Set() increments the attempts
// count against the ID that was initially set.
Set(namespace, id string, otp models.OTP) (models.OTP, error)
// SetAddress sets (updates) the address on an existing OTP.
SetAddress(namespace, id, address string) error
// Check checks the attempt count and TTL duration against an ID.
// Passing counter=true increments the attempt counter.
Check(namespace, id string, counter bool) (models.OTP, error)
// Close closes an OTP and marks it as done (verified).
// After this, the OTP has to expire after a TTL or be deleted.
Close(namespace, id string) error
// Delete deletes the OTP saved against a given ID.
Delete(namespace, id string) error
// Ping checks if store is reachable
Ping() error
}
// redisStore implements a Redis Store.
type redisStore struct {
pool *redis.Pool
keyPrefix string
}
// RedisConf contains Redis configuration fields.
type RedisConf struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
MaxActive int `mapstructure:"max_active"`
MaxIdle int `mapstructure:"max_idle"`
Timeout time.Duration `mapstructure:"timeout"`
KeyPrefix string `mapstructure:"key_prefix"`
}
// NewRedisStore returns a Redis implementation of store.
func NewRedisStore(c RedisConf) Store {
if c.KeyPrefix == "" {
c.KeyPrefix = "OTP"
}
pool := &redis.Pool{
Wait: true,
MaxActive: c.MaxActive,
MaxIdle: c.MaxIdle,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial(
"tcp",
fmt.Sprintf("%s:%d", c.Host, c.Port),
redis.DialPassword(c.Password),
redis.DialConnectTimeout(c.Timeout),
redis.DialReadTimeout(c.Timeout),
redis.DialWriteTimeout(c.Timeout),
)
return c, err
},
}
return &redisStore{
pool: pool,
keyPrefix: c.KeyPrefix,
}
}
// Ping checks if Redis server is reachable
func (r *redisStore) Ping() error {
c := r.pool.Get()
defer c.Close()
_, err := c.Do("PING") // Test redis connection
return err
}
// Check checks the attempt count and TTL duration against an ID.
// Passing count=true increments the attempt counter.
func (r *redisStore) Check(namespace, id string, counter bool) (models.OTP, error) {
c := r.pool.Get()
defer c.Close()
out, err := r.get(namespace, id, c)
if err != nil {
return out, err
}
if !counter {
return out, err
}
// Increment attempts.
key := r.makeKey(namespace, id)
r.begin(c)
c.Send("HINCRBY", key, "attempts", 1)
c.Send("TTL", key)
resp, err := r.end(c)
if err != nil {
return out, err
}
attempts, _ := redis.Int(resp[0], nil)
out.Attempts = attempts
ttl, _ := redis.Int64(resp[1], nil)
out.TTL = time.Duration(ttl) * time.Second
return out, err
}
// Set sets an OTP in the store.
func (r *redisStore) Set(namespace, id string, otp models.OTP) (models.OTP, error) {
c := r.pool.Get()
defer c.Close()
// Set the OTP value.
var (
key = r.makeKey(namespace, id)
exp = otp.TTL.Nanoseconds() / int64(time.Millisecond)
)
r.begin(c)
c.Send("HMSET", key,
"otp", otp.OTP,
"to", otp.To,
"channel_description", otp.ChannelDesc,
"address_description", otp.AddressDesc,
"extra", string(otp.Extra),
"provider", otp.Provider,
"closed", false,
"max_attempts", otp.MaxAttempts)
c.Send("HINCRBY", key, "attempts", 1)
c.Send("PEXPIRE", key, exp)
// Flush the commands and get their responses.
// [1] is the number of attempts.
// [3] is the TTL.
resp, err := r.end(c)
if err != nil {
return otp, err
}
attempts, err := redis.Int(resp[1], nil)
if err != nil {
return otp, err
}
otp.Attempts = attempts
otp.TTLSeconds = otp.TTL.Seconds()
otp.Namespace = namespace
otp.ID = id
return otp, nil
}
// SetAddress sets (updates) the address on an existing OTP.
func (r *redisStore) SetAddress(namespace, id, address string) error {
c := r.pool.Get()
defer c.Close()
// Set the OTP value.
var key = r.makeKey(namespace, id)
if _, err := c.Do("HSET", key, "to", address); err != nil {
return err
}
return nil
}
// Close closes an OTP and marks it as done (verified).
// After this, the OTP has to expire after a TTL or be deleted.
func (r *redisStore) Close(namespace, id string) error {
c := r.pool.Get()
defer c.Close()
_, err := c.Do("HSET", r.makeKey(namespace, id), "closed", true)
return err
}
// Delete deletes the OTP saved against a given ID.
func (r *redisStore) Delete(namespace, id string) error {
c := r.pool.Get()
defer c.Close()
_, err := c.Do("DEL", r.makeKey(namespace, id))
return err
}
// get begins a transaction.
func (r *redisStore) get(namespace, id string, c redis.Conn) (models.OTP, error) {
var (
key = r.makeKey(namespace, id)
out = models.OTP{
Namespace: namespace,
ID: id,
}
)
resp, err := redis.Values(c.Do("HGETALL", key))
if err != nil {
return out, err
}
if err := redis.ScanStruct(resp, &out); err != nil {
return out, err
}
// Doesn't exist?
if out.OTP == "" {
return out, ErrNotExist
}
ttl, err := redis.Int64(c.Do("TTL", key))
if err != nil {
return out, err
}
out.TTL = time.Duration(ttl) * time.Second
out.TTLSeconds = out.TTL.Seconds()
return out, nil
}
// begin begins a transaction.
func (r *redisStore) begin(c redis.Conn) error {
return c.Send("MULTI")
}
// end begins a transaction.
func (r *redisStore) end(c redis.Conn) ([]interface{}, error) {
rep, err := redis.Values(c.Do("EXEC"))
// Check if there are any errors.
for _, r := range rep {
if v, ok := r.(redis.Error); ok {
return rep, v
}
}
return rep, err
}
// makeKey makes the Redis key for the OTP.
func (r *redisStore) makeKey(namespace, id string) string {
return fmt.Sprintf("%s:%s:%s", r.keyPrefix, namespace, id)
}