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);
|
15
|
147 logger.debug(String.format("got: authToken=%s consumerSecret=%s userId=%s issueTime=%s computedToken=%s",
|
|
148 authToken, consumerSecret, userId, issueTime, computedToken));
|
|
149 if (!computedToken.equalsIgnoreCase(authToken)) {
|
|
150 logger.warn("authToken differ!");
|
13
|
151 return null;
|
10
|
152 }
|
|
153 // check token lifetime
|
|
154 // validity = iso8601.parse_date(issue_time)
|
|
155 // expiry = validity + datetime.timedelta(seconds=consumer.ttl)
|
|
156 int tokenTtl = 86400;
|
|
157 DateTime tokenValidity = null;
|
|
158 DateTime tokenExpiry = null;
|
|
159 try {
|
|
160 DateTimeFormatter parser = ISODateTimeFormat.dateTime();
|
|
161 tokenValidity = parser.parseDateTime(issueTime);
|
|
162 String tokenTtlString = requestHeaders.getFirstValue("x-annotator-auth-token-ttl", true);
|
|
163 tokenTtl = Integer.parseInt(tokenTtlString);
|
|
164 tokenExpiry = tokenValidity.plusSeconds(tokenTtl);
|
|
165 } catch (NumberFormatException e) {
|
|
166 e.printStackTrace();
|
|
167 }
|
15
|
168 if (tokenValidity == null || tokenValidity.isAfterNow() || tokenExpiry == null || tokenExpiry.isBeforeNow()) {
|
|
169 logger.warn(String.format("authToken invalid! tokenValidity=%s tokenExpiry=%s now=%s", tokenValidity, tokenExpiry, DateTime.now()));
|
|
170 // we dont care about validity right now
|
|
171 //return null;
|
10
|
172 }
|
|
173 // must be ok then
|
15
|
174 logger.debug("auth OK! user="+userId);
|
13
|
175 return userId;
|
10
|
176 }
|
|
177
|
|
178 /**
|
11
|
179 * creates Annotator-JSON from an Annotation object.
|
8
|
180 *
|
|
181 * @param annot
|
|
182 * @return
|
|
183 */
|
13
|
184 public JSONObject createAnnotatorJson(Convert.Annotation annot) {
|
|
185 boolean makeUserObject = true;
|
8
|
186 JSONObject jo = new JSONObject();
|
|
187 try {
|
|
188 jo.put("text", annot.text);
|
|
189 jo.put("uri", annot.url);
|
|
190
|
13
|
191 if (makeUserObject) {
|
|
192 // create user object
|
|
193 JSONObject userObject = new JSONObject();
|
|
194 // save creator as uri
|
|
195 userObject.put("uri", annot.creator);
|
|
196 // make short user id
|
|
197 String userID = annot.creator;
|
|
198 if (userID.startsWith(NS.MPIWG_PERSONS)) {
|
|
199 userID = userID.replace(NS.MPIWG_PERSONS, ""); // entferne NAMESPACE
|
|
200 }
|
|
201 // save as id
|
|
202 userObject.put("id", userID);
|
|
203 // get full name
|
|
204 RestServer restServer = (RestServer) getApplication();
|
|
205 String userName = restServer.getUserNameFromLdap(userID);
|
|
206 userObject.put("name", userName);
|
|
207 // save user object
|
|
208 jo.put("user", userObject);
|
|
209 } else {
|
|
210 // save user as string
|
|
211 jo.put("user", annot.creator);
|
8
|
212 }
|
|
213
|
13
|
214 List<String> xpointers = new ArrayList<String>();
|
8
|
215 if (annot.xpointers == null || annot.xpointers.size() == 0)
|
13
|
216 xpointers.add(annot.xpointer);
|
8
|
217 else {
|
|
218 for (String xpointerString : annot.xpointers) {
|
13
|
219 xpointers.add(xpointerString);
|
8
|
220 }
|
|
221 }
|
13
|
222 jo.put("ranges", transformToRanges(xpointers));
|
8
|
223 jo.put("id", annot.annotationUri);
|
|
224 return jo;
|
|
225 } catch (JSONException e) {
|
|
226 // TODO Auto-generated catch block
|
|
227 e.printStackTrace();
|
|
228 return null;
|
|
229 }
|
|
230 }
|
|
231
|
|
232 private JSONArray transformToRanges(List<String> xpointers) {
|
|
233
|
|
234 JSONArray ja = new JSONArray();
|
|
235
|
|
236 Pattern rg = Pattern
|
|
237 .compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
|
10
|
238 Pattern rg1 = Pattern.compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
|
8
|
239
|
|
240 try {
|
|
241 for (String xpointer : xpointers) {
|
|
242 String decoded = URLDecoder.decode(xpointer, "utf-8");
|
|
243 Matcher m = rg.matcher(decoded);
|
|
244
|
|
245 if (m.find()) {
|
|
246 {
|
|
247 JSONObject jo = new JSONObject();
|
|
248 jo.put("start", m.group(1));
|
|
249 jo.put("startOffset", m.group(2));
|
|
250 jo.put("end", m.group(3));
|
|
251 jo.put("endOffset", m.group(4));
|
|
252 ja.put(jo);
|
|
253 }
|
|
254 }
|
|
255 m = rg1.matcher(xpointer);
|
|
256 if (m.find()) {
|
|
257 JSONObject jo = new JSONObject();
|
|
258 jo.put("start", m.group(1));
|
|
259 jo.put("startOffset", m.group(2));
|
|
260
|
|
261 ja.put(jo);
|
|
262 }
|
|
263 }
|
|
264 } catch (JSONException e) {
|
|
265 // TODO Auto-generated catch block
|
|
266 e.printStackTrace();
|
|
267 } catch (UnsupportedEncodingException e) {
|
|
268 // TODO Auto-generated catch block
|
|
269 e.printStackTrace();
|
|
270 }
|
|
271
|
|
272 return ja;
|
|
273 }
|
|
274
|
11
|
275 /**
|
13
|
276 * creates an Annotation object with data from JSON.
|
|
277 *
|
|
278 * uses the specification from the annotator project: {@link https://github.com/okfn/annotator/wiki/Annotation-format}
|
11
|
279 *
|
13
|
280 * 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
|
|
281 * de.mpiwg.itgroup.annotationManager.Constants.NS
|
11
|
282 *
|
|
283 * @param jo
|
|
284 * @return
|
|
285 * @throws JSONException
|
|
286 */
|
|
287 public Convert.Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException {
|
|
288 String url = jo.getString("uri");
|
|
289 String text = jo.getString("text");
|
13
|
290
|
|
291 // check authentication
|
|
292 String authUser = checkAuthToken(entity);
|
|
293 if (authUser == null) {
|
|
294 // try http auth
|
|
295 User httpUser = getHttpAuthUser(entity);
|
|
296 if (httpUser == null) {
|
11
|
297 setStatus(Status.CLIENT_ERROR_FORBIDDEN);
|
|
298 return null;
|
|
299 }
|
13
|
300 authUser = httpUser.getIdentifier();
|
11
|
301 }
|
13
|
302 // username not required, if no username given authuser will be used
|
|
303 String username = null;
|
|
304 String userUri = null;
|
|
305 if (jo.has("user")) {
|
|
306 if (jo.get("user") instanceof String) {
|
|
307 // user is just a String
|
|
308 username = jo.getString("user");
|
|
309 // TODO: what if username and authUser are different?
|
|
310 } else {
|
|
311 // user is an object
|
|
312 JSONObject user = jo.getJSONObject("user");
|
|
313 if (user.has("id")) {
|
|
314 username = user.getString("id");
|
|
315 }
|
|
316 if (user.has("uri")) {
|
|
317 userUri = user.getString("uri");
|
|
318 }
|
|
319 }
|
|
320 }
|
|
321 if (username == null) {
|
|
322 username = authUser;
|
|
323 }
|
|
324
|
|
325 // create xpointer
|
11
|
326 String xpointer;
|
|
327 if (jo.has("ranges")) {
|
|
328 JSONObject ranges = jo.getJSONArray("ranges").getJSONObject(0);
|
|
329 String start = ranges.getString("start");
|
|
330 String end = ranges.getString("end");
|
|
331 String startOffset = ranges.getString("startOffset");
|
|
332 String endOffset = ranges.getString("endOffset");
|
13
|
333
|
11
|
334 try {
|
|
335 xpointer = url
|
|
336 + "#"
|
|
337 + URLEncoder.encode(String.format(
|
|
338 "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))",
|
|
339 start, startOffset, end, endOffset), "utf-8");
|
|
340 } catch (UnsupportedEncodingException e) {
|
|
341 e.printStackTrace();
|
|
342 setStatus(Status.SERVER_ERROR_INTERNAL);
|
|
343 return null;
|
|
344 }
|
|
345 } else {
|
|
346 xpointer = url;
|
|
347 }
|
13
|
348
|
11
|
349 // username should be a URI, if not it will set to the MPIWG namespace defined in
|
|
350 // de.mpiwg.itgroup.annotationManager.Constants.NS
|
13
|
351 if (userUri == null) {
|
|
352 if (username.startsWith("http")) {
|
|
353 userUri = username;
|
|
354 } else {
|
|
355 userUri = NS.MPIWG_PERSONS + username;
|
|
356 }
|
|
357 }
|
|
358 return new Convert.Annotation(xpointer, userUri, null, text, null);
|
|
359 }
|
|
360
|
|
361 /**
|
|
362 * returns the logged in User.
|
|
363 *
|
|
364 * @param entity
|
|
365 * @return
|
|
366 */
|
|
367 protected User getHttpAuthUser(Representation entity) {
|
|
368 RestServer restServer = (RestServer) getApplication();
|
|
369 if (!restServer.authenticate(getRequest(), getResponse())) {
|
|
370 // Not authenticated
|
|
371 return null;
|
|
372 }
|
|
373
|
|
374 ClientInfo ci = getRequest().getClientInfo();
|
|
375 logger.debug(ci);
|
|
376 return getRequest().getClientInfo().getUser();
|
|
377
|
11
|
378 }
|
|
379
|
8
|
380 }
|