forked from databendlabs/databend-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_token.go
59 lines (47 loc) · 1.39 KB
/
access_token.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 godatabend
import (
"context"
"io/ioutil"
"github.com/BurntSushi/toml"
)
// AccessTokenLoader is used on Bearer authentication. The token may have a limited
// lifetime, you can rotate your token by this interface.
type AccessTokenLoader interface {
// LoadAccessToken is called whenever a new request is made to the server.
LoadAccessToken(ctx context.Context, forceRotate bool) (string, error)
}
type StaticAccessTokenLoader struct {
AccessToken string
}
func NewStaticAccessTokenLoader(accessToken string) *StaticAccessTokenLoader {
return &StaticAccessTokenLoader{
AccessToken: accessToken,
}
}
func (l *StaticAccessTokenLoader) LoadAccessToken(ctx context.Context, forceRotate bool) (string, error) {
return l.AccessToken, nil
}
type FileAccessTokenLoader struct {
path string
}
type FileAccessTokenData struct {
AccessToken string `toml:"access_token"`
}
func NewFileAccessTokenLoader(path string) *FileAccessTokenLoader {
return &FileAccessTokenLoader{
path: path,
}
}
// try decode as toml, if not toml, return the plain key content
func (l *FileAccessTokenLoader) LoadAccessToken(ctx context.Context, forceRotate bool) (string, error) {
buf, err := ioutil.ReadFile(l.path)
if err != nil {
return "", err
}
content := string(buf)
data := &FileAccessTokenData{}
if _, err = toml.Decode(content, &data); err == nil {
return data.AccessToken, nil
}
return content, nil
}