forked from mikespook/gorbac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
role.go
79 lines (69 loc) · 1.6 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
76
77
78
79
package gorbac
import (
"sync"
)
// Role is an interface.
// You should implement this interface for your own role structures.
type Role interface {
ID() string
Permit(Permission) bool
}
// Roles is a map
type Roles map[string]Role
// NewStdRole is the default role factory function.
// It matches the declaration to RoleFactoryFunc.
func NewStdRole(id string) *StdRole {
role := &StdRole{
IDStr: id,
permissions: make(Permissions),
}
return role
}
// StdRole is the default role implement.
// You can combine this struct into your own Role implement.
type StdRole struct {
sync.RWMutex
// IDStr is the identity of role
IDStr string `json:"id"`
permissions Permissions
}
// ID returns the role's identity name.
func (role *StdRole) ID() string {
return role.IDStr
}
// Assign a permission to the role.
func (role *StdRole) Assign(p Permission) error {
role.Lock()
role.permissions[p.ID()] = p
role.Unlock()
return nil
}
// Permit returns true if the role has specific permission.
func (role *StdRole) Permit(p Permission) (rslt bool) {
role.RLock()
for _, rp := range role.permissions {
if rp.Match(p) {
rslt = true
break
}
}
role.RUnlock()
return
}
// Revoke the specific permission.
func (role *StdRole) Revoke(p Permission) error {
role.Lock()
delete(role.permissions, p.ID())
role.Unlock()
return nil
}
// Permissions returns all permissions into a slice.
func (role *StdRole) Permissions() []Permission {
role.RLock()
result := make([]Permission, 0, len(role.permissions))
for _, p := range role.permissions {
result = append(result, p)
}
role.RUnlock()
return result
}