This repository has been archived by the owner on Aug 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
access_token.go
90 lines (71 loc) · 1.77 KB
/
access_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
package youdu
import (
"errors"
"strconv"
"time"
)
const getTokenUrl = "/cgi/gettoken"
type accessToken struct {
accessToken string
expire time.Time
}
type accessTokenProvider struct {
config *Config
accessToken accessToken
}
func NewAccessTokenProvider(config *Config) *accessTokenProvider {
return &accessTokenProvider{
config: config,
}
}
func (p *accessTokenProvider) GetAccessToken() (string, error) {
// from memory
if at := p.accessToken.GetAccessToken(); at != "" && p.accessToken.Expire().After(time.Now()) {
return at, nil
}
// from cache
// todo: support cache
return p.Refresh()
}
func (p *accessTokenProvider) Refresh() (string, error) {
// encrypt
encrypt, err := p.config.GetEncryptor().Encrypt(strconv.Itoa(int(time.Now().Unix())))
if err != nil {
return "", err
}
resp, err := p.config.GetHttp().Post(getTokenUrl, map[string]interface{}{
"appId": p.config.AppId,
"buin": p.config.Buin,
"encrypt": encrypt,
})
if err != nil {
return "", err
}
if !resp.IsSuccess() {
return "", errors.New("Response status code is " + strconv.Itoa(resp.StatusCode()))
}
jsonRet, err := resp.Json()
if err != nil {
return "", err
}
decrypt, err := p.config.GetEncryptor().Decrypt(jsonRet["encrypt"].(string))
if err != nil {
return "", err
}
var v struct {
AccessToken string `json:"accessToken"`
ExpireIn int `json:"expireIn"`
}
if err := decrypt.Unmarshal(&v); err != nil {
return "", err
}
p.accessToken.accessToken = v.AccessToken
p.accessToken.expire = time.Now().Add(time.Duration(v.ExpireIn-600) * time.Second) // 提前10分钟失效
return p.accessToken.accessToken, nil
}
func (a accessToken) GetAccessToken() string {
return a.accessToken
}
func (a accessToken) Expire() time.Time {
return a.expire
}