This repository has been archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
89 lines (79 loc) · 2.3 KB
/
utils.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
'use strict';
const cors = require('cors');
const debug = require('debug')('auth-saml:utils');
const url = require('url');
const fs = require('fs');
const path = require('path');
const utils = function () {};
const _validCorsHosts = {};
utils.storeRedirectUriForCors = function (uri) {
debug('storeRedirectUriForCors() ' + uri);
try {
const parsedUri = url.parse(uri);
const host = parsedUri.protocol + '//' + parsedUri.host;
_validCorsHosts[host] = true;
debug(_validCorsHosts);
} catch (ex) {
console.error(ex);
console.error(ex.stack);
console.error('storeRedirectUriForCors() - Invalid URI: ' + uri);
}
}
function isCorsHostValid(host) {
debug('isCorsHostValid(): ' + host);
if (_validCorsHosts[host]) {
debug('Yes, ' + host + ' is valid.');
return true;
}
debug('*** ' + host + ' is not a valid CORS origin.');
return false;
}
const _allowOptions = {
origin: true,
credentials: true,
allowedHeaders: [
'Accept',
'Accept-Encoding',
'Connection',
'User-Agent',
'Content-Type',
'Cookie',
'Host',
'Origin',
'Referer'
]
};
const _denyOptions = {
origin: false
};
utils.cors = function () {
const optionsDelegate = (req, callback) => {
const origin = req.header('Origin');
debug('in CORS options delegate. req.headers = ');
debug(req.headers);
if (isCorsHostValid(origin))
callback(null, _allowOptions); // Mirror origin, it's okay
else
callback(null, _denyOptions);
};
return cors(optionsDelegate);
};
utils._packageVersion = null;
utils.getVersion = function () {
if (!utils._packageVersion) {
const packageFile = path.join(__dirname, 'package.json');
if (fs.existsSync(packageFile)) {
try {
const packageInfo = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
if (packageInfo.version)
utils._packageVersion = packageInfo.version;
} catch (ex) {
console.error(ex);
}
}
if (!utils._packageVersion) // something went wrong
utils._packageVersion = "0.0.0";
}
return utils._packageVersion;
};
module.exports = utils;