-
Notifications
You must be signed in to change notification settings - Fork 29
/
LTI.java
148 lines (131 loc) · 7.29 KB
/
LTI.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package models;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.System.Logger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.AbstractMap;
import java.util.Base64;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.net.ssl.HttpsURLConnection;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthValidator;
import net.oauth.SimpleOAuthValidator;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpParameters;
@Singleton
public class LTI {
@Inject private StorageConnector assignmentConn;
private static Logger logger = System.getLogger("com.horstmann.codecheck");
public boolean validate(String url, Map<String, String[]> postParams) {
final String OAUTH_KEY_PARAMETER = "oauth_consumer_key";
if (postParams == null) return false;
Set<Map.Entry<String, String>> entries = new HashSet<>();
for (Map.Entry<String, String[]> entry : postParams.entrySet())
for (String s : entry.getValue())
entries.add(new AbstractMap.SimpleEntry<>(entry.getKey(), s));
String key = com.horstmann.codecheck.Util.getParam(postParams, OAUTH_KEY_PARAMETER);
for (Map.Entry<String, String> entry : com.horstmann.codecheck.Util.getParams(url).entrySet())
entries.add(entry);
int n = url.lastIndexOf("?");
if (n >= 0) url = url.substring(0, n);
OAuthMessage oam = new OAuthMessage("POST", url, entries);
OAuthConsumer cons = new OAuthConsumer(null, key, getSharedSecret(key), null);
OAuthValidator oav = new SimpleOAuthValidator();
OAuthAccessor acc = new OAuthAccessor(cons);
try {
oav.validateMessage(oam, acc);
return true;
} catch (Exception e) {
logger.log(Logger.Level.ERROR, "Did not validate: " + e.getLocalizedMessage() + "\nurl: " + url + "\nentries: " + entries);
return false;
}
}
private String getSharedSecret(String oauthConsumerKey) {
String sharedSecret = "";
try {
sharedSecret = assignmentConn.readLTISharedSecret(oauthConsumerKey);
if (sharedSecret == null)
logger.log(Logger.Level.WARNING, "No shared secret for consumer key " + oauthConsumerKey);
} catch (IOException e) {
logger.log(Logger.Level.WARNING, "Could not read CodeCheckLTICredentials");
// Return empty string
}
return sharedSecret;
}
private static Pattern codeMajorPattern = Pattern.compile("<imsx_codeMajor>(.+)</imsx_codeMajor>");
private static Pattern descriptionPattern = Pattern.compile("(?s)<imsx_description>(.+)</imsx_description>");
public String passbackGradeToLMS(String gradePassbackURL,
String sourcedID, double score, String oauthConsumerKey)
throws URISyntaxException, IOException,
OAuthMessageSignerException, OAuthExpectationFailedException,
OAuthCommunicationException, NoSuchAlgorithmException {
String oauthSecret = getSharedSecret(oauthConsumerKey);
String xmlString1 = "<?xml version = \"1.0\" encoding = \"UTF-8\"?> <imsx_POXEnvelopeRequest xmlns = \"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\"> <imsx_POXHeader> <imsx_POXRequestHeaderInfo> <imsx_version>V1.0</imsx_version> <imsx_messageIdentifier>"
+ System.currentTimeMillis() + "</imsx_messageIdentifier> </imsx_POXRequestHeaderInfo> </imsx_POXHeader> <imsx_POXBody> <replaceResultRequest> <resultRecord> <sourcedGUID> <sourcedId>";
String xmlString2 = "</sourcedId> </sourcedGUID> <result> <resultScore> <language>en</language> <textString>";
String xmlString3 = "</textString> </resultScore> </result> </resultRecord> </replaceResultRequest> </imsx_POXBody> </imsx_POXEnvelopeRequest>";
String xml = xmlString1 + sourcedID + xmlString2 + score + xmlString3;
URL url = URI.create(gradePassbackURL).toURL();
HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
request.setRequestMethod("POST");
request.setRequestProperty("Content-Type", "application/xml");
//request.setRequestProperty("Authorization", "OAuth"); // Needed for Moodle???
byte[] xmlBytes = xml.getBytes("UTF-8");
request.setRequestProperty("Content-Length", Integer.toString(xmlBytes.length));
// https://stackoverflow.com/questions/28204736/how-can-i-send-oauth-body-hash-using-signpost
DefaultOAuthConsumer consumer = new DefaultOAuthConsumer(oauthConsumerKey, oauthSecret);
consumer.setTokenWithSecret(null, null);
MessageDigest md = MessageDigest.getInstance("SHA1");
String bodyHash = Base64.getEncoder().encodeToString(md.digest(xmlBytes));
HttpParameters params = new HttpParameters();
params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
//params.put("realm", gradePassbackURL); // http://zewaren.net/site/?q=node/123
consumer.setAdditionalParameters(params);
consumer.sign(request);
// logger.info("passbackGradeToLMS: URL {}, request {}, XML {}", url, new java.util.TreeMap<>(consumer.getRequestParameters()), xml);
// POST the xml to the grade passback url
request.setDoOutput(true);
OutputStream out = request.getOutputStream();
out.write(xmlBytes);
out.close();
// request.connect();
if (request.getResponseCode() != 200)
logger.log(Logger.Level.WARNING, "passbackGradeToLMS: Not successful" + request.getResponseCode() + " " + request.getResponseMessage());
try {
InputStream in = request.getInputStream();
String body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
Matcher matcher1 = codeMajorPattern.matcher(body);
Matcher matcher2 = descriptionPattern.matcher(body);
String message = "";
if (matcher1.find()) message += matcher1.group(1);
if (matcher2.find()) message += ": " + matcher2.group(1);
if (message.length() == 0) message = body;
if (!body.contains("<imsx_codeMajor>success</imsx_codeMajor>"))
logger.log(Logger.Level.WARNING, "passbackGradeToLMS: Not successful " + body);
return message;
} catch (Exception e) {
InputStream in = request.getErrorStream();
String body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
logger.log(Logger.Level.WARNING, "passbackGradeToLMS: Response error " + e.getMessage() + ": " + body);
return body;
}
}
}