-
Notifications
You must be signed in to change notification settings - Fork 928
/
uaa_authentication.go
74 lines (61 loc) · 1.86 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
package wrapper
import (
"bytes"
"io/ioutil"
"net/http"
"code.cloudfoundry.org/cli/api/cloudcontroller"
)
//go:generate counterfeiter . UAAClient
// UAAClient is the interface for getting a valid access token
type UAAClient interface {
AccessToken() string
RefreshToken() error
}
// UAAAuthentication wraps connections and adds authentication headers to all
// requests
type UAAAuthentication struct {
connection cloudcontroller.Connection
client UAAClient
}
// NewUAAAuthentication returns a pointer to a UAAAuthentication wrapper with
// the client set as the AuthenticationStore
func NewUAAAuthentication(client UAAClient) *UAAAuthentication {
return &UAAAuthentication{
client: client,
}
}
// Wrap sets the connection on the UAAAuthentication and returns itself
func (t *UAAAuthentication) Wrap(innerconnection cloudcontroller.Connection) cloudcontroller.Connection {
t.connection = innerconnection
return t
}
// Make adds authentication headers to the passed in request and then calls the
// wrapped connection's Make
func (t *UAAAuthentication) Make(request *http.Request, passedResponse *cloudcontroller.Response) error {
var (
err error
rawRequestBody []byte
)
if request.Body != nil {
rawRequestBody, err = ioutil.ReadAll(request.Body)
defer request.Body.Close()
if err != nil {
return err
}
request.Body = ioutil.NopCloser(bytes.NewBuffer(rawRequestBody))
}
request.Header.Set("Authorization", t.client.AccessToken())
err = t.connection.Make(request, passedResponse)
if _, ok := err.(cloudcontroller.InvalidAuthTokenError); ok {
err = t.client.RefreshToken()
if err != nil {
return err
}
if rawRequestBody != nil {
request.Body = ioutil.NopCloser(bytes.NewBuffer(rawRequestBody))
}
request.Header.Set("Authorization", t.client.AccessToken())
err = t.connection.Make(request, passedResponse)
}
return err
}