-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtoken_store.go
More file actions
86 lines (71 loc) · 1.89 KB
/
token_store.go
File metadata and controls
86 lines (71 loc) · 1.89 KB
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
package main
import (
"encoding/base64"
"encoding/json"
"strings"
"time"
)
const MaxEntries = 3
// decoder/encoder for v2 tokens, declared here so they can be tested as compatible
var V2DecodeString = base64.RawURLEncoding.DecodeString
var V2EncodeString = base64.RawURLEncoding.EncodeToString
// prefix on all v2 base64url-encoded tokens, which when decoded is `{"entries":[`
const V2EncodedTokenPrefix = "eyJlbnRyaWVzIjpb"
type TokenEntry struct {
Token string `json:"token"`
AddedAt int64 `json:"added_at"`
}
type TokenStore struct {
Entries []TokenEntry `json:"entries"`
}
func NewTokenStore() *TokenStore {
return &TokenStore{
Entries: make([]TokenEntry, 0, MaxEntries),
}
}
func NewTokenStoreFromString(str string) *TokenStore {
ts := NewTokenStore()
ts.FromString(str)
return ts
}
func (ts *TokenStore) AddToken(token string) {
ts.AddTokenEntry(TokenEntry{
Token: token,
AddedAt: time.Now().Unix(),
})
}
func (ts *TokenStore) AddTokenEntry(entry TokenEntry) {
if len(ts.Entries) >= MaxEntries {
ts.Entries = ts.Entries[1:]
}
ts.Entries = append(ts.Entries, entry)
}
func (ts *TokenStore) FindToken(token string) *TokenEntry {
for i := len(ts.Entries) - 1; i >= 0; i-- {
if ts.Entries[i].Token == token {
return &ts.Entries[i]
}
}
return nil
}
func (ts *TokenStore) ToJSON() ([]byte, error) {
return json.Marshal(ts)
}
func (ts *TokenStore) FromJSON(data []byte) error {
return json.Unmarshal(data, ts)
}
// FromString creates a TokenStore from a string, either a plain PN token (v1) or a base64url-encoded JSON TS object (v2).
func (ts *TokenStore) FromString(str string) {
// if it looks like a v2 encoded object, try to parse it
if strings.HasPrefix(str, V2EncodedTokenPrefix) {
decoded, err := V2DecodeString(str)
if err == nil {
err = ts.FromJSON(decoded)
if err == nil {
return
}
}
}
// treat it as a single token string
ts.AddToken(str)
}