-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_functions_test.go
58 lines (46 loc) · 1.49 KB
/
example_functions_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
package fastac_test
import (
"github.com/abichinger/fastac"
"github.com/abichinger/fastac/model"
"github.com/abichinger/fastac/model/fm"
)
//the model uses a custom MatchingFunc named customPathMatch
var example_functions_model = `
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && customPathMatch(r.obj, p.obj) && r.act == p.act`
var example_functions_policy = [][]string{
{"p", "alice", "*", "GET"},
{"p", "alice", "/user/alice", "PATCH"},
}
// ExampleFunctions shows how to use a custom util.MatchingFunc
func Example_functions() {
//customPathMatch needs to be registered before loading the model
fm.SetFunction("customPathMatch", func(arguments ...interface{}) (interface{}, error) {
rObj := arguments[0].(string)
rSub := arguments[1].(string)
if rSub == "*" {
return true, nil
}
return rObj == rSub, nil
})
//create enforcer and add rules
m := model.NewModel()
_ = m.LoadModelFromText(example_functions_model)
e, _ := fastac.NewEnforcer(m, nil)
_ = e.AddRules(example_functions_policy)
//perform some requests
printReq(e, "alice", "/user/alice/entry/1", "GET")
printReq(e, "bob", "/user/alice/entry/1", "GET")
printReq(e, "alice", "/user/alice", "PATCH")
printReq(e, "bob", "/user/alice", "PATCH")
// Output: alice, /user/alice/entry/1, GET => allow
// bob, /user/alice/entry/1, GET => deny
// alice, /user/alice, PATCH => allow
// bob, /user/alice, PATCH => deny
}