This repository has been archived by the owner on Sep 16, 2019. It is now read-only.
/
access-control.js
80 lines (72 loc) · 1.92 KB
/
access-control.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
var yaml = require('js-yaml');
fs = require('fs');
// Parse the YAML config file
try {
var config = yaml.safeLoad(fs.readFileSync('./config.yaml', 'utf8'));
// Log out config settings
if(config && config.origins) {
console.log('Origin whitelisting enabled for ' + config.origins.join(', '));
}
else {
console.log('Origin whitelisting is disabled.');
}
if(config && config.tables) {
console.log('Table whitelisting enabled for ' + config.tables.join(', '));
}
else {
console.log('Table whitelisting is disabled.');
}
} catch (e) {
if (e.code === 'ENOENT') {
console.error('No config file was found. Origin and table whitelisting disabled.');
}
else {
console.error(e);
}
}
var checkOrigin = function(req, res, next) {
if(config && config.origins) {
// Verify origin and set appropriate access-control header
var allowed = config.origins.indexOf(req.header('Origin')) !== -1;
if(allowed) {
res.set('Access-Control-Allow-Origin', req.header('Origin'));
next();
}
else {
var msg = 'Rejected a request from a non-whitelisted origin: ' + req.header('Origin');
console.error(msg);
res.json(msg, 403);
}
}
else {
// No origin whitelisting is enabled
res.set('Access-Control-Allow-Origin', req.header('Origin'));
next();
}
};
var checkTable = function(req, res, next) {
if(config && config.tables) {
// Verify the table is whitelisted and reject the request if it isn't
var allowed = false;
config.tables.every(function(el) {
if(req.url.indexOf(el) !== -1) {
allowed = true;
return false;
}
else return true;
});
if(allowed) {
next();
}
else {
console.error('Rejected a request for a non-whitelisted table.');
res.json('You are trying to query a table that has not been whitelisted in FusionTables-proxy.', 403);
}
}
else {
// No table whitelisting is enabled
next();
}
}
module.exports.checkTable = checkTable;
module.exports.checkOrigin = checkOrigin;