-
Notifications
You must be signed in to change notification settings - Fork 3
/
store_boltdbfile.go
380 lines (320 loc) · 8.63 KB
/
store_boltdbfile.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Copyright 2016 Author YuShuangqi. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tokenauth
import (
"encoding/json"
"errors"
"fmt"
"github.com/boltdb/bolt"
"os"
"path/filepath"
)
// Store implement by boltdb,see:https://github.com/boltdb/bolt
type BoltDBFileStore struct {
Alias string
db *bolt.DB
dbPath string
}
var (
// all tokens save in this buckert
buckert_alltokens = []byte("bk_all_tokeninfo")
// a one audience tokens save relation in audience's buckert child bukert.
buckert_oneAudienceTokens = []byte("bk_one_audience_tokens")
// one audience info key
audienceInfoKey = []byte("one_audience")
buckert_singletokens_singledids = []byte("bk_token_singleIDs")
)
func (store *BoltDBFileStore) DBPath() string {
return store.dbPath
}
//delete audience and all tokens of this audience
func (store *BoltDBFileStore) deleteAudience(id string, tx *bolt.Tx) error {
bk := tx.Bucket([]byte(id))
if bk == nil {
return nil
}
tokensBk := tx.Bucket(buckert_alltokens)
if tokensBk != nil {
audienceTokensBk := bk.Bucket(buckert_oneAudienceTokens)
err := audienceTokensBk.ForEach(func(k, v []byte) error {
return tokensBk.Delete(k)
})
if err != nil {
return err
}
}
// Last need delete client bucket
return tx.DeleteBucket([]byte(id))
}
// Save audience into store.
// Returns error if error occured during execution.
func (store *BoltDBFileStore) SaveAudience(audience *Audience) error {
if audience == nil || len(audience.ID) == 0 {
return errors.New("audience id is empty.")
}
bytes, err := json.Marshal(audience)
if err != nil {
return err
}
return store.db.Update(func(tx *bolt.Tx) error {
// need delete old audience info before save
if err := store.deleteAudience(audience.ID, tx); err != nil {
return err
}
bk, err := tx.CreateBucket([]byte(audience.ID))
if err != nil {
return err
}
if _, err = bk.CreateBucket(buckert_oneAudienceTokens); err != nil {
return err
}
if err = bk.Put(audienceInfoKey, bytes); err != nil {
return err
}
return nil
})
}
// Delete audience and all tokens of audience.
func (store *BoltDBFileStore) DeleteAudience(audienceID string) error {
if len(audienceID) == 0 {
return errors.New("audienceID is emtpty.")
}
return store.db.Update(func(tx *bolt.Tx) error {
return store.deleteAudience(audienceID, tx)
})
}
// Get audience info or returns error.
func (store *BoltDBFileStore) GetAudience(audienceID string) (audience *Audience, err error) {
if len(audienceID) == 0 {
return nil, errors.New("audienceID is emtpty.")
}
err = store.db.View(func(tx *bolt.Tx) error {
bk := tx.Bucket([]byte(audienceID))
// not found
if bk == nil {
return nil
}
bytes := bk.Get(audienceInfoKey)
if bytes == nil {
return nil
}
audience = &Audience{}
if err := json.Unmarshal(bytes, audience); err != nil {
audience = nil
return err
} else {
return nil
}
})
return
}
// Save token to store. return error when save fail.
// Save token json to store and save the relation of token with client if not single model.
// The first , token must not empty and effectiveness.
// Does not consider concurrency.
func (store *BoltDBFileStore) SaveToken(token *Token) error {
if token == nil || len(token.Value) == 0 {
return errors.New("token tokenString is empty.")
}
if len(token.ClientID) == 0 && len(token.SingleID) == 0 {
return errors.New("token clientid and singleid,It can't be empty")
}
if token.Expired() {
return errors.New("token is expired,not need save.")
}
//first to get token byte data
tokenBytes, err := json.Marshal(token)
if err != nil {
return err
}
return store.db.Update(func(tx *bolt.Tx) error {
bk, err := tx.CreateBucketIfNotExists(buckert_alltokens)
if err != nil {
return err
}
// Singlge token has no client. But need delete old token
if token.IsSingle() {
if idsBK, err := tx.CreateBucketIfNotExists(buckert_singletokens_singledids); err != nil {
return err
} else {
key := []byte(token.SingleID)
// Find and delete old token.
oldTokenValueData := idsBK.Get(key)
if oldTokenValueData != nil {
if err = store.deleteToken(string(oldTokenValueData), tx); err != nil {
return err
}
}
// Save new token relation
if err = idsBK.Put(key, []byte(token.Value)); err != nil {
return err
}
}
} else {
// Need add token key to client blucket.
// Only save the relation of token with client.
if au := tx.Bucket([]byte(token.ClientID)); au == nil {
return errors.New("can not found audience, not save audience before save token ?")
} else if err = au.Bucket(buckert_oneAudienceTokens).Put([]byte(token.Value), []byte("")); err != nil {
return err
}
}
// Safe check.
if err != nil {
return err
}
err = bk.Put([]byte(token.Value), tokenBytes)
return err
})
}
//Get token info if find in store,or return error
func (store *BoltDBFileStore) GetToken(tokenString string) (token *Token, err error) {
if len(tokenString) == 0 {
return nil, errors.New("tokenString is empty.")
}
err = store.db.View(func(tx *bolt.Tx) error {
bk := tx.Bucket(buckert_alltokens)
if bk == nil {
return nil
}
tokenBytes := bk.Get([]byte(tokenString))
if tokenBytes == nil {
return nil
}
token = &Token{}
if err := json.Unmarshal(tokenBytes, token); err != nil {
token = nil
return err
} else {
return nil
}
})
return
}
// Delete token
// Returns error if delete token fail.
func (store *BoltDBFileStore) DeleteToken(tokenString string) error {
if len(tokenString) == 0 {
return errors.New("incompatible tokenString")
}
return store.db.Update(func(tx *bolt.Tx) error {
return store.deleteToken(tokenString, tx)
})
}
// Delete token
// Returns error if delete token fail.
func (store *BoltDBFileStore) deleteToken(tokenString string, tx *bolt.Tx) error {
bk := tx.Bucket(buckert_alltokens)
if bk == nil {
return errors.New("incompatible tokenString")
}
key := []byte(tokenString)
tokenBytes := bk.Get(key)
// Not found
if tokenBytes == nil {
return errors.New("incompatible tokenString")
}
err := bk.Delete(key)
if err != nil {
return err
}
//clear the relation token with client
token := &Token{}
err = json.Unmarshal(tokenBytes, token)
if err == nil && token.IsSingle() == false {
err = tx.Bucket([]byte(token.ClientID)).Bucket(buckert_oneAudienceTokens).Delete(key)
}
return err
}
// Open db if db is not opened.
// Returns error if open new db fail or close old db fail if exist
func (store *BoltDBFileStore) open(dbPath string) error {
// Do not open same db again
if store.db != nil && dbPath == store.db.Path() {
return nil
}
//check file dir path or create dir.
dir := filepath.Dir(dbPath)
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
err = os.Mkdir(dir, 0766)
}
if err != nil {
return err
}
}
if db, err := bolt.Open(dbPath, 0666, nil); err != nil {
return err
} else {
//close old db before use new db
if store.db != nil {
err = store.db.Close()
if err != nil {
db.Close() //need close new db
return errors.New("store: close old db fail," + err.Error())
}
}
store.db = db
store.dbPath = db.Path()
}
return nil
}
// Close bolt db
func (store *BoltDBFileStore) Close() error {
if store.db != nil {
return store.db.Close()
}
return nil
}
// Delete token if token expired
func (store *BoltDBFileStore) DeleteExpired() {
if store.db == nil {
return
}
store.db.View(func(tx *bolt.Tx) error {
// Get all tokens bucket.
bk := tx.Bucket(buckert_alltokens)
if bk == nil {
return nil
}
// Foreach all tokens.
bk.ForEach(func(k, v []byte) error {
token := &Token{}
if err := json.Unmarshal(v, token); err == nil {
// Will delete token when expired
if token.Expired() {
store.DeleteToken(token.Value)
}
}
return nil
})
return nil
})
return
}
// Init and Open BoltDBF.
// config is json string.
// e.g:
// {"path":"./data/tokenbolt.db"}
func (store *BoltDBFileStore) Open(config string) error {
if len(config) == 0 {
return errors.New("boltdbStore: bolt db store config is empty")
}
var cf map[string]string
if err := json.Unmarshal([]byte(config), &cf); err != nil {
return fmt.Errorf("boltdbStore: unmarshal %p fail:%s", config, err.Error())
}
if path, ok := cf["path"]; !ok {
return errors.New("boltdbStore: bolt db store config has no path key.")
} else {
return store.open(path)
}
}
// new Bolt DB file store instance.
func NewBoltDBFileStore() *BoltDBFileStore {
return &BoltDBFileStore{Alias: "BoltDBFileStore"}
}
func init() {
RegStore("default", NewBoltDBFileStore())
}