/
google.go
85 lines (74 loc) · 2.16 KB
/
google.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
//Code from https://developers.google.com/apps-script/guides/rest/quickstart/go
//Modified to support refreshing tokens
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
const tokenFile = "./token.credential"
// GetClient returns the generated Client.
func GetClient(scopes ...string) *http.Client {
b, err := ioutil.ReadFile("client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, scopes...)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
tok, err := tokenFromFile(tokenFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokenFile, tok)
}
ctx := context.Background()
//Very hacky, but somehow works
ts := oauth2.ReuseTokenSource(nil, config.TokenSource(ctx, tok))
t, _ := ts.Token()
return config.Client(ctx, t)
}
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Println(authURL)
var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}
// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
t := &oauth2.Token{}
err = json.NewDecoder(f).Decode(t)
return &oauth2.Token{RefreshToken: t.RefreshToken}, err
}
// saveToken uses a file path to create a file and store the
// token in it.
func saveToken(file string, token *oauth2.Token) {
log.Printf("Saving credential file to: %s\n", file)
f, err := os.Create(file)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}