-
Notifications
You must be signed in to change notification settings - Fork 928
/
uaa_authentication.go
88 lines (73 loc) · 2.54 KB
/
uaa_authentication.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 wrapper
import (
"code.cloudfoundry.org/cli/api/cloudcontroller"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccerror"
"code.cloudfoundry.org/cli/api/uaa"
)
//go:generate counterfeiter . UAAClient
// UAAClient is the interface for getting a valid access token
type UAAClient interface {
RefreshAccessToken(refreshToken string) (uaa.RefreshedTokens, error)
}
//go:generate counterfeiter . TokenCache
// TokenCache is where the UAA token information is stored.
type TokenCache interface {
AccessToken() string
RefreshToken() string
SetAccessToken(token string)
SetRefreshToken(token string)
}
// UAAAuthentication wraps connections and adds authentication headers to all
// requests
type UAAAuthentication struct {
connection cloudcontroller.Connection
client UAAClient
cache TokenCache
}
// NewUAAAuthentication returns a pointer to a UAAAuthentication wrapper with
// the client and a token cache.
func NewUAAAuthentication(client UAAClient, cache TokenCache) *UAAAuthentication {
return &UAAAuthentication{
client: client,
cache: cache,
}
}
// Wrap sets the connection on the UAAAuthentication and returns itself
func (t *UAAAuthentication) Wrap(innerconnection cloudcontroller.Connection) cloudcontroller.Connection {
t.connection = innerconnection
return t
}
// SetClient sets the UAA client that the wrapper will use.
func (t *UAAAuthentication) SetClient(client UAAClient) {
t.client = client
}
// Make adds authentication headers to the passed in request and then calls the
// wrapped connection's Make. If the client is not set on the wrapper, it will
// not add any header or handle any authentication errors.
func (t *UAAAuthentication) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error {
if t.client == nil {
return t.connection.Make(request, passedResponse)
}
request.Header.Set("Authorization", t.cache.AccessToken())
requestErr := t.connection.Make(request, passedResponse)
if _, ok := requestErr.(ccerror.InvalidAuthTokenError); ok {
tokens, err := t.client.RefreshAccessToken(t.cache.RefreshToken())
if err != nil {
return err
}
t.cache.SetAccessToken(tokens.AuthorizationToken())
t.cache.SetRefreshToken(tokens.RefreshToken)
if request.Body != nil {
err = request.ResetBody()
if err != nil {
if _, ok := err.(ccerror.PipeSeekError); ok {
return ccerror.PipeSeekError{Err: requestErr}
}
return err
}
}
request.Header.Set("Authorization", t.cache.AccessToken())
requestErr = t.connection.Make(request, passedResponse)
}
return requestErr
}