-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth.go
133 lines (121 loc) · 2.93 KB
/
oauth.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"encoding/gob"
"errors"
"fmt"
"hash/fnv"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"time"
"code.google.com/p/goauth2/oauth"
)
func osUserCacheDir() string {
switch runtime.GOOS {
case "darwin":
return filepath.Join(os.Getenv("HOME"), "Library", "Caches")
case "linux", "freebsd":
return filepath.Join(os.Getenv("HOME"), ".cache")
}
log.Printf("TODO: osUserCacheDir on GOOS %q", runtime.GOOS)
return "."
}
func tokenCacheFile(config *oauth.Config) string {
hash := fnv.New32a()
hash.Write([]byte(config.ClientId))
hash.Write([]byte(config.ClientSecret))
hash.Write([]byte(config.Scope))
fn := fmt.Sprintf("inevo-gdriver%v", hash.Sum32())
return filepath.Join(osUserCacheDir(), url.QueryEscape(fn))
}
func tokenFromFile(file string) (*oauth.Token, error) {
if !*cacheToken {
return nil, errors.New("--cachetoken is false")
}
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := new(oauth.Token)
err = gob.NewDecoder(f).Decode(t)
return t, err
}
func openUrl(url string) {
try := []string{"xdg-open", "google-chrome", "open"}
for _, bin := range try {
err := exec.Command(bin, url).Run()
if err == nil {
return
}
}
log.Printf("Error opening URL in browser.")
}
func tokenFromWeb(config *oauth.Config) *oauth.Token {
ch := make(chan string)
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/favicon.ico" {
http.Error(rw, "", 404)
return
}
if req.FormValue("state") != randState {
log.Printf("State doesn't match: req = %#v", req)
http.Error(rw, "", 500)
return
}
if code := req.FormValue("code"); code != "" {
fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
rw.(http.Flusher).Flush()
ch <- code
return
}
log.Printf("no code")
http.Error(rw, "", 500)
}))
defer ts.Close()
config.RedirectURL = ts.URL
authUrl := config.AuthCodeURL(randState)
go openUrl(authUrl)
log.Printf("Authorize this app at: %s", authUrl)
code := <-ch
log.Printf("Got code: %s", code)
t := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
_, err := t.Exchange(code)
if err != nil {
log.Fatalf("Token exchange error: %v", err)
}
return t.Token
}
func saveToken(file string, token *oauth.Token) {
f, err := os.Create(file)
if err != nil {
log.Printf("Warning: failed to cache oauth token: %v", err)
return
}
defer f.Close()
gob.NewEncoder(f).Encode(token)
}
func getOAuthClient(config *oauth.Config) *http.Client {
cacheFile := tokenCacheFile(config)
token, err := tokenFromFile(cacheFile)
if err != nil {
token = tokenFromWeb(config)
saveToken(cacheFile, token)
} else {
log.Printf("Using cached token %#v from %q", token, cacheFile)
}
t := &oauth.Transport{
Token: token,
Config: config,
Transport: http.DefaultTransport,
}
return t.Client()
}