-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
adapter.go
689 lines (592 loc) · 17.9 KB
/
adapter.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// Copyright 2018 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mongodbadapter
import (
"context"
"errors"
"fmt"
"log"
"runtime"
"strings"
"time"
"github.com/casbin/casbin/v2/model"
"github.com/casbin/casbin/v2/persist"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
const defaultTimeout time.Duration = 30 * time.Second
const defaultDatabaseName string = "casbin"
const defaultCollectionName string = "casbin_rule"
// CasbinRule represents a rule in Casbin.
type CasbinRule struct {
PType string
V0 string
V1 string
V2 string
V3 string
V4 string
V5 string
}
// adapter represents the MongoDB adapter for policy storage.
type adapter struct {
client *mongo.Client
collection *mongo.Collection
timeout time.Duration
filtered bool
}
// finalizer is the destructor for adapter.
func finalizer(a *adapter) {
a.close()
}
// NewAdapter is the constructor for Adapter. If database name is not provided
// in the Mongo URL, 'casbin' will be used as database name.
// 'casbin_rule' will be used as a collection name.
func NewAdapter(url string, timeout ...interface{}) (persist.BatchAdapter, error) {
if !strings.HasPrefix(url, "mongodb+srv://") && !strings.HasPrefix(url, "mongodb://") {
url = fmt.Sprint("mongodb://" + url)
}
// Parse and validate url before apply it.
connString, err := connstring.ParseAndValidate(url)
if err != nil {
return nil, err
}
clientOption := options.Client().ApplyURI(url)
var databaseName string
// Get database name from connString.
if connString.Database != "" {
databaseName = connString.Database
} else {
databaseName = defaultDatabaseName
}
return baseNewAdapter(clientOption, databaseName, defaultCollectionName, timeout...)
}
// NewAdapterWithClientOption is an alternative constructor for Adapter
// that does the same as NewAdapter, but uses mongo.ClientOption instead of a Mongo URL + a databaseName option
func NewAdapterWithClientOption(clientOption *options.ClientOptions, databaseName string, timeout ...interface{}) (persist.BatchAdapter, error) {
return baseNewAdapter(clientOption, databaseName, defaultCollectionName, timeout...)
}
// NewAdapterWithCollectionName is an alternative constructor for Adapter
// that does the same as NewAdapterWithClientOption, but with an extra collectionName option
func NewAdapterWithCollectionName(clientOption *options.ClientOptions, databaseName string, collectionName string, timeout ...interface{}) (persist.BatchAdapter, error) {
return baseNewAdapter(clientOption, databaseName, collectionName, timeout...)
}
// baseNewAdapter is a base constructor for Adapter
func baseNewAdapter(clientOption *options.ClientOptions, databaseName string, collectionName string, timeout ...interface{}) (persist.BatchAdapter, error) {
a := &adapter{}
a.filtered = false
if len(timeout) == 1 {
a.timeout = timeout[0].(time.Duration)
} else if len(timeout) > 1 {
return nil, errors.New("too many arguments")
} else {
a.timeout = defaultTimeout
}
// Open the DB, create it if not existed.
err := a.open(clientOption, databaseName, collectionName)
if err != nil {
return nil, err
}
// Call the destructor when the object is released.
runtime.SetFinalizer(a, finalizer)
return a, nil
}
// NewFilteredAdapter is the constructor for FilteredAdapter.
// Casbin will not automatically call LoadPolicy() for a filtered adapter.
func NewFilteredAdapter(url string) (persist.FilteredAdapter, error) {
a, err := NewAdapter(url)
if err != nil {
return nil, err
}
a.(*adapter).filtered = true
return a.(*adapter), nil
}
type AdapterConfig struct {
DatabaseName string
CollectionName string
Timeout time.Duration
IsFiltered bool
}
func NewAdapterByDB(client *mongo.Client, config *AdapterConfig) (persist.BatchAdapter, error) {
if config == nil {
config = &AdapterConfig{}
}
if config.CollectionName == "" {
config.CollectionName = defaultCollectionName
}
if config.DatabaseName == "" {
config.DatabaseName = defaultDatabaseName
}
if config.Timeout == 0 {
config.Timeout = defaultTimeout
}
collection := client.Database(config.DatabaseName).Collection(config.CollectionName)
a := &adapter{
client: client,
collection: collection,
timeout: config.Timeout,
filtered: config.IsFiltered,
}
if err := a.prepareIndexes(); err != nil {
return nil, err
}
// Call the destructor when the object is released.
runtime.SetFinalizer(a, finalizer)
return a, nil
}
func (a *adapter) open(clientOption *options.ClientOptions, databaseName string, collectionName string) error {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
client, err := mongo.Connect(ctx, clientOption)
if err != nil {
return err
}
db := client.Database(databaseName)
collection := db.Collection(collectionName)
a.client = client
a.collection = collection
if err = a.prepareIndexes(); err != nil {
return err
}
return nil
}
func (a *adapter) prepareIndexes() error {
indexes := []string{"ptype", "v0", "v1", "v2", "v3", "v4", "v5"}
keysDoc := bson.D{}
for _, k := range indexes {
keyDoc := bson.E{}
keyDoc.Key = k
keyDoc.Value = 1
keysDoc = append(keysDoc, keyDoc)
}
if _, err := a.collection.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: keysDoc,
Options: options.Index().SetUnique(true),
},
); err != nil {
return err
}
return nil
}
func (a *adapter) close() {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
_ = a.client.Disconnect(ctx)
}
func (a *adapter) dropTable() error {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
err := a.collection.Drop(ctx)
if err != nil {
return err
}
return nil
}
func loadPolicyLine(line CasbinRule, model model.Model) error {
var p = []string{line.PType,
line.V0, line.V1, line.V2, line.V3, line.V4, line.V5}
var lineText string
if line.V5 != "" {
lineText = strings.Join(p, ", ")
} else if line.V4 != "" {
lineText = strings.Join(p[:6], ", ")
} else if line.V3 != "" {
lineText = strings.Join(p[:5], ", ")
} else if line.V2 != "" {
lineText = strings.Join(p[:4], ", ")
} else if line.V1 != "" {
lineText = strings.Join(p[:3], ", ")
} else if line.V0 != "" {
lineText = strings.Join(p[:2], ", ")
}
return persist.LoadPolicyLine(lineText, model)
}
// LoadPolicy loads policy from database.
func (a *adapter) LoadPolicy(model model.Model) error {
return a.LoadFilteredPolicy(model, nil)
}
// LoadFilteredPolicy loads matching policy lines from database. If not nil,
// the filter must be a valid MongoDB selector.
func (a *adapter) LoadFilteredPolicy(model model.Model, filter interface{}) error {
if filter == nil {
a.filtered = false
filter = bson.D{{}}
} else {
a.filtered = true
}
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
cursor, err := a.collection.Find(ctx, filter)
if err != nil {
return err
}
for cursor.Next(ctx) {
line := CasbinRule{}
err := cursor.Decode(&line)
if err != nil {
return err
}
err = loadPolicyLine(line, model)
if err != nil {
return err
}
}
return cursor.Close(ctx)
}
// IsFiltered returns true if the loaded policy has been filtered.
func (a *adapter) IsFiltered() bool {
return a.filtered
}
func savePolicyLine(ptype string, rule []string) CasbinRule {
line := CasbinRule{
PType: ptype,
}
if len(rule) > 0 {
line.V0 = rule[0]
}
if len(rule) > 1 {
line.V1 = rule[1]
}
if len(rule) > 2 {
line.V2 = rule[2]
}
if len(rule) > 3 {
line.V3 = rule[3]
}
if len(rule) > 4 {
line.V4 = rule[4]
}
if len(rule) > 5 {
line.V5 = rule[5]
}
return line
}
// SavePolicy saves policy to database.
func (a *adapter) SavePolicy(model model.Model) error {
if a.filtered {
return errors.New("cannot save a filtered policy")
}
if err := a.dropTable(); err != nil {
return err
}
var lines []interface{}
for ptype, ast := range model["p"] {
for _, rule := range ast.Policy {
line := savePolicyLine(ptype, rule)
lines = append(lines, &line)
}
}
for ptype, ast := range model["g"] {
for _, rule := range ast.Policy {
line := savePolicyLine(ptype, rule)
lines = append(lines, &line)
}
}
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if _, err := a.collection.InsertMany(ctx, lines); err != nil {
return err
}
return nil
}
// AddPolicy adds a policy rule to the storage.
func (a *adapter) AddPolicy(sec string, ptype string, rule []string) error {
line := savePolicyLine(ptype, rule)
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if _, err := a.collection.InsertOne(ctx, line); err != nil {
return err
}
return nil
}
// AddPolicies adds policy rules to the storage.
func (a *adapter) AddPolicies(sec string, ptype string, rules [][]string) error {
var lines []interface{}
for _, rule := range rules {
line := savePolicyLine(ptype, rule)
lines = append(lines, line)
}
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if _, err := a.collection.InsertMany(ctx, lines); err != nil {
return err
}
return nil
}
// RemovePolicies removes policy rules from the storage.
func (a *adapter) RemovePolicies(sec string, ptype string, rules [][]string) error {
var lines []CasbinRule
for _, rule := range rules {
line := savePolicyLine(ptype, rule)
lines = append(lines, line)
}
for _, line := range lines {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if _, err := a.collection.DeleteOne(ctx, line); err != nil {
return err
}
}
return nil
}
// RemovePolicy removes a policy rule from the storage.
func (a *adapter) RemovePolicy(sec string, ptype string, rule []string) error {
line := savePolicyLine(ptype, rule)
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if _, err := a.collection.DeleteOne(ctx, line); err != nil {
return err
}
return nil
}
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
func (a *adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
selector := make(map[string]interface{})
selector["ptype"] = ptype
if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) {
if fieldValues[0-fieldIndex] != "" {
selector["v0"] = fieldValues[0-fieldIndex]
}
}
if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) {
if fieldValues[1-fieldIndex] != "" {
selector["v1"] = fieldValues[1-fieldIndex]
}
}
if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) {
if fieldValues[2-fieldIndex] != "" {
selector["v2"] = fieldValues[2-fieldIndex]
}
}
if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) {
if fieldValues[3-fieldIndex] != "" {
selector["v3"] = fieldValues[3-fieldIndex]
}
}
if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) {
if fieldValues[4-fieldIndex] != "" {
selector["v4"] = fieldValues[4-fieldIndex]
}
}
if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) {
if fieldValues[5-fieldIndex] != "" {
selector["v5"] = fieldValues[5-fieldIndex]
}
}
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if _, err := a.collection.DeleteMany(ctx, selector); err != nil {
return err
}
return nil
}
// UpdatePolicy updates a policy rule from storage.
// This is part of the Auto-Save feature.
func (a *adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error {
oldLine := savePolicyLine(ptype, oldRule)
newLine := savePolicyLine(ptype, newPolicy)
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
// Updating all the documents equals to replacing
_, err := a.collection.ReplaceOne(ctx, oldLine, newLine)
return err
}
// UpdatePolicies updates some policy rules to storage, like db, redis.
func (a *adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error {
oldLines := make([]CasbinRule, 0, len(oldRules))
newLines := make([]CasbinRule, 0, len(oldRules))
for _, oldRule := range oldRules {
oldLines = append(oldLines, savePolicyLine(ptype, oldRule))
}
for _, newRule := range newRules {
newLines = append(newLines, savePolicyLine(ptype, newRule))
}
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
for i := range oldRules {
_, err := a.collection.ReplaceOne(ctx, oldLines[i], newLines[i])
if err != nil {
return err
}
}
return nil
}
// UpdateFilteredPolicies deletes old rules and adds new rules.
func (a *adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) {
selector := make(map[string]interface{})
selector["ptype"] = ptype
if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) {
if fieldValues[0-fieldIndex] != "" {
selector["v0"] = fieldValues[0-fieldIndex]
}
}
if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) {
if fieldValues[1-fieldIndex] != "" {
selector["v1"] = fieldValues[1-fieldIndex]
}
}
if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) {
if fieldValues[2-fieldIndex] != "" {
selector["v2"] = fieldValues[2-fieldIndex]
}
}
if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) {
if fieldValues[3-fieldIndex] != "" {
selector["v3"] = fieldValues[3-fieldIndex]
}
}
if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) {
if fieldValues[4-fieldIndex] != "" {
selector["v4"] = fieldValues[4-fieldIndex]
}
}
if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) {
if fieldValues[5-fieldIndex] != "" {
selector["v5"] = fieldValues[5-fieldIndex]
}
}
oldLines := make([]CasbinRule, 0)
newLines := make([]CasbinRule, 0, len(newPolicies))
for _, newPolicy := range newPolicies {
newLines = append(newLines, savePolicyLine(ptype, newPolicy))
}
oldPolicies, err := a.updateFilteredPoliciesTxn(oldLines, newLines, selector)
if err == nil {
return oldPolicies, err
}
// (IllegalOperation) Transaction numbers are only allowed on a replica set member or mongos
if mongoErr, ok := err.(mongo.CommandError); !ok || mongoErr.Code != 20 {
return nil, err
}
log.Println("[WARNING]: As your mongodb server doesn't allow a replica set, transaction operation is not supported. So Casbin Adapter will run non-transactional updating!")
return a.updateFilteredPolicies(oldLines, newLines, selector)
}
func (a *adapter) updateFilteredPoliciesTxn(oldLines, newLines []CasbinRule, selector map[string]interface{}) ([][]string, error) {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
session, err := a.client.StartSession()
if err != nil {
return nil, err
}
defer session.EndSession(context.TODO())
_, err = session.WithTransaction(ctx, func(sessionCtx mongo.SessionContext) (interface{}, error) {
// Load old policies
cursor, err := a.collection.Find(ctx, selector)
if err != nil {
_ = session.AbortTransaction(context.Background())
return nil, err
}
for cursor.Next(ctx) {
line := CasbinRule{}
err := cursor.Decode(&line)
if err != nil {
_ = session.AbortTransaction(context.Background())
return nil, err
}
oldLines = append(oldLines, line)
}
if err = cursor.Close(ctx); err != nil {
_ = session.AbortTransaction(context.Background())
return nil, err
}
// Delete all old policies
if _, err := a.collection.DeleteMany(sessionCtx, selector); err != nil {
_ = session.AbortTransaction(context.Background())
return nil, err
}
// Insert new policies
for _, newLine := range newLines {
if _, err := a.collection.InsertOne(sessionCtx, &newLine); err != nil {
_ = session.AbortTransaction(context.Background())
return nil, err
}
}
return nil, nil
})
if err != nil {
return nil, err
}
// return deleted rulues
oldPolicies := make([][]string, 0)
for _, v := range oldLines {
oldPolicy := v.toStringPolicy()
oldPolicies = append(oldPolicies, oldPolicy)
}
return oldPolicies, nil
}
func (a *adapter) updateFilteredPolicies(oldLines, newLines []CasbinRule, selector map[string]interface{}) ([][]string, error) {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
// Load old policies
cursor, err := a.collection.Find(ctx, selector)
if err != nil {
return nil, err
}
for cursor.Next(ctx) {
line := CasbinRule{}
err := cursor.Decode(&line)
if err != nil {
return nil, err
}
oldLines = append(oldLines, line)
}
if err = cursor.Close(ctx); err != nil {
return nil, err
}
// Delete all old policies
if _, err := a.collection.DeleteMany(ctx, selector); err != nil {
return nil, err
}
// Insert new policies
for _, newLine := range newLines {
if _, err := a.collection.InsertOne(ctx, &newLine); err != nil {
return nil, err
}
}
// return deleted rulues
oldPolicies := make([][]string, 0)
for _, v := range oldLines {
oldPolicy := v.toStringPolicy()
oldPolicies = append(oldPolicies, oldPolicy)
}
return oldPolicies, nil
}
func (c *CasbinRule) toStringPolicy() []string {
policy := make([]string, 0)
if c.PType != "" {
policy = append(policy, c.PType)
}
if c.V0 != "" {
policy = append(policy, c.V0)
}
if c.V1 != "" {
policy = append(policy, c.V1)
}
if c.V2 != "" {
policy = append(policy, c.V2)
}
if c.V3 != "" {
policy = append(policy, c.V3)
}
if c.V4 != "" {
policy = append(policy, c.V4)
}
if c.V5 != "" {
policy = append(policy, c.V5)
}
return policy
}