forked from Brightspace/superagent-d2l-session-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperagent-d2l-session-auth.js
72 lines (57 loc) · 1.49 KB
/
superagent-d2l-session-auth.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
'use strict';
var url = require('url'),
xsrf = require('frau-superagent-xsrf-token');
function noop() {}
function isRelative/*ly safe*/(url) {
return url.hostname === null;
}
function endsWith(haystack, needle) {
var expectedPosition = haystack.length - needle.length;
var lastIndex = haystack.indexOf(needle, expectedPosition);
var result = lastIndex !== -1 && lastIndex === expectedPosition;
return result;
}
function isBrightspaceApi(url) {
return url.protocol === 'https:'
&& (url.hostname === 'api.brightspace.com'
|| endsWith(url.hostname, '.api.brightspace.com')
);
}
function isTrustedHost(url, trustedHost) {
return typeof trustedHost === 'string'
&& url.host === trustedHost.toLowerCase();
}
function isTrusted(parsed, trustedHost) {
return isBrightspaceApi(parsed)
|| isTrustedHost(parsed, trustedHost);
}
module.exports = function(getJwt, opts) {
opts = opts || {};
return function(req) {
req = req.use(xsrf);
var end = req.end;
req.end = function(cb) {
function finish() {
req.end = end;
req.end(cb);
}
var parsed = url.parse(req.url);
if (isRelative(parsed) || !isTrusted(parsed, opts.trustedHost)) {
finish();
return this;
}
getJwt(opts.scope)
.then(function(token) {
req.set('Authorization', 'Bearer ' + token);
})
.catch(noop)
.then(function() {
// Run this async in another turn
// So we don't catch errors with our Promise
setTimeout(finish);
});
return this;
};
return req;
};
};