forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokensource.go
55 lines (43 loc) · 1.03 KB
/
tokensource.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
package oauth
import (
"errors"
"sync"
"github.com/imdario/mergo"
"golang.org/x/oauth2"
)
type TokenRefresher interface {
RefreshToken(token *oauth2.Token) (*oauth2.Token, error)
}
type TokenSource struct {
mu sync.Mutex
token *oauth2.Token
refresher TokenRefresher
}
func RefreshTokenSource(token *oauth2.Token, refresher TokenRefresher) oauth2.TokenSource {
ts := &TokenSource{
token: token,
refresher: refresher,
}
return ts
}
func (ts *TokenSource) Token() (*oauth2.Token, error) {
ts.mu.Lock()
defer ts.mu.Unlock()
if ts.token.Valid() {
return ts.token, nil
}
token, err := ts.refresher.RefreshToken(ts.token)
if err != nil {
return ts.token, err
}
if token.AccessToken == "" {
err = errors.New("token refresh failed to obtain access token")
} else {
err = ts.mergeToken(token)
}
return ts.token, err
}
// mergeToken updates a token while preventing wiping the refresh token
func (ts *TokenSource) mergeToken(t *oauth2.Token) error {
return mergo.Merge(ts.token, t, mergo.WithOverride)
}