-
Notifications
You must be signed in to change notification settings - Fork 56
/
oauth2.go
61 lines (53 loc) · 1.54 KB
/
oauth2.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
package gads
import (
"encoding/json"
"io/ioutil"
"golang.org/x/net/context"
"golang.org/x/oauth2"
)
type AuthConfig struct {
file string `json:"-"`
OAuth2Config *oauth2.Config `json:"oauth2.Config"`
OAuth2Token *oauth2.Token `json:"oauth2.Token"`
tokenSource oauth2.TokenSource `json:"-"`
Auth Auth `json:"gads.Auth"`
}
func NewCredentialsFromFile(pathToFile string, ctx context.Context) (ac AuthConfig, err error) {
data, err := ioutil.ReadFile(pathToFile)
if err != nil {
return ac, err
}
if err := json.Unmarshal(data, &ac); err != nil {
return ac, err
}
ac.file = pathToFile
ac.tokenSource = ac.OAuth2Config.TokenSource(ctx, ac.OAuth2Token)
ac.Auth.Client = ac.OAuth2Config.Client(ctx, ac.OAuth2Token)
return ac, err
}
func NewCredentials(ctx context.Context) (ac AuthConfig, err error) {
return NewCredentialsFromFile(*configJson, ctx)
}
// Save writes the contents of AuthConfig back to the JSON file it was
// loaded from.
func (c AuthConfig) Save() error {
configData, err := json.MarshalIndent(&c, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(c.file, configData, 0600)
}
// Token implements oauth2.TokenSource interface and store updates to
// config file.
func (c AuthConfig) Token() (token *oauth2.Token, err error) {
// use cached token
if c.OAuth2Token.Valid() {
return c.OAuth2Token, err
}
// get new token from tokens source and store
c.OAuth2Token, err = c.tokenSource.Token()
if err != nil {
return nil, err
}
return token, c.Save()
}