Skip to content

Commit

Permalink
Add RESTful support for g
Browse files Browse the repository at this point in the history
  • Loading branch information
nodece committed Dec 9, 2018
1 parent a50dc57 commit 8cfc636
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
11 changes: 11 additions & 0 deletions model_test.go
Expand Up @@ -273,6 +273,17 @@ func TestRBACModelWithCustomData(t *testing.T) {
testEnforce(t, e, "bob", "data2", "write", true)
}

func TestRBACModelWithRESTful(t *testing.T) {
e := NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")

e.AddGroupingPolicy("/resource/:id", "data2_admin")

testEnforce(t, e, "/resource/1", "data2", "read", true)
testEnforce(t, e, "/resource/1", "data2", "write", true)
testEnforce(t, e, "/resource/1", "data1", "read", false)
testEnforce(t, e, "/resource/1", "data1", "write", false)
}

type testCustomRoleManager struct{}

func NewRoleManager() rbac.RoleManager {
Expand Down
28 changes: 27 additions & 1 deletion rbac/default-role-manager/role_manager.go
Expand Up @@ -16,16 +16,19 @@ package defaultrolemanager

import (
"errors"
"strings"
"sync"

"github.com/casbin/casbin/log"
"github.com/casbin/casbin/rbac"
"github.com/casbin/casbin/util"
)

// RoleManager provides a default implementation for the RoleManager interface
type RoleManager struct {
allRoles *sync.Map
maxHierarchyLevel int
restful bool
}

// NewRoleManager is the constructor for creating an instance of the
Expand All @@ -38,11 +41,30 @@ func NewRoleManager(maxHierarchyLevel int) rbac.RoleManager {
}

func (rm *RoleManager) hasRole(name string) bool {
_, ok := rm.allRoles.Load(name)
var ok bool
if rm.restful {
rm.allRoles.Range(func(key, value interface{}) bool {
if util.KeyMatch2(name, key.(string)) {
ok = true
}
return true
})
} else {
_, ok = rm.allRoles.Load(name)
}

return ok
}

func (rm *RoleManager) createRole(name string) *Role {
if rm.restful {
rm.allRoles.Range(func(key, value interface{}) bool {
if util.KeyMatch2(name, key.(string)) {
name = key.(string)
}
return true
})
}
role, _ := rm.allRoles.LoadOrStore(name, newRole(name))
return role.(*Role)
}
Expand All @@ -64,6 +86,10 @@ func (rm *RoleManager) AddLink(name1 string, name2 string, domain ...string) err
return errors.New("error: domain should be 1 parameter")
}

if strings.Contains(name1, "/*") || strings.Contains(name1, "/:") {
rm.restful = true
}

role1 := rm.createRole(name1)
role2 := rm.createRole(name2)
role1.addRole(role2)
Expand Down

0 comments on commit 8cfc636

Please sign in to comment.