-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_manager.go
104 lines (95 loc) · 2.17 KB
/
token_manager.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gdsync
import (
"encoding/gob"
"fmt"
"net/http"
"os"
"time"
"code.google.com/p/goauth2/oauth"
)
type TokenManager struct {
Transport *oauth.Transport
Config *oauth.Config
Filename string
}
func NewTokenManager(config *oauth.Config, filename, passphrase string) (*TokenManager, error) {
if filename != "" {
config.AccessType = "offline"
}
mgr := &TokenManager{
Config: config,
Filename: filename,
}
err := mgr.initialize(passphrase)
if err != nil {
return nil, err
}
return mgr, nil
}
func (mgr *TokenManager) recoverFromStoredToken(passphrase string) error {
if mgr.Filename == "" {
return os.ErrNotExist
}
fin, err := NewProtectedFileReader(mgr.Filename, passphrase)
if err != nil {
return err
}
defer fin.File.Close()
var token *oauth.Token = nil
if err := gob.NewDecoder(fin).Decode(&token); err != nil {
return err
}
t := &oauth.Transport {
Config: mgr.Config,
Token: token,
Transport: http.DefaultTransport,
}
if !token.Expiry.IsZero() && token.Expiry.Before(time.Now()) {
err := t.Refresh()
if (err != nil) {
return err
}
fout, err := NewProtectedFileWriter(mgr.Filename, passphrase)
if err == nil {
gob.NewEncoder(fout).Encode(token)
fout.File.Close()
}
}
mgr.Transport = t
return nil
}
func (mgr *TokenManager) initialize(passphrase string) error {
if err := mgr.recoverFromStoredToken(passphrase); err == nil {
return nil
}
// Generate a URL to visit for authorization.
authUrl := mgr.Config.AuthCodeURL("state")
fmt.Printf("Go to the following link in your browser: %v\n", authUrl)
t := &oauth.Transport{
Config: mgr.Config,
Transport: http.DefaultTransport,
}
// Read the code, and exchange it for a token.
fmt.Printf("Enter verification code: ")
var code string
fmt.Scanln(&code)
_, err := t.Exchange(code)
if err != nil {
return err
}
mgr.Transport = t
if mgr.Filename != "" {
fout, err := NewProtectedFileWriter(mgr.Filename, passphrase)
if err != nil {
fmt.Printf("An error occured storing the auth file: %v\n", err)
} else {
fout.File.Chmod(0600)
gob.NewEncoder(fout).Encode(t.Token)
fout.File.Close()
}
}
return nil
}
func init() {
gob.Register(oauth.Token{})
}