-
Notifications
You must be signed in to change notification settings - Fork 0
/
role.go
82 lines (65 loc) · 1.97 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
80
81
82
package roles
import (
"fmt"
"net/http"
"github.com/qor/qor"
)
type Role struct {
definitions map[string]func(req *http.Request, currentUser qor.CurrentUser) bool
}
func New() *Role {
return &Role{}
}
var role = &Role{}
func Register(name string, fc func(req *http.Request, currentUser qor.CurrentUser) bool) {
role.Register(name, fc)
}
func NewPermission() *Permission {
return role.newPermission()
}
func (role *Role) newPermission() *Permission {
return &Permission{
Role: role,
allowRoles: map[PermissionMode][]string{},
denyRoles: map[PermissionMode][]string{},
}
}
func Allow(mode PermissionMode, roles ...string) *Permission {
return role.Allow(mode, roles...)
}
func Deny(mode PermissionMode, roles ...string) *Permission {
return role.Deny(mode, roles...)
}
func MatchedRoles(req *http.Request, currentUser qor.CurrentUser) []string {
return role.MatchedRoles(req, currentUser)
}
func (role *Role) MatchedRoles(req *http.Request, currentUser qor.CurrentUser) (roles []string) {
if definitions := role.definitions; definitions != nil {
for name, definition := range definitions {
if definition(req, currentUser) {
roles = append(roles, name)
}
}
}
return
}
func (role *Role) Get(name string) (func(req *http.Request, currentUser qor.CurrentUser) bool, bool) {
fc, ok := role.definitions[name]
return fc, ok
}
func (role *Role) Register(name string, fc func(req *http.Request, currentUser qor.CurrentUser) bool) {
if role.definitions == nil {
role.definitions = map[string]func(req *http.Request, currentUser qor.CurrentUser) bool{}
}
definition := role.definitions[name]
if definition != nil {
fmt.Printf("%v already defined, overwrited it!\n", name)
}
role.definitions[name] = fc
}
func (role *Role) Allow(mode PermissionMode, roles ...string) *Permission {
return role.newPermission().Allow(mode, roles...)
}
func (role *Role) Deny(mode PermissionMode, roles ...string) *Permission {
return role.newPermission().Deny(mode, roles...)
}