-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_cache.go
72 lines (66 loc) · 1.51 KB
/
token_cache.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
package GraphClient
import (
"encoding/json"
"io/ioutil"
"sync"
)
type ITokenCache interface {
Get(HomeAccountId string) *Token
Set(HomeAccountId string, token Token) error
Delete(HomeAccountId string) error
}
type DefaultTokenCache struct {
locker sync.Mutex
}
func (t *DefaultTokenCache) Get(HomeAccountId string) *Token {
t.locker.Lock()
defer t.locker.Unlock()
file, err := ioutil.ReadFile("./token.cache")
if err != nil {
return nil
}
m := map[string]string{}
if err := json.Unmarshal(file, &m); err != nil {
return nil
}
if m[HomeAccountId] == "" {
return nil
}
result := &Token{}
if err := json.Unmarshal([]byte(m[HomeAccountId]), result); err != nil {
return nil
}
return result
}
func (t *DefaultTokenCache) Set(HomeAccountId string, token Token) error {
t.locker.Lock()
defer t.locker.Unlock()
file, _ := ioutil.ReadFile("./token.cache")
m := map[string]string{}
_ = json.Unmarshal(file, &m)
jresult, err := json.Marshal(token)
if err != nil {
return err
}
m[HomeAccountId] = string(jresult)
result, err := json.Marshal(m)
if err != nil {
return err
}
err = ioutil.WriteFile("./token.cache", result, 0755)
return err
}
func (t *DefaultTokenCache) Delete(HomeAccountId string) error {
t.locker.Lock()
defer t.locker.Unlock()
file, _ := ioutil.ReadFile("./token.cache")
m := map[string]string{}
_ = json.Unmarshal(file, &m)
delete(m, HomeAccountId)
result, err := json.Marshal(m)
if err != nil {
return err
}
err = ioutil.WriteFile("./token.cache", result, 0755)
return err
}