Skip to content

Commit

Permalink
feat: add user interactions in casbinJsGetPermissionForUser method (#397
Browse files Browse the repository at this point in the history
)

* feat: add user interactions in casbinJsGetPermissionForUser method

* fix: Refactoring method casbinJsGetPermissionForUser
  • Loading branch information
JackYifan authored Jun 16, 2024
1 parent 536d194 commit 1dab612
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/main/java/org/casbin/jcasbin/main/Frontend.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,20 @@ public static String casbinJsGetPermissionForUser(Enforcer e, String user) {
Model model = e.getModel();
Map<String, Object> m = new HashMap<>();
m.put("m", model.saveModelToText().trim());
List<List<String>> policies = new ArrayList<>();
for (String ptype : model.model.get("p").keySet()) {
List<List<String>> policy = model.getPolicy("p", ptype);
for (List<String> p : policy) {
List<String> 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<List<String>> getPolicyBySection(Model model, String section) {
List<List<String>> policies = new ArrayList<>();
for (String ptype : model.model.get(section).keySet()) {
List<List<String>> policy = model.getPolicy(section, ptype);
for (List<String> p : policy) {
List<String> tmp = new ArrayList<>(p);
tmp.add(0, ptype);
policies.add(tmp);
}
}
return policies;
}
}
8 changes: 8 additions & 0 deletions src/test/java/org/casbin/jcasbin/main/FrontendUnitTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<String> sArr : (List<List<String>>) received.get("p")) {
Expand All @@ -43,5 +45,11 @@ public void testCasbinJsGetPermissionForUser() throws IOException {
i++;
}
}
for (List<String> sArr : (List<List<String>>) received.get("g")) {
for (String s : sArr) {
assertEquals(expectedPolicyItem[i].trim(), s.trim());
i++;
}
}
}
}

0 comments on commit 1dab612

Please sign in to comment.