-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
69 lines (53 loc) · 2.06 KB
/
app.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
var url = require('url');
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var htmlToAssertion = require('./html-to-assertion');
var app = express();
var PORT = process.env.PORT || 3000;
var ORIGIN = process.env.ORIGIN || 'http://localhost:' + PORT;
var ISSUER_NAME = process.env.ISSUER_NAME || 'Badge Microformat Bridge';
var ISSUER_ORG = process.env.ISSUER_ORG || '%n (via %d)';
app.use(express.static(__dirname + '/static'));
app.get('/assertion', function(req, res, next) {
var fullURL = req.param('url') || '';
var info = url.parse(fullURL);
var makeAssertion = function(body, issuerName, origin) {
var dom = cheerio.load(body);
try {
var result = htmlToAssertion.findUnique(dom, fullURL);
} catch (e) {
return res.type("text")
.send("unexpected exception parsing microformat: " + e);
}
var assertion = result.assertion;
if (result.errors.length)
return res.send({errors: result.errors}, 502);
assertion.badge.issuer.org = ISSUER_ORG
.replace('%n', assertion.badge.issuer.name)
.replace('%o', assertion.badge.issuer.origin)
.replace('%d', url.parse(assertion.badge.issuer.origin).host);
assertion.badge.issuer.name = issuerName;
assertion.badge.issuer.origin = origin;
return res.send(assertion);
};
if (!/^https?:/.test(info.protocol))
return res.type('text').send('invalid URL', 400);
if (req.param('testHtml'))
return makeAssertion(req.param('testHtml'), 'TESTING MODE', '');
request({
url: fullURL,
timeout: 5000,
}, function(err, proxiedRes, body) {
if (err) return next(err);
if (proxiedRes.statusCode != 200)
return res.type('text').send('gateway response is not 200', 502);
if (!(/^text\/html/.test(proxiedRes.headers['content-type']) &&
typeof(body) == 'string'))
return res.type('text').send('gateway response is not html', 502);
return makeAssertion(body, ISSUER_NAME, ORIGIN);
});
});
app.listen(PORT, function() {
console.log("Listening on port " + PORT + ".");
});