1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.opencastproject.external.util;
22
23 import static com.entwinemedia.fn.data.json.Jsons.f;
24 import static com.entwinemedia.fn.data.json.Jsons.obj;
25 import static com.entwinemedia.fn.data.json.Jsons.v;
26
27 import org.opencastproject.security.api.AccessControlEntry;
28 import org.opencastproject.security.api.AccessControlList;
29
30 import com.entwinemedia.fn.data.json.JValue;
31 import com.entwinemedia.fn.data.json.Jsons;
32
33 import org.apache.commons.lang3.StringUtils;
34 import org.json.simple.JSONArray;
35 import org.json.simple.JSONObject;
36 import org.json.simple.parser.JSONParser;
37 import org.json.simple.parser.ParseException;
38
39 import java.util.ArrayList;
40 import java.util.List;
41 import java.util.ListIterator;
42
43 public final class AclUtils {
44 private static final String ACTION_JSON_KEY = "action";
45 private static final String ALLOW_JSON_KEY = "allow";
46 private static final String ROLE_JSON_KEY = "role";
47
48 private AclUtils() {
49 }
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 public static AccessControlList deserializeJsonToAcl(String json, boolean assumeAllow)
65 throws IllegalArgumentException, ParseException {
66 JSONParser parser = new JSONParser();
67 JSONArray aclJson = (JSONArray) parser.parse(json);
68 @SuppressWarnings("unchecked")
69 ListIterator<Object> iterator = aclJson.listIterator();
70 JSONObject aceJson;
71 List<AccessControlEntry> entries = new ArrayList<AccessControlEntry>();
72 while (iterator.hasNext()) {
73 aceJson = (JSONObject) iterator.next();
74 String action = aceJson.get(ACTION_JSON_KEY) != null ? aceJson.get(ACTION_JSON_KEY).toString() : "";
75 String allow;
76 if (assumeAllow) {
77 allow = "true";
78 } else {
79 allow = aceJson.get(ALLOW_JSON_KEY) != null ? aceJson.get(ALLOW_JSON_KEY).toString() : "";
80 }
81 String role = aceJson.get(ROLE_JSON_KEY) != null ? aceJson.get(ROLE_JSON_KEY).toString() : "";
82 if (StringUtils.trimToNull(action) != null && StringUtils.trimToNull(allow) != null
83 && StringUtils.trimToNull(role) != null) {
84 AccessControlEntry ace = new AccessControlEntry(role, action, Boolean.parseBoolean(allow));
85 entries.add(ace);
86 } else {
87 throw new IllegalArgumentException(
88 String.format(
89 "One of the access control elements is missing a property. The action was '%s', allow was '%s' and the role was '%s'",
90 action, allow, role));
91 }
92 }
93 return new AccessControlList(entries);
94 }
95
96
97
98
99
100
101
102
103 public static List<JValue> serializeAclToJson(AccessControlList acl) {
104 List<JValue> entries = new ArrayList<JValue>();
105 for (AccessControlEntry ace : acl.getEntries()) {
106 entries.add(obj(
107 f(ALLOW_JSON_KEY, v(ace.isAllow())), f(ACTION_JSON_KEY, v(ace.getAction(), Jsons.BLANK)),
108 f(ROLE_JSON_KEY, v(ace.getRole(), Jsons.BLANK))));
109 }
110 return entries;
111 }
112 }