Skip to content

Commit 1dab612

Browse files
authored
feat: add user interactions in casbinJsGetPermissionForUser method (casbin#397)
* feat: add user interactions in casbinJsGetPermissionForUser method * fix: Refactoring method casbinJsGetPermissionForUser
1 parent 536d194 commit 1dab612

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

src/main/java/org/casbin/jcasbin/main/Frontend.java

+14-10
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,20 @@ public static String casbinJsGetPermissionForUser(Enforcer e, String user) {
2727
Model model = e.getModel();
2828
Map<String, Object> m = new HashMap<>();
2929
m.put("m", model.saveModelToText().trim());
30-
List<List<String>> policies = new ArrayList<>();
31-
for (String ptype : model.model.get("p").keySet()) {
32-
List<List<String>> policy = model.getPolicy("p", ptype);
33-
for (List<String> p : policy) {
34-
List<String> tmp = new ArrayList<>(p);
35-
tmp.add(0, ptype);
36-
policies.add(tmp);
37-
}
38-
}
39-
m.put("p", policies);
30+
m.put("p", getPolicyBySection(model,"p"));
31+
m.put("g", getPolicyBySection(model,"g"));
4032
return new Gson().toJson(m);
4133
}
34+
private static List<List<String>> getPolicyBySection(Model model, String section) {
35+
List<List<String>> policies = new ArrayList<>();
36+
for (String ptype : model.model.get(section).keySet()) {
37+
List<List<String>> policy = model.getPolicy(section, ptype);
38+
for (List<String> p : policy) {
39+
List<String> tmp = new ArrayList<>(p);
40+
tmp.add(0, ptype);
41+
policies.add(tmp);
42+
}
43+
}
44+
return policies;
45+
}
4246
}

src/test/java/org/casbin/jcasbin/main/FrontendUnitTest.java

+8
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.nio.file.Paths;
2323
import java.util.HashMap;
2424
import java.util.List;
25+
import java.util.regex.Pattern;
2526

2627
import static org.junit.Assert.assertEquals;
2728

@@ -35,6 +36,7 @@ public void testCasbinJsGetPermissionForUser() throws IOException {
3536
assertEquals(received.get("m"), expectedModelStr);
3637

3738
String expectedPolicyStr = new String(Files.readAllBytes(Paths.get("examples/rbac_with_hierarchy_policy.csv")));
39+
expectedPolicyStr = Pattern.compile("\n+").matcher(expectedPolicyStr).replaceAll("\n");
3840
String[] expectedPolicyItem = expectedPolicyStr.split(",|\n");
3941
int i = 0;
4042
for (List<String> sArr : (List<List<String>>) received.get("p")) {
@@ -43,5 +45,11 @@ public void testCasbinJsGetPermissionForUser() throws IOException {
4345
i++;
4446
}
4547
}
48+
for (List<String> sArr : (List<List<String>>) received.get("g")) {
49+
for (String s : sArr) {
50+
assertEquals(expectedPolicyItem[i].trim(), s.trim());
51+
i++;
52+
}
53+
}
4654
}
4755
}

0 commit comments

Comments
 (0)