From 1dab612d58fc3bb9759e0a69076d8e91166ce9f4 Mon Sep 17 00:00:00 2001 From: Jack <57058925+JackYifan@users.noreply.github.com> Date: Sun, 16 Jun 2024 11:29:32 +0800 Subject: [PATCH] feat: add user interactions in casbinJsGetPermissionForUser method (#397) * feat: add user interactions in casbinJsGetPermissionForUser method * fix: Refactoring method casbinJsGetPermissionForUser --- .../org/casbin/jcasbin/main/Frontend.java | 24 +++++++++++-------- .../casbin/jcasbin/main/FrontendUnitTest.java | 8 +++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/casbin/jcasbin/main/Frontend.java b/src/main/java/org/casbin/jcasbin/main/Frontend.java index e035cc7c..dc7660a8 100644 --- a/src/main/java/org/casbin/jcasbin/main/Frontend.java +++ b/src/main/java/org/casbin/jcasbin/main/Frontend.java @@ -27,16 +27,20 @@ public static String casbinJsGetPermissionForUser(Enforcer e, String user) { Model model = e.getModel(); Map m = new HashMap<>(); m.put("m", model.saveModelToText().trim()); - List> policies = new ArrayList<>(); - for (String ptype : model.model.get("p").keySet()) { - List> policy = model.getPolicy("p", ptype); - for (List p : policy) { - List tmp = new ArrayList<>(p); - tmp.add(0, ptype); - policies.add(tmp); - } - } - m.put("p", policies); + m.put("p", getPolicyBySection(model,"p")); + m.put("g", getPolicyBySection(model,"g")); return new Gson().toJson(m); } + private static List> getPolicyBySection(Model model, String section) { + List> policies = new ArrayList<>(); + for (String ptype : model.model.get(section).keySet()) { + List> policy = model.getPolicy(section, ptype); + for (List p : policy) { + List tmp = new ArrayList<>(p); + tmp.add(0, ptype); + policies.add(tmp); + } + } + return policies; + } } diff --git a/src/test/java/org/casbin/jcasbin/main/FrontendUnitTest.java b/src/test/java/org/casbin/jcasbin/main/FrontendUnitTest.java index 64fa70b2..904a5cfc 100644 --- a/src/test/java/org/casbin/jcasbin/main/FrontendUnitTest.java +++ b/src/test/java/org/casbin/jcasbin/main/FrontendUnitTest.java @@ -22,6 +22,7 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.List; +import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; @@ -35,6 +36,7 @@ public void testCasbinJsGetPermissionForUser() throws IOException { assertEquals(received.get("m"), expectedModelStr); String expectedPolicyStr = new String(Files.readAllBytes(Paths.get("examples/rbac_with_hierarchy_policy.csv"))); + expectedPolicyStr = Pattern.compile("\n+").matcher(expectedPolicyStr).replaceAll("\n"); String[] expectedPolicyItem = expectedPolicyStr.split(",|\n"); int i = 0; for (List sArr : (List>) received.get("p")) { @@ -43,5 +45,11 @@ public void testCasbinJsGetPermissionForUser() throws IOException { i++; } } + for (List sArr : (List>) received.get("g")) { + for (String s : sArr) { + assertEquals(expectedPolicyItem[i].trim(), s.trim()); + i++; + } + } } }