-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_storage_test.go
69 lines (58 loc) · 1.49 KB
/
example_storage_test.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
package fastac_test
import (
"fmt"
"os"
"sort"
"strings"
"github.com/abichinger/fastac"
gormadapter "github.com/abichinger/gorm-adapter"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var example_rules_1 = [][]string{
{"p", "alice", "data1", "read"},
{"p", "alice", "data1", "write"},
{"p", "bob", "data1", "read"},
}
func createDB(name string) *gorm.DB {
_ = os.Mkdir(".tmp", 0755)
db, _ := gorm.Open(sqlite.Open(".tmp/"+name+".db"), &gorm.Config{})
return db
}
func removeDB(name string) {
os.Remove(".tmp/" + name + ".db")
}
// ExampleStorageAdapter shows how to store/load policy rules to/from a storage adapter
func Example_storageAdapter() {
//init adapter
db := createDB("example")
defer removeDB("example")
a, err := gormadapter.NewAdapter(db)
if err != nil {
panic(err)
}
//create enforcer and store rules using the autosave feature
e, _ := fastac.NewEnforcer("examples/basic_model.conf", a, fastac.OptionAutosave(true))
err = e.AddRules(example_rules_1)
if err != nil {
panic(err)
}
//second enforcer to demonstrate LoadPolicy
e2, _ := fastac.NewEnforcer("examples/basic_model.conf", a)
err = e2.LoadPolicy()
if err != nil {
panic(err)
}
loadedRules := []string{}
e2.GetModel().RangeRules(func(rule []string) bool {
loadedRules = append(loadedRules, strings.Join(rule, ", "))
return true
})
sort.Strings(loadedRules)
for _, rule := range loadedRules {
fmt.Println(rule)
}
// Output: p, alice, data1, read
// p, alice, data1, write
// p, bob, data1, read
}