Skip to content

Commit

Permalink
feat: casbin_js_get_permission_for_user (#229)
Browse files Browse the repository at this point in the history
Signed-off-by: abingcbc <[email protected]>
  • Loading branch information
Abingcbc authored Dec 9, 2021
1 parent 010b4d8 commit 075ca10
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions casbin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .persist import *
from .effect import *
from .model import *
from .frontend import *
14 changes: 14 additions & 0 deletions casbin/frontend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import json


def casbin_js_get_permission_for_user(e, user):
model = e.get_model()
m = {}
m["m"] = model.to_text()
policies = []
for p_type in model["p"].keys():
policy = model.get_policy("p", p_type)
for p in policy:
policies.append([p_type] + p)
m["p"] = policies
return json.dumps(m)
30 changes: 30 additions & 0 deletions casbin/model/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,33 @@ def sort_policies_by_priority(self):
assertion.policy_map[",".join(policy)] = i

return None

def to_text(self):
s = []

def write_string(sec):
for p_type in self[sec]:
value = self[sec][p_type].value
s.append(
"{} = {}\n".format(
sec, value.replace("p_", "p.").replace("r_", "r.")
)
)

s.append("[request_definition]\n")
write_string("r")
s.append("[policy_definition]\n")
write_string("p")
if "g" in self.keys():
s.append("[role_definition]\n")
for p_type in self["g"]:
s.append("{} = {}\n".format(p_type, self["g"][p_type].value))
s.append("[policy_effect]\n")
write_string("e")
s.append("[matchers]\n")
write_string("m")

# remove last \n
s[-1] = s[-1].strip()

return "".join(s)
26 changes: 26 additions & 0 deletions tests/test_frontend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import json
import re
import casbin
from unittest import TestCase
from tests.test_enforcer import get_examples


class TestFrontend(TestCase):
def test_casbin_js_get_permission_for_user(self):
e = casbin.SyncedEnforcer(
get_examples("rbac_model.conf"),
get_examples("rbac_with_hierarchy_policy.csv"),
)
received = json.loads(casbin.casbin_js_get_permission_for_user(e, "alice"))
with open(get_examples("rbac_model.conf"), "r") as file:
expected_model_str = file.read()
self.assertEqual(received["m"], re.sub("\n+", "\n", expected_model_str))

with open(get_examples("rbac_with_hierarchy_policy.csv"), "r") as file:
expected_policies_str = file.read()
expected_policy_item = re.split(r",|\n", expected_policies_str)
i = 0
for s_arr in received["p"]:
for s in s_arr:
self.assertEqual(s.strip(), expected_policy_item[i].strip())
i += 1

0 comments on commit 075ca10

Please sign in to comment.