-
Notifications
You must be signed in to change notification settings - Fork 2
/
role.go
75 lines (62 loc) · 1.15 KB
/
role.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
package gocqrs
type Role struct {
Name string `json:"name"`
// Access to entities
Entities []string
// events and read cmd that can be executed ,default ALL
Allowed []string `json:"allowed"`
NotAllowed []string `json:"noAllowed"`
}
func NewRole(r string) *Role {
var role Role
if r == "" {
panic("invalid role name")
}
role.Name = r
role.Allowed = make([]string, 0)
role.NotAllowed = make([]string, 0)
return &role
}
func (r *Role) CanRead(e string) bool {
allowed := false
if len(r.Entities) == 0 {
allowed = true
}
for _, entity := range r.Entities {
if entity == e {
allowed = true
break
}
}
return allowed
}
func (r *Role) Can(e string) bool {
allowed := false
if len(r.Allowed) == 0 {
allowed = true
} else {
for _, ae := range r.Allowed {
if ae == e {
allowed = true
break
}
}
}
for _, de := range r.NotAllowed {
if e == de {
allowed = false
break
}
}
return allowed
}
func (r *Role) Allow(cmd ...string) {
for _, c := range cmd {
r.Allowed = append(r.Allowed, c)
}
}
func (r *Role) NotAllow(cmd ...string) {
for _, c := range cmd {
r.NotAllowed = append(r.NotAllowed, c)
}
}