-
Notifications
You must be signed in to change notification settings - Fork 176
/
role.go
72 lines (63 loc) · 1.47 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
package gorbac
import (
"sync"
)
// Roles is a map
type Roles[T comparable] map[T]Role[T]
// NewStdRole is the default role factory function.
// It matches the declaration to RoleFactoryFunc.
func NewRole[T comparable](id T) Role[T] {
return Role[T]{
ID: id,
permissions: make(Permissions[T]),
}
}
// StdRole is the default role implement.
// You can combine this struct into your own Role implement.
// T is the type of ID
type Role[T comparable] struct {
sync.RWMutex
// ID is the serialisable identity of role
ID T `json:"id"`
permissions Permissions[T]
}
// Assign a permission to the role.
func (role *Role[T]) Assign(p Permission[T]) error {
role.Lock()
role.permissions[p.ID()] = p
role.Unlock()
return nil
}
// Permit returns true if the role has specific permission.
func (role *Role[T]) Permit(p Permission[T]) (ok bool) {
var zero Permission[T]
if p == zero {
return false
}
role.RLock()
for _, rp := range role.permissions {
if rp.Match(p) {
ok = true
break
}
}
role.RUnlock()
return
}
// Revoke the specific permission.
func (role *Role[T]) Revoke(p Permission[T]) error {
role.Lock()
delete(role.permissions, p.ID())
role.Unlock()
return nil
}
// Permissions returns all permissions into a slice.
func (role *Role[T]) Permissions() []Permission[T] {
role.RLock()
result := make([]Permission[T], 0, len(role.permissions))
for _, p := range role.permissions {
result = append(result, p)
}
role.RUnlock()
return result
}