-
Notifications
You must be signed in to change notification settings - Fork 46
/
cached_authorizer.go
80 lines (67 loc) · 1.96 KB
/
cached_authorizer.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
package auth
import (
"context"
"fmt"
"net/http"
"sync"
"golang.org/x/oauth2"
)
// Copyright (c) HashiCorp Inc. All rights reserved.
// Licensed under the MIT License. See NOTICE.txt in the project root for license information.
var _ Authorizer = &CachedAuthorizer{}
// CachedAuthorizer caches a token until it expires, then acquires a new token from Source
type CachedAuthorizer struct {
// Source contains the underlying Authorizer for obtaining tokens
Source Authorizer
mutex sync.RWMutex
token *oauth2.Token
auxTokens []*oauth2.Token
}
// Token returns the current token if it's still valid, else will acquire a new token
func (c *CachedAuthorizer) Token(ctx context.Context, req *http.Request) (*oauth2.Token, error) {
c.mutex.RLock()
valid := c.token != nil && c.token.Valid()
c.mutex.RUnlock()
if !valid {
c.mutex.Lock()
defer c.mutex.Unlock()
var err error
c.token, err = c.Source.Token(ctx, req)
if err != nil {
return nil, err
}
}
return c.token, nil
}
// AuxiliaryTokens returns additional tokens for auxiliary tenant IDs, for use in multi-tenant scenarios
func (c *CachedAuthorizer) AuxiliaryTokens(ctx context.Context, req *http.Request) ([]*oauth2.Token, error) {
c.mutex.RLock()
var valid bool
for _, token := range c.auxTokens {
valid = token != nil && token.Valid()
if !valid {
break
}
}
c.mutex.RUnlock()
if !valid {
c.mutex.Lock()
defer c.mutex.Unlock()
var err error
c.auxTokens, err = c.Source.AuxiliaryTokens(ctx, req)
if err != nil {
return nil, err
}
}
return c.auxTokens, nil
}
// NewCachedAuthorizer returns an Authorizer that caches an access token for the duration of its validity.
// If the cached token expires, a new one is acquired and cached.
func NewCachedAuthorizer(src Authorizer) (Authorizer, error) {
if _, ok := src.(*SharedKeyAuthorizer); ok {
return nil, fmt.Errorf("internal-error: SharedKeyAuthorizer cannot be cached")
}
return &CachedAuthorizer{
Source: src,
}, nil
}