forked from cychiuae/casbin-pg-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiltered_adapter.go
85 lines (72 loc) · 2.37 KB
/
filtered_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
package casbinpgadapter
import (
"database/sql"
"errors"
casbinModel "github.com/casbin/casbin/v2/model"
"github.com/casbin/casbin/v2/persist"
"github.com/nrfta/go-casbin-pg-adapter/pkg/model"
)
// FilteredAdapter is the filtered file adapter for Casbin. It can load policy
// from file or save policy to file and supports loading of filtered policies.
type FilteredAdapter struct {
*Adapter
filtered bool
}
var _ = persist.FilteredAdapter(&FilteredAdapter{})
// NewFilteredAdapter is the constructor for FilteredAdapter.
func NewFilteredAdapter(db *sql.DB, tableName string) (*FilteredAdapter, error) {
a := FilteredAdapter{filtered: false}
var err error
a.Adapter, err = NewAdapter(db, tableName)
return &a, err
}
// NewFilteredAdapterWithDBSchema return a pointer for FilteredAdapter which has schema dbSchema
func NewFilteredAdapterWithDBSchema(db *sql.DB, dbSchema string, tableName string) (*FilteredAdapter, error) {
a := FilteredAdapter{filtered: false}
var err error
a.Adapter, err = NewAdapterWithDBSchema(db, dbSchema, tableName)
return &a, err
}
// LoadPolicy loads all policy rules from the storage.
func (a *FilteredAdapter) LoadPolicy(model casbinModel.Model) error {
a.filtered = false
return a.Adapter.LoadPolicy(model)
}
// LoadFilteredPolicy loads only policy rules that match the filter.
func (a *FilteredAdapter) LoadFilteredPolicy(mod casbinModel.Model, filter interface{}) error {
if filter == nil {
return a.LoadPolicy(mod)
}
filterValue, ok := filter.(*model.Filter)
if !ok {
return errors.New("invalid filter type")
}
err := a.loadFilteredPolicyFile(mod, filterValue)
if err == nil {
a.filtered = true
}
return err
}
func (a *FilteredAdapter) loadFilteredPolicyFile(model casbinModel.Model, filter *model.Filter) error {
casbinRules, err := a.casbinRuleRepository.LoadFilteredRules(filter)
if err != nil {
return err
}
for _, casbinRule := range casbinRules {
rule := casbinRule.ToStringSlice()
sec := rule[0][0:1]
model.AddPolicy(sec, rule[0], rule[1:])
}
return nil
}
// IsFiltered returns true if the loaded policy has been filtered.
func (a *FilteredAdapter) IsFiltered() bool {
return a.filtered
}
// SavePolicy saves all policy rules to the storage.
func (a *FilteredAdapter) SavePolicy(model casbinModel.Model) error {
if a.filtered {
return errors.New("cannot save a filtered policy")
}
return a.Adapter.SavePolicy(model)
}