This repository has been archived by the owner on Aug 24, 2019. It is now read-only.
/
google_oauth.go
243 lines (215 loc) · 5.76 KB
/
google_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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"bytes"
"encoding/gob"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"code.google.com/p/goauth2/oauth"
)
var g_config = &oauth.Config{
ClientId: "", // Set by --clientid or --clientid_file
ClientSecret: "", // Set by --secret or --secret_file
Scope: "https://www.googleapis.com/auth/moderator", // filled in per-API
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://accounts.google.com/o/oauth2/token",
AccessType: "offline",
}
// Flags
var (
clientId = flag.String("clientid", "", "OAuth Client ID. If non-empty, overrides --clientid_file")
clientIdFile = flag.String("clientid_file", "clientid.dat",
"Name of a file containing just the project's OAuth Client ID from https://code.google.com/apis/console/")
secret = flag.String("secret", "", "OAuth Client Secret. If non-empty, overrides --secret_file")
secretFile = flag.String("secret_file", "clientsecret.dat",
"Name of a file containing just the project's OAuth Client Secret from https://code.google.com/apis/console/")
cacheToken = flag.Bool("cachetoken", true, "cache the OAuth token")
debug = flag.Bool("debug", false, "show HTTP traffic")
)
func NewOauthClient(scope string) *http.Client {
g_config.Scope = scope
g_config.ClientId = valueOrFileContents(*clientId, *clientIdFile)
g_config.ClientSecret = valueOrFileContents(*secret, *secretFile)
return getOAuthClient(g_config)
}
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(g_config *oauth.Config) string {
return filepath.Join(osUserCacheDir(), url.QueryEscape(
fmt.Sprintf("go-api-demo-%s-%s-%s", g_config.ClientId, g_config.ClientSecret, g_config.Scope)))
}
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 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 condDebugTransport(rt http.RoundTripper) http.RoundTripper {
if *debug {
return &logTransport{rt}
}
return rt
}
func getOAuthClient(g_config *oauth.Config) *http.Client {
cacheFile := tokenCacheFile(g_config)
token, err := tokenFromFile(cacheFile)
if err != nil {
token = tokenFromWeb(g_config)
saveToken(cacheFile, token)
} else {
// log.Printf("Using cached token %#v from %q", token, cacheFile)
}
t := &oauth.Transport{
Token: token,
Config: g_config,
Transport: condDebugTransport(http.DefaultTransport),
}
return t.Client()
}
func tokenFromWeb(g_config *oauth.Config) *oauth.Token {
ch := make(chan string)
randState := fmt.Sprintf("st%d", time.Now())
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()
g_config.RedirectURL = ts.URL
fmt.Println(ts.URL)
authUrl := g_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: g_config,
Transport: condDebugTransport(http.DefaultTransport),
}
_, err := t.Exchange(code)
if err != nil {
log.Fatalf("Token exchange error: %v", err)
}
return t.Token
}
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 valueOrFileContents(value string, filename string) string {
if value != "" {
return value
}
slurp, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("Error reading %q: %v", filename, err)
}
return strings.TrimSpace(string(slurp))
}
type logTransport struct {
rt http.RoundTripper
}
func (t *logTransport) RoundTrip(req *http.Request) (*http.Response, error) {
var buf bytes.Buffer
os.Stdout.Write([]byte("\n[request]\n"))
if req.Body != nil {
req.Body = ioutil.NopCloser(&readButCopy{req.Body, &buf})
}
req.Write(os.Stdout)
if req.Body != nil {
req.Body = ioutil.NopCloser(&buf)
}
os.Stdout.Write([]byte("\n[/request]\n"))
res, err := t.rt.RoundTrip(req)
fmt.Printf("[response]\n")
if err != nil {
fmt.Printf("ERROR: %v", err)
} else {
body := res.Body
res.Body = nil
res.Write(os.Stdout)
if body != nil {
res.Body = ioutil.NopCloser(&echoAsRead{body})
}
}
return res, err
}
type echoAsRead struct {
src io.Reader
}
func (r *echoAsRead) Read(p []byte) (int, error) {
n, err := r.src.Read(p)
if n > 0 {
os.Stdout.Write(p[:n])
}
if err == io.EOF {
fmt.Printf("\n[/response]\n")
}
return n, err
}
type readButCopy struct {
src io.Reader
dst io.Writer
}
func (r *readButCopy) Read(p []byte) (int, error) {
n, err := r.src.Read(p)
if n > 0 {
r.dst.Write(p[:n])
}
return n, err
}