-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoken_cache.go
More file actions
48 lines (41 loc) · 1.1 KB
/
token_cache.go
File metadata and controls
48 lines (41 loc) · 1.1 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
package colony
import (
"sync"
"time"
)
// tokenEntry holds a cached JWT token and its expiry.
type tokenEntry struct {
token string
expiry time.Time
}
// globalTokenCache is a process-wide token cache shared across Client
// instances. Keyed by apiKey + "\x00" + baseURL so that clients with the
// same credentials share a token.
var globalTokenCache sync.Map // map[string]*tokenEntry
func tokenCacheKey(apiKey, baseURL string) string {
return apiKey + "\x00" + baseURL
}
func getCachedToken(apiKey, baseURL string) (string, bool) {
key := tokenCacheKey(apiKey, baseURL)
v, ok := globalTokenCache.Load(key)
if !ok {
return "", false
}
entry := v.(*tokenEntry)
if time.Now().After(entry.expiry) {
globalTokenCache.Delete(key)
return "", false
}
return entry.token, true
}
func setCachedToken(apiKey, baseURL, token string) {
key := tokenCacheKey(apiKey, baseURL)
globalTokenCache.Store(key, &tokenEntry{
token: token,
expiry: time.Now().Add(tokenCacheDuration),
})
}
func clearCachedToken(apiKey, baseURL string) {
key := tokenCacheKey(apiKey, baseURL)
globalTokenCache.Delete(key)
}