forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
51 lines (41 loc) · 1.12 KB
/
helper.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
package oauth
import (
"time"
"github.com/evcc-io/evcc/util"
"golang.org/x/oauth2"
)
// Refresh refreshes the token every 5m. If token refresh fails 5 times, it is aborted.
func Refresh(log *util.Logger, token *oauth2.Token, ts oauth2.TokenSource, optMaxTokenLifetime ...time.Duration) {
var failed int
// limit lifetime of initial token
limitTokenLife(token, optMaxTokenLifetime...)
for range time.Tick(5 * time.Minute) {
// get token- either previous or new
t, err := ts.Token()
if err != nil {
// error means refresh failed
failed++
if failed > 5 {
log.ERROR.Printf("token refresh: %v, giving up", err)
return
}
log.ERROR.Printf("token refresh: %v", err)
continue
}
failed = 0
// limit lifetime of new tokens
if t.Expiry != token.Expiry {
token = t
limitTokenLife(token, optMaxTokenLifetime...)
}
}
}
func limitTokenLife(token *oauth2.Token, optMaxTokenLifetime ...time.Duration) {
if len(optMaxTokenLifetime) != 1 {
return
}
maxTokenLifetime := optMaxTokenLifetime[0]
if time.Until(token.Expiry) > maxTokenLifetime {
token.Expiry = time.Now().Add(maxTokenLifetime)
}
}