-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.go
59 lines (45 loc) · 1.11 KB
/
auth.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
package client
import (
"net/http"
"golang.org/x/oauth2"
)
// NewOAUTHWrapper returns a TransportWrapper which adds
// OAUTH2 authentication to a HTTP transport.
func NewOAUTHWrapper(opts ...OAUTHOption) *OAUTHWrapper {
var cfg OAUTHConfig
cfg.Option(opts...)
return &OAUTHWrapper{
transport: oauth2.Transport{
Source: cfg.source,
},
}
}
type OAUTHWrapper struct {
transport oauth2.Transport
}
func (w *OAUTHWrapper) RoundTrip(req *http.Request) (*http.Response, error) {
return w.transport.RoundTrip(req)
}
func (w *OAUTHWrapper) Wrap(rt http.RoundTripper) http.RoundTripper {
w.transport.Base = rt
return w
}
type OAUTHConfig struct {
source oauth2.TokenSource
}
func (c *OAUTHConfig) Option(opts ...OAUTHOption) {
for _, opt := range opts {
opt.ConfigureOAUTH(c)
}
}
type OAUTHOption interface {
ConfigureOAUTH(*OAUTHConfig)
}
// WithAccessToken configures a OAUTHWrapper with an OAUTH2 token
// used when making requests.
type WithAccessToken string
func (at WithAccessToken) ConfigureOAUTH(c *OAUTHConfig) {
c.source = oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: string(at),
})
}