-
Notifications
You must be signed in to change notification settings - Fork 0
/
refreshtoken.go
88 lines (77 loc) · 1.86 KB
/
refreshtoken.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
package refreshtoken
import (
"crypto/rand"
"fmt"
"time"
)
type Store interface {
Add(token, userID string)
IsOwner(token, userID string) bool
ExtendValidity(token string)
Delete(token string)
Valid(token string) bool
ExpirationTime(token string) time.Time
}
// Generate a new refresh token
func New() string {
b := make([]byte, 64)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
type storeItem struct {
expiration time.Time
owner string
}
type inMemoryRefreshTokenStore struct {
tokens map[string]storeItem
expirationTime time.Duration
}
type InMemoryTokenOption func(c *inMemoryRefreshTokenStore)
func NewInMemoryTokenStore(opts ...func(s *inMemoryRefreshTokenStore)) Store {
s := &inMemoryRefreshTokenStore{
tokens: map[string]storeItem{},
}
for _, opt := range opts {
opt(s)
}
return s
}
func WithExpTime(d time.Duration) InMemoryTokenOption {
return func(s *inMemoryRefreshTokenStore) {
s.expirationTime = d
}
}
func (s *inMemoryRefreshTokenStore) Add(token, userID string) {
s.tokens[token] = storeItem{
owner: userID,
expiration: time.Now().Add(s.expirationTime),
}
}
func (s *inMemoryRefreshTokenStore) ExtendValidity(token string) {
i, ok := s.tokens[token]
if !ok {
return // TODO: check if this can happen
}
s.tokens[token] = storeItem{
owner: i.owner,
expiration: time.Now().Add(s.expirationTime),
}
}
func (s *inMemoryRefreshTokenStore) Delete(token string) {
delete(s.tokens, token)
}
func (s *inMemoryRefreshTokenStore) Valid(token string) bool {
t, ok := s.tokens[token]
return ok && t.expiration.After(time.Now())
}
func (s *inMemoryRefreshTokenStore) IsOwner(token, userID string) bool {
t, ok := s.tokens[token]
return ok && t.owner == userID
}
func (s *inMemoryRefreshTokenStore) ExpirationTime(token string) time.Time {
t, ok := s.tokens[token]
if !ok {
return time.Time{}
}
return t.expiration
}