-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
64 lines (51 loc) · 1.15 KB
/
token.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
package main
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"os"
"path"
"golang.org/x/oauth2"
)
const tokenFilename = "$HOME/.gomuche/token.json"
// NewTokenFromFile reads token from file and returns it.
func NewTokenFromFile() *oauth2.Token {
filename := os.ExpandEnv(tokenFilename)
bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalln(err)
}
token := new(oauth2.Token)
err = json.Unmarshal(bytes, &token)
if err != nil {
log.Fatalln(err)
}
return token
}
// NewTokenFromCode retrieves a new token from Google using code and returns it.
func NewTokenFromCode(conf *oauth2.Config, code string) *oauth2.Token {
ctx := context.Background()
token, err := conf.Exchange(ctx, code)
if err != nil {
log.Fatalln(err)
}
SaveToken(token)
return token
}
// SaveToken saves token to file.
func SaveToken(token *oauth2.Token) {
bytes, err := json.MarshalIndent(token, "", " ")
if err != nil {
log.Fatalln(err)
}
filename := os.ExpandEnv(tokenFilename)
err = os.MkdirAll(path.Dir(filename), 0755)
if err != nil {
log.Fatalln(err)
}
err = ioutil.WriteFile(filename, bytes, 0755)
if err != nil {
log.Fatalln(err)
}
}