-
Notifications
You must be signed in to change notification settings - Fork 3
/
token.go
112 lines (92 loc) · 2.38 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
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
package main
import "encoding/json"
import "fmt"
import "io/ioutil"
import "log"
import "net/http"
import "net/url"
import "os"
import "strings"
import "time"
var myClient = &http.Client{Timeout: 10 * time.Second}
type Token struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
Scope []string `json:"scope"`
ExpiresIn int `json:"expires_in"`
ExpireIn int `json:"expire_in"`
}
type TokenFile struct {
Token *Token `json:"token"`
Refreshed time.Time `json:"refreshed"`
}
func readCacheToken(tokenFilePath string) *TokenFile {
jsonFile, err := os.Open(tokenFilePath)
if err != nil {
log.Panic(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var tokenFile TokenFile
err = json.Unmarshal(byteValue, &tokenFile)
if err != nil {
log.Panic(err)
}
return &tokenFile
}
func writeCacheToken(tokenFilePath string, r *Token) {
file, err := json.MarshalIndent(TokenFile{
Token: r,
Refreshed: time.Now(),
}, "", " ")
if err != nil {
log.Panic(err)
}
err = ioutil.WriteFile(tokenFilePath, file, 0600)
if err != nil {
log.Panic(err)
}
}
func doRefresh(refreshToken string) *Token {
reqBody := fmt.Sprintf(
"grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s", url.QueryEscape(refreshToken), clientId, clientSecret)
url := "https://app.velux-active.com/oauth2/token"
req, err := http.NewRequest("POST", url, strings.NewReader(reqBody))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if Debug {
log.Printf("token refresh: %+v", req)
}
resp, err := myClient.Do(req)
if err != nil {
log.Panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panic(err)
}
r := new(Token)
err = json.Unmarshal(body, &r)
if err != nil {
log.Panic(err)
}
if r.AccessToken == "" {
log.Panicf("invalid response: %s", body)
}
return r
}
func refreshToken(tokenFilePath string) *Token {
tokenFile := readCacheToken(tokenFilePath)
var resultToken *Token
expireTime := tokenFile.Refreshed.Add(time.Second * time.Duration(tokenFile.Token.ExpireIn))
if expireTime.Before(time.Now()) {
resultToken = doRefresh(tokenFile.Token.RefreshToken)
writeCacheToken(tokenFilePath, resultToken)
} else {
if Debug {
log.Println("skip refreshing token")
}
resultToken = tokenFile.Token
}
return resultToken
}