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