-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathncl-connect.js
116 lines (93 loc) · 3.02 KB
/
ncl-connect.js
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
var request = require('request'),
cheerio = require('cheerio'),
FormData = require('form-data');
exports.login = function(url, user, callback)
{
var jar = request.jar();
request.get({ uri: url, jar: jar }, function(error, response, body) {
if(error)
return callback(error || {error: 401}, null);
request.post({
url: 'https://gateway.ncl.ac.uk/idp/Authn/UserPassword',
jar: jar,
form: {
j_username: user.id,
j_password: user.pass,
_eventId: 'submit',
submit: 'LOGIN'
}
}, onGatewayResponse);
});
function onGatewayResponse(error, response, body)
{
if(error)
return callback(error || { error: 401 }, null);
request.get({ url: url, jar: jar }, function (error, response, body) {
if(error)
return callback(error || { error: 401 }, null);
var $ = cheerio.load(body);
var $form = $('form');
var action = $form.attr('action');
var response = $form.find('input[name=SAMLResponse]').attr('value');
var target = $form.find('input[name=TARGET]');
request.post({
url: action,
jar: jar,
form: {
SAMLResponse: response,
TARGET: target.length > 0 ? target.attr('value') : ''
}
}, onLoginResponse);
});
}
function onLoginResponse(error, response, body)
{
if(error)
return callback(error || { error: 401 }, null);
var cookie;
response.headers["set-cookie"].forEach(function(c) {
if(c.indexOf("shibsession") !== -1)
cookie = c;
});
request.get({ url: url, jar: jar }, function (error, response, body) {
if(error)
return callback(error || { error: 401 }, null);
var $ = cheerio.load(body);
callback(null, cookie, $);
});
}
}
exports.getPage = function(user, url, callback)
{
if(user.dev) {
var fs = require('fs');
var filename = url.split('?')[0].substring(23).replace(/\//g, '-');
var file = fs.readFileSync('testHTML/' + filename, 'utf8');
var $ = cheerio.load(file);
callback(null, $);
}
else {
if(!user.cookie)
callback({error: 401}, null);
else {
var headers = {
'Cookie': user.cookie
};
request.get({
url: url,
headers: headers
}, function (error, response, body)
{
if (!error && response.statusCode == 200)
{
var $ = cheerio.load(body);
callback(null, $);
}
else
{
callback(error || { error: 401 }, null);
}
});
}
}
}