forked from sintanial/amocrm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoken_storage.go
54 lines (44 loc) · 1.06 KB
/
token_storage.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
package amocrm
import (
"encoding/json"
"io/ioutil"
"os"
"time"
)
type TokenStorage interface {
SetToken(Token) error
GetToken() (Token, error)
}
type JSONFileTokenStorage struct {
File string
}
type JSONToken struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
}
func (self JSONFileTokenStorage) SetToken(token Token) error {
jt := JSONToken{
AccessToken: token.AccessToken(),
RefreshToken: token.RefreshToken(),
TokenType: token.TokenType(),
ExpiresAt: token.ExpiresAt(),
}
data, err := json.Marshal(jt)
if err != nil {
return err
}
return ioutil.WriteFile(self.File, data, os.ModePerm)
}
func (self JSONFileTokenStorage) GetToken() (Token, error) {
data, err := ioutil.ReadFile(self.File)
if err != nil {
return nil, nil
}
var jt JSONToken
if err := json.Unmarshal(data, &jt); err != nil {
return nil, err
}
return NewToken(jt.AccessToken, jt.RefreshToken, jt.TokenType, jt.ExpiresAt), nil
}