forked from i-love-flamingo/flamingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
145 lines (114 loc) · 2.44 KB
/
file.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package store
import (
"io/ioutil"
"path/filepath"
"sync"
"encoding/json"
"os"
"flamingo.me/flamingo/core/auth/domain"
)
type (
File struct {
sync.RWMutex
path string
}
)
var (
_ Store = &File{}
)
func (s *File) Inject(cfg *struct {
Path string `inject:"config:session.file"`
}) {
s.path = cfg.Path
}
func (s *File) DestroySessionsForUser(user domain.User) error {
s.Lock()
defer s.Unlock()
ids, err := s.getAllSessionIds(user)
if err != nil {
return err
}
err = s.destroyAllSessionsByIds(ids)
if err != nil {
return err
}
err = os.Remove(s.getAllHashesFileName(user))
if err != nil {
return err
}
return nil
}
func (s *File) SetHashAndSessionIdForUser(user domain.User, hash string, id string) error {
s.Lock()
defer s.Unlock()
ids, err := s.getAllSessionIds(user)
if err != nil {
return err
}
err = s.addSessionsId(user, ids, id)
if err != nil {
return err
}
err = s.addSessionsId(user, ids, id)
if err != nil {
return err
}
return ioutil.WriteFile(s.getHashFileName(user), []byte(hash), 0600)
}
func (s *File) GetHashByUser(user domain.User) (string, error) {
filename := s.getHashFileName(user)
s.RLock()
defer s.RUnlock()
data, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
return string(data), nil
}
func (s *File) getHashFileName(user domain.User) string {
return filepath.Join(s.path, "user_hash_"+user.Sub)
}
func (s *File) getAllHashesFileName(user domain.User) string {
return filepath.Join(s.path, "user_hashes_"+user.Sub)
}
func (s *File) getAllSessionIds(user domain.User) ([]string, error) {
filename := s.getAllHashesFileName(user)
if _, err := os.Stat(filename); os.IsNotExist(err) {
return []string{}, nil
}
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var ids []string
err = json.Unmarshal(data, &ids)
if err != nil {
return nil, err
}
return ids, nil
}
func (s *File) destroyAllSessionsByIds(ids []string) error {
for _, id := range ids {
filename := filepath.Join(s.path, "session_"+id)
if _, err := os.Stat(filename); os.IsNotExist(err) {
continue
}
err := os.Remove(filename)
if err != nil {
return err
}
}
return nil
}
func (s *File) addSessionsId(user domain.User, ids []string, id string) error {
ids = append(ids, id)
data, err := json.Marshal(ids)
if err != nil {
return err
}
err = ioutil.WriteFile(s.getAllHashesFileName(user), data, 0600)
if err != nil {
return err
}
return nil
}