8
|
1 /**
|
|
2 * Base class for Annotator resource classes.
|
|
3 */
|
|
4 package de.mpiwg.itgroup.annotationManager.restlet;
|
|
5
|
|
6 import java.io.UnsupportedEncodingException;
|
|
7 import java.net.URLDecoder;
|
11
|
8 import java.net.URLEncoder;
|
10
|
9 import java.security.MessageDigest;
|
|
10 import java.security.NoSuchAlgorithmException;
|
8
|
11 import java.util.ArrayList;
|
|
12 import java.util.List;
|
|
13 import java.util.regex.Matcher;
|
|
14 import java.util.regex.Pattern;
|
|
15
|
14
|
16 import javax.xml.bind.DatatypeConverter;
|
|
17
|
10
|
18 import org.apache.log4j.Logger;
|
|
19 import org.joda.time.DateTime;
|
|
20 import org.joda.time.format.DateTimeFormatter;
|
|
21 import org.joda.time.format.ISODateTimeFormat;
|
8
|
22 import org.json.JSONArray;
|
|
23 import org.json.JSONException;
|
|
24 import org.json.JSONObject;
|
13
|
25 import org.restlet.data.ClientInfo;
|
8
|
26 import org.restlet.data.Form;
|
11
|
27 import org.restlet.data.Status;
|
8
|
28 import org.restlet.representation.Representation;
|
|
29 import org.restlet.resource.Options;
|
|
30 import org.restlet.resource.ServerResource;
|
11
|
31 import org.restlet.security.User;
|
8
|
32
|
|
33 import de.mpiwg.itgroup.annotationManager.Constants.NS;
|
|
34 import de.mpiwg.itgroup.annotationManager.RDFHandling.Convert;
|
|
35
|
|
36 /**
|
|
37 * Base class for Annotator resource classes.
|
|
38 *
|
|
39 * @author dwinter, casties
|
|
40 *
|
|
41 */
|
|
42 public abstract class AnnotatorResourceImpl extends ServerResource {
|
|
43
|
10
|
44 protected Logger logger = Logger.getRootLogger();
|
|
45
|
8
|
46 protected String getAllowedMethodsForHeader() {
|
|
47 return "OPTIONS,GET,POST";
|
|
48 }
|
|
49
|
|
50 /**
|
13
|
51 * returns a hex String of a SHA256 digest of text.
|
|
52 *
|
|
53 * @param text
|
|
54 * @return
|
|
55 */
|
|
56 public String getSha256Digest(String text) {
|
|
57 String digest = null;
|
|
58 try {
|
|
59 MessageDigest md = MessageDigest.getInstance("SHA-256");
|
|
60 md.update(text.getBytes("UTF-8"));
|
|
61 byte[] dg = md.digest();
|
14
|
62 digest = DatatypeConverter.printHexBinary(dg);
|
13
|
63 } catch (NoSuchAlgorithmException e) {
|
|
64 e.printStackTrace();
|
|
65 } catch (UnsupportedEncodingException e) {
|
|
66 e.printStackTrace();
|
|
67 }
|
|
68 return digest;
|
|
69 }
|
|
70
|
|
71 /**
|
8
|
72 * Handle options request to allow CORS for AJAX.
|
|
73 *
|
|
74 * @param entity
|
|
75 */
|
|
76 @Options
|
|
77 public void doOptions(Representation entity) {
|
13
|
78 logger.debug("AnnotatorResourceImpl doOptions!");
|
|
79 setCorsHeaders();
|
|
80 }
|
|
81
|
|
82 /**
|
|
83 * set headers to allow CORS for AJAX.
|
|
84 */
|
|
85 protected void setCorsHeaders() {
|
10
|
86 Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
|
8
|
87 if (responseHeaders == null) {
|
|
88 responseHeaders = new Form();
|
10
|
89 getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
|
8
|
90 }
|
10
|
91 responseHeaders.add("Access-Control-Allow-Methods", getAllowedMethodsForHeader());
|
8
|
92 // echo back Origin and Request-Headers
|
10
|
93 Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
|
8
|
94 String origin = requestHeaders.getFirstValue("Origin", true);
|
|
95 if (origin == null) {
|
|
96 responseHeaders.add("Access-Control-Allow-Origin", "*");
|
|
97 } else {
|
|
98 responseHeaders.add("Access-Control-Allow-Origin", origin);
|
|
99 }
|
10
|
100 String allowHeaders = requestHeaders.getFirstValue("Access-Control-Request-Headers", true);
|
8
|
101 if (allowHeaders != null) {
|
|
102 responseHeaders.add("Access-Control-Allow-Headers", allowHeaders);
|
|
103 }
|
|
104 responseHeaders.add("Access-Control-Allow-Credentials", "true");
|
|
105 responseHeaders.add("Access-Control-Max-Age", "60");
|
|
106 }
|
|
107
|
|
108 /**
|
10
|
109 * returns if authentication information from headers is valid.
|
|
110 *
|
|
111 * @param entity
|
|
112 * @return
|
|
113 */
|
|
114 public boolean isAuthenticated(Representation entity) {
|
13
|
115 return (checkAuthToken(entity) != null);
|
|
116 }
|
|
117
|
|
118 /**
|
|
119 * checks Annotator Auth plugin authentication information from headers. returns userId if successful.
|
|
120 *
|
|
121 * @param entity
|
|
122 * @return
|
|
123 */
|
|
124 public String checkAuthToken(Representation entity) {
|
10
|
125 Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
|
|
126 String consumerKey = requestHeaders.getFirstValue("x-annotator-consumer-key", true);
|
|
127 if (consumerKey == null) {
|
13
|
128 return null;
|
10
|
129 }
|
13
|
130 // get stored consumer secret for key
|
10
|
131 RestServer restServer = (RestServer) getApplication();
|
|
132 String consumerSecret = restServer.getConsumerSecret(consumerKey);
|
|
133 logger.debug("requested consumer key=" + consumerKey + " secret=" + consumerSecret);
|
|
134 if (consumerSecret == null) {
|
13
|
135 return null;
|
10
|
136 }
|
|
137 String userId = requestHeaders.getFirstValue("x-annotator-user-id", true);
|
|
138 String issueTime = requestHeaders.getFirstValue("x-annotator-auth-token-issue-time", true);
|
|
139 if (userId == null || issueTime == null) {
|
13
|
140 return null;
|
10
|
141 }
|
|
142 // compute hashed token based on the values we know
|
|
143 // computed_token = hashlib.sha256(consumer.secret + user_id + issue_time).hexdigest()
|
13
|
144 String computedToken = getSha256Digest(consumerSecret + userId + issueTime);
|
10
|
145 // compare to the token we got
|
|
146 String authToken = requestHeaders.getFirstValue("x-annotator-auth-token", true);
|
|
147 logger.debug(String.format("got: authToken=%s consumerSecret=%s userId=%s issueTime=%s", authToken, consumerSecret, userId,
|
|
148 issueTime));
|
|
149 if (!computedToken.equals(authToken)) {
|
13
|
150 return null;
|
10
|
151 }
|
|
152 // check token lifetime
|
|
153 // validity = iso8601.parse_date(issue_time)
|
|
154 // expiry = validity + datetime.timedelta(seconds=consumer.ttl)
|
|
155 int tokenTtl = 86400;
|
|
156 DateTime tokenValidity = null;
|
|
157 DateTime tokenExpiry = null;
|
|
158 try {
|
|
159 DateTimeFormatter parser = ISODateTimeFormat.dateTime();
|
|
160 tokenValidity = parser.parseDateTime(issueTime);
|
|
161 String tokenTtlString = requestHeaders.getFirstValue("x-annotator-auth-token-ttl", true);
|
|
162 tokenTtl = Integer.parseInt(tokenTtlString);
|
|
163 tokenExpiry = tokenValidity.plusSeconds(tokenTtl);
|
|
164 } catch (NumberFormatException e) {
|
|
165 e.printStackTrace();
|
|
166 }
|
|
167 if (tokenValidity == null || tokenValidity.isAfterNow() || tokenExpiry.isBeforeNow()) {
|
13
|
168 return null;
|
10
|
169 }
|
|
170 // must be ok then
|
13
|
171 return userId;
|
10
|
172 }
|
|
173
|
|
174 /**
|
11
|
175 * creates Annotator-JSON from an Annotation object.
|
8
|
176 *
|
|
177 * @param annot
|
|
178 * @return
|
|
179 */
|
13
|
180 public JSONObject createAnnotatorJson(Convert.Annotation annot) {
|
|
181 boolean makeUserObject = true;
|
8
|
182 JSONObject jo = new JSONObject();
|
|
183 try {
|
|
184 jo.put("text", annot.text);
|
|
185 jo.put("uri", annot.url);
|
|
186
|
13
|
187 if (makeUserObject) {
|
|
188 // create user object
|
|
189 JSONObject userObject = new JSONObject();
|
|
190 // save creator as uri
|
|
191 userObject.put("uri", annot.creator);
|
|
192 // make short user id
|
|
193 String userID = annot.creator;
|
|
194 if (userID.startsWith(NS.MPIWG_PERSONS)) {
|
|
195 userID = userID.replace(NS.MPIWG_PERSONS, ""); // entferne NAMESPACE
|
|
196 }
|
|
197 // save as id
|
|
198 userObject.put("id", userID);
|
|
199 // get full name
|
|
200 RestServer restServer = (RestServer) getApplication();
|
|
201 String userName = restServer.getUserNameFromLdap(userID);
|
|
202 userObject.put("name", userName);
|
|
203 // save user object
|
|
204 jo.put("user", userObject);
|
|
205 } else {
|
|
206 // save user as string
|
|
207 jo.put("user", annot.creator);
|
8
|
208 }
|
|
209
|
13
|
210 List<String> xpointers = new ArrayList<String>();
|
8
|
211 if (annot.xpointers == null || annot.xpointers.size() == 0)
|
13
|
212 xpointers.add(annot.xpointer);
|
8
|
213 else {
|
|
214 for (String xpointerString : annot.xpointers) {
|
13
|
215 xpointers.add(xpointerString);
|
8
|
216 }
|
|
217 }
|
13
|
218 jo.put("ranges", transformToRanges(xpointers));
|
8
|
219 jo.put("id", annot.annotationUri);
|
|
220 return jo;
|
|
221 } catch (JSONException e) {
|
|
222 // TODO Auto-generated catch block
|
|
223 e.printStackTrace();
|
|
224 return null;
|
|
225 }
|
|
226 }
|
|
227
|
|
228 private JSONArray transformToRanges(List<String> xpointers) {
|
|
229
|
|
230 JSONArray ja = new JSONArray();
|
|
231
|
|
232 Pattern rg = Pattern
|
|
233 .compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
|
10
|
234 Pattern rg1 = Pattern.compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
|
8
|
235
|
|
236 try {
|
|
237 for (String xpointer : xpointers) {
|
|
238 String decoded = URLDecoder.decode(xpointer, "utf-8");
|
|
239 Matcher m = rg.matcher(decoded);
|
|
240
|
|
241 if (m.find()) {
|
|
242 {
|
|
243 JSONObject jo = new JSONObject();
|
|
244 jo.put("start", m.group(1));
|
|
245 jo.put("startOffset", m.group(2));
|
|
246 jo.put("end", m.group(3));
|
|
247 jo.put("endOffset", m.group(4));
|
|
248 ja.put(jo);
|
|
249 }
|
|
250 }
|
|
251 m = rg1.matcher(xpointer);
|
|
252 if (m.find()) {
|
|
253 JSONObject jo = new JSONObject();
|
|
254 jo.put("start", m.group(1));
|
|
255 jo.put("startOffset", m.group(2));
|
|
256
|
|
257 ja.put(jo);
|
|
258 }
|
|
259 }
|
|
260 } catch (JSONException e) {
|
|
261 // TODO Auto-generated catch block
|
|
262 e.printStackTrace();
|
|
263 } catch (UnsupportedEncodingException e) {
|
|
264 // TODO Auto-generated catch block
|
|
265 e.printStackTrace();
|
|
266 }
|
|
267
|
|
268 return ja;
|
|
269 }
|
|
270
|
11
|
271 /**
|
13
|
272 * creates an Annotation object with data from JSON.
|
|
273 *
|
|
274 * uses the specification from the annotator project: {@link https://github.com/okfn/annotator/wiki/Annotation-format}
|
11
|
275 *
|
13
|
276 * The username will be transformed to an URI if not given already as URI, if not it will set to the MPIWG namespace defined in
|
|
277 * de.mpiwg.itgroup.annotationManager.Constants.NS
|
11
|
278 *
|
|
279 * @param jo
|
|
280 * @return
|
|
281 * @throws JSONException
|
|
282 */
|
|
283 public Convert.Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException {
|
|
284 String url = jo.getString("uri");
|
|
285 String text = jo.getString("text");
|
13
|
286
|
|
287 // check authentication
|
|
288 String authUser = checkAuthToken(entity);
|
|
289 if (authUser == null) {
|
|
290 // try http auth
|
|
291 User httpUser = getHttpAuthUser(entity);
|
|
292 if (httpUser == null) {
|
11
|
293 setStatus(Status.CLIENT_ERROR_FORBIDDEN);
|
|
294 return null;
|
|
295 }
|
13
|
296 authUser = httpUser.getIdentifier();
|
11
|
297 }
|
13
|
298 // username not required, if no username given authuser will be used
|
|
299 String username = null;
|
|
300 String userUri = null;
|
|
301 if (jo.has("user")) {
|
|
302 if (jo.get("user") instanceof String) {
|
|
303 // user is just a String
|
|
304 username = jo.getString("user");
|
|
305 // TODO: what if username and authUser are different?
|
|
306 } else {
|
|
307 // user is an object
|
|
308 JSONObject user = jo.getJSONObject("user");
|
|
309 if (user.has("id")) {
|
|
310 username = user.getString("id");
|
|
311 }
|
|
312 if (user.has("uri")) {
|
|
313 userUri = user.getString("uri");
|
|
314 }
|
|
315 }
|
|
316 }
|
|
317 if (username == null) {
|
|
318 username = authUser;
|
|
319 }
|
|
320
|
|
321 // create xpointer
|
11
|
322 String xpointer;
|
|
323 if (jo.has("ranges")) {
|
|
324 JSONObject ranges = jo.getJSONArray("ranges").getJSONObject(0);
|
|
325 String start = ranges.getString("start");
|
|
326 String end = ranges.getString("end");
|
|
327 String startOffset = ranges.getString("startOffset");
|
|
328 String endOffset = ranges.getString("endOffset");
|
13
|
329
|
11
|
330 try {
|
|
331 xpointer = url
|
|
332 + "#"
|
|
333 + URLEncoder.encode(String.format(
|
|
334 "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))",
|
|
335 start, startOffset, end, endOffset), "utf-8");
|
|
336 } catch (UnsupportedEncodingException e) {
|
|
337 e.printStackTrace();
|
|
338 setStatus(Status.SERVER_ERROR_INTERNAL);
|
|
339 return null;
|
|
340 }
|
|
341 } else {
|
|
342 xpointer = url;
|
|
343 }
|
13
|
344
|
11
|
345 // username should be a URI, if not it will set to the MPIWG namespace defined in
|
|
346 // de.mpiwg.itgroup.annotationManager.Constants.NS
|
13
|
347 if (userUri == null) {
|
|
348 if (username.startsWith("http")) {
|
|
349 userUri = username;
|
|
350 } else {
|
|
351 userUri = NS.MPIWG_PERSONS + username;
|
|
352 }
|
|
353 }
|
|
354 return new Convert.Annotation(xpointer, userUri, null, text, null);
|
|
355 }
|
|
356
|
|
357 /**
|
|
358 * returns the logged in User.
|
|
359 *
|
|
360 * @param entity
|
|
361 * @return
|
|
362 */
|
|
363 protected User getHttpAuthUser(Representation entity) {
|
|
364 RestServer restServer = (RestServer) getApplication();
|
|
365 if (!restServer.authenticate(getRequest(), getResponse())) {
|
|
366 // Not authenticated
|
|
367 return null;
|
|
368 }
|
|
369
|
|
370 ClientInfo ci = getRequest().getClientInfo();
|
|
371 logger.debug(ci);
|
|
372 return getRequest().getClientInfo().getUser();
|
|
373
|
11
|
374 }
|
|
375
|
8
|
376 }
|