-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpermission_manager.go
62 lines (50 loc) · 1.44 KB
/
permission_manager.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
package casbin
import (
"app/authz"
"app/internal/ref"
"github.com/casbin/casbin/v2"
)
var _ authz.PermissionManager = (*PermissionManager)(nil)
type PermissionManager struct {
enforcer *casbin.Enforcer
}
func NewPermissionManager(enforcer *casbin.Enforcer) *PermissionManager {
return &PermissionManager{enforcer: enforcer}
}
func (permissionManager *PermissionManager) Check(req authz.Request) bool {
hasPermission, err := permissionManager.enforcer.Enforce(
req.Subject.String(),
req.Domain,
req.Object.String(),
req.Action,
)
return err == nil && hasPermission
}
func (permissionManager *PermissionManager) Add(policies ...authz.Policy) error {
_, err := permissionManager.enforcer.AddPoliciesEx(toRules(policies))
return err
}
func (permissionManager *PermissionManager) Remove(policies ...authz.Policy) error {
_, err := permissionManager.enforcer.RemovePolicies(toRules(policies))
return err
}
func (permissionManager *PermissionManager) RemoveBySubject(subject ref.Ref) error {
_, err := permissionManager.enforcer.RemoveFilteredPolicy(RequestSubjectIndex, subject.String())
return err
}
func toRule(policy authz.Policy) []string {
return []string{
policy.Subject.String(),
policy.Domain,
policy.Object.String(),
policy.Action,
policy.Effect,
}
}
func toRules(policies []authz.Policy) [][]string {
rules := make([][]string, len(policies))
for i, policy := range policies {
rules[i] = toRule(policy)
}
return rules
}