-
Notifications
You must be signed in to change notification settings - Fork 0
/
role.go
64 lines (53 loc) · 1.25 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
package rbac
import (
"errors"
"fmt"
"math/bits"
)
// Option allows to configure role.
type Option func(*Role) error
// Role represents a role.
type Role struct {
name string
resources map[Resource]AccessLevel
}
// NewRole constructs a role.
func NewRole(name string, options ...Option) (*Role, error) {
if name == "" {
return nil, errors.New("empty role name")
}
r := &Role{
name: name,
resources: make(map[Resource]AccessLevel),
}
for _, option := range options {
if err := option(r); err != nil {
return nil, err
}
}
return r, nil
}
// CanAccess checks whether the role can access the resource.
func (r *Role) CanAccess(resource Resource, mask AccessMask) bool {
for res, level := range r.resources {
if res.String() == resource.String() {
return uint8(mask)&bits.RotateLeft8(1, level.Int()) != 0
}
}
return false
}
// WithResource configures resource with access level.
func WithResource(r Resource, level AccessLevel) Option {
return func(role *Role) error {
if r == nil {
return fmt.Errorf("resource is nil")
}
for res := range role.resources {
if res.String() == r.String() {
return fmt.Errorf("resource %s is already defined", r.String())
}
}
role.resources[r] = level
return nil
}
}