-
Notifications
You must be signed in to change notification settings - Fork 176
/
helper.go
101 lines (91 loc) · 2.11 KB
/
helper.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
package gorbac
import "fmt"
// WalkHandler is a function defined by user to handle role
type WalkHandler[T comparable] func(Role[T], []T) error
// Walk passes each Role to WalkHandler
func Walk[T comparable](rbac *RBAC[T], h WalkHandler[T]) (err error) {
if h == nil {
return
}
rbac.mutex.Lock()
defer rbac.mutex.Unlock()
for id := range rbac.roles {
var parents []T
r := rbac.roles[id]
for parent := range rbac.parents[id] {
parents = append(parents, parent)
}
if err := h(r, parents); err != nil {
return err
}
}
return
}
// InherCircle returns an error when detecting any circle inheritance.
func InherCircle[T comparable](rbac *RBAC[T]) (err error) {
rbac.mutex.Lock()
skipped := make(map[T]struct{}, len(rbac.roles))
var stack []T
for id := range rbac.roles {
if err = dfs(rbac, id, skipped, stack); err != nil {
break
}
}
rbac.mutex.Unlock()
return err
}
var (
ErrFoundCircle = fmt.Errorf("Found circle")
)
// https://en.wikipedia.org/wiki/Depth-first_search
func dfs[T comparable](rbac *RBAC[T], id T, skipped map[T]struct{},
stack []T) error {
if _, ok := skipped[id]; ok {
return nil
}
for _, item := range stack {
if item == id {
return ErrFoundCircle
}
}
parents := rbac.parents[id]
if len(parents) == 0 {
stack = nil
skipped[id] = empty
return nil
}
stack = append(stack, id)
for pid := range parents {
if err := dfs(rbac, pid, skipped, stack); err != nil {
return err
}
}
return nil
}
// AnyGranted checks if any role has the permission.
func AnyGranted[T comparable](rbac *RBAC[T], roles []T,
permission Permission[T], assert AssertionFunc[T]) (ok bool) {
rbac.mutex.Lock()
for _, role := range roles {
if rbac.isGranted(role, permission, assert) {
ok = true
break
}
}
rbac.mutex.Unlock()
return
}
// AllGranted checks if all roles have the permission.
func AllGranted[T comparable](rbac *RBAC[T], roles []T,
permission Permission[T], assert AssertionFunc[T]) (ok bool) {
ok = true
rbac.mutex.Lock()
for _, role := range roles {
if !rbac.isGranted(role, permission, assert) {
ok = false
break
}
}
rbac.mutex.Unlock()
return
}