-
Notifications
You must be signed in to change notification settings - Fork 34
/
creds.go
83 lines (69 loc) · 1.56 KB
/
creds.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package robinhood
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/user"
"path"
"strings"
"golang.org/x/oauth2"
)
var defaultPath = ""
func init() {
u, err := user.Current()
if err == nil {
defaultPath = path.Join(u.HomeDir, ".config", "robinhood.token")
}
}
// A CredsCacher takes user credentials and a file path. The token obtained
// from the RobinHood API will be cached at the file path, and a new token will
// not be obtained.
type CredsCacher struct {
Creds oauth2.TokenSource
Path string
}
// Token implements TokenSource. It may fail if an error is encountered
// checking the file path provided, or if the underlying creds return an error
// when retrieving their token.
func (c *CredsCacher) Token() (*oauth2.Token, error) {
if c.Path == "" {
c.Path = defaultPath
}
mustLogin := false
err := os.MkdirAll(path.Dir(c.Path), 0750)
if err != nil {
return nil, fmt.Errorf("error creating path for token: %s", err)
}
_, err = os.Stat(c.Path)
if err != nil {
if strings.Contains(err.Error(), "no such file") {
mustLogin = true
} else {
return nil, err
}
}
if !mustLogin {
bs, err := ioutil.ReadFile(c.Path)
if err != nil {
return nil, err
}
if len(bs) > 0 {
var o oauth2.Token
if err := json.Unmarshal(bs, &o); err == nil && o.Valid() {
return &o, err
}
}
}
tok, err := c.Creds.Token()
if err != nil {
return nil, err
}
f, err := os.OpenFile(c.Path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640)
if err != nil {
return nil, err
}
defer f.Close()
err = json.NewEncoder(f).Encode(tok)
return tok, err
}