-
Notifications
You must be signed in to change notification settings - Fork 0
/
roles.go
117 lines (102 loc) · 2.13 KB
/
roles.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package role
import (
"database/sql/driver"
"encoding/json"
"errors"
)
type Roles []Role
func (roles Roles) ByName(name string) Role {
for _, r := range roles {
if r.Name == name {
return r
}
}
return Role{}
}
func (roles Roles) NamedMap() map[string]Role {
ret := map[string]Role{}
for _, r := range roles {
ret[r.Name] = r
}
return ret
}
func (roles Roles) Value() (driver.Value, error) {
return json.Marshal(roles)
}
func (roles *Roles) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(b, &roles)
}
func (roles Roles) Can(name string) bool {
for _, role := range roles {
if role.Can(name) {
return true
}
}
return false
}
func (roles Roles) CanOnly(name string) bool {
if len(roles) == 1 && roles[0].Name == name && roles.Can(name) {
return true
}
return false
}
func (roles Roles) CanOver(name string, entityID string) bool {
for _, role := range roles {
for _, sub := range role.Over {
if sub == "*" && role.Name == name {
return role.Can(name)
}
if sub == entityID {
return role.Can(name)
}
}
if role.Implies.CanOver(name, entityID) {
return true
}
}
return false
}
func (roles *Roles) AssignEntities(name string, entityIDs []string) {
for i, role := range *roles {
if role.Name == name {
(*roles)[i].Over = entityIDs
}
}
}
func (this *Roles) Implications(validRoles Roles) {
for i, role := range *this {
role.Implies = validRoles.ByName(role.Name).Implies
for j, sub := range role.Implies {
sub.Implications(validRoles)
role.Implies[j] = sub
}
(*this)[i] = role
}
}
type Role struct {
Name string `json:"name"`
Label string `json:"label"`
Implies Roles `json:"-"`
Over []string `json:"over"`
}
func (this *Role) Implications(validRoles Roles) {
this.Implies = validRoles.ByName(this.Name).Implies
for _, role := range this.Implies {
role.Implications(validRoles)
}
}
func (this *Role) Can(role string) bool {
if role == this.Name {
return true
}
for _, sub := range this.Implies {
if sub.Can(role) {
return true
}
}
return false
}