Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
66 lines (58 loc) · 2.04 KB
/
Copy pathconfig.go
File metadata and controls
66 lines (58 loc) · 2.04 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package oauthctx
import (
"context"
"net/http"
"golang.org/x/oauth2"
)
// Config describes a typical 3-legged OAuth2 flow, with both the
// client application information and the server's endpoint URLs.
// For the client credentials 2-legged OAuth2 flow, see the ClientCredentials.
type Config struct{ *oauth2.Config }
// NewConfig creates new Config
func NewConfig(cfg *oauth2.Config) *Config {
return &Config{Config: cfg}
}
// Client returns an HTTP client using the provided token.
// The token will auto-refresh as necessary. The underlying
// HTTP transport will be obtained from options.
// The returned client and its Transport should not be modified.
func (c *Config) Client(t *oauth2.Token, ops ...RequestFlowOp) *http.Client {
conf := NewRequestFlowConfig(ops...)
return NewClient(
c.TokenSource(t, conf.TokenSourceOps()...), // TokenSource seeds the cache with t; NewClient short-circuits ReuseTokenSource, matching oauth2.Config.Client behaviour
conf.ClientOps()...)
}
// TokenSource returns a TokenSource that returns t until t expires,
// automatically refreshing it as necessary.
//
// Most users will use Config.Client instead.
func (c *Config) TokenSource(t *oauth2.Token, ops ...TokenSourceOp) TokenSource {
tkr := &tokenRefresher{
srcConf: NewTokenSourceConfig(ops...),
oauthConf: c.Config,
}
if t != nil {
tkr.refreshToken = t.RefreshToken
}
return ReuseTokenSource(t, tkr)
}
// tokenRefresher is a TokenSource that performs "grant_type=refresh_token"
// requests. It is not safe for concurrent use because it mutates refreshToken
// on each call; it must always be wrapped in a ReuseTokenSource.
type tokenRefresher struct {
srcConf *TokenSourceConfig
oauthConf *oauth2.Config
refreshToken string
}
func (tf *tokenRefresher) TokenContext(ctx context.Context) (*oauth2.Token, error) {
src := tf.oauthConf.TokenSource(
tf.srcConf.WithOauth2HTTPClient(ctx),
&oauth2.Token{RefreshToken: tf.refreshToken},
)
tk, err := src.Token()
if err != nil {
return nil, err
}
tf.refreshToken = tk.RefreshToken
return tk, nil
}