-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcached.go
65 lines (53 loc) · 1.44 KB
/
cached.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
package internal
import (
"context"
"log"
"time"
"github.com/mniak/ytlive/config"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
type CachedTokenSource struct {
config oauth2.Config
ctx context.Context
}
func NewCachedTokenSource(ctx context.Context, config oauth2.Config) CachedTokenSource {
return CachedTokenSource{
ctx: ctx,
config: config,
}
}
func (ts CachedTokenSource) saveToken(token *oauth2.Token) error {
config.Root.Token = *token
err := config.Save()
if err != nil {
return err
}
return nil
}
func (ts CachedTokenSource) Token() (*oauth2.Token, error) {
if config.Root.Token.AccessToken != "" {
if config.Root.Token.Expiry.After(time.Now()) {
return &config.Root.Token, nil
}
log.Println("access token expired")
}
if config.Root.Token.RefreshToken == "" {
return nil, errors.New("could not refresh the token because the client secret is empty on config")
}
if config.Root.Application.ClientID == "" {
return nil, errors.New("could not refresh the token because the client id is empty on config")
}
if config.Root.Application.ClientSecret == "" {
return nil, errors.New("could not refresh the token because the client secret is empty on config")
}
token, err := ts.config.TokenSource(ts.ctx, &config.Root.Token).Token()
if err != nil {
return token, err
}
err = ts.saveToken(token)
if err != nil {
log.Println(errors.Wrap(err, "failed to write token in cache"))
}
return token, nil
}