forked from fiznool/express-mongo-sanitize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (89 loc) · 2.22 KB
/
index.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
'use strict';
const whitelist = [
"settings.profileSetupRequired",
"physicalAddress.street",
"physicalAddress.city",
"physicalAddress.state",
"physicalAddress.zipCode",
"socialMediaLink.facebook",
"socialMediaLink.instagram",
"socialMediaLink.snapchat",
"socialMediaLink.twitter",
"socialMediaLink.linkedin",
"socialMediaLink.youtube",
]
const TEST_REGEX = /^\$|\./;
const REPLACE_REGEX = /^\$|\./g;
function isPlainObject(obj) {
return typeof obj === 'object' && obj !== null;
}
function withEach(target, cb) {
(function act(obj) {
if(Array.isArray(obj)) {
obj.forEach(act);
} else if(isPlainObject(obj)) {
Object.keys(obj).forEach(function(key) {
const val = obj[key];
const resp = cb(obj, val, key);
if(resp.shouldRecurse) {
act(obj[resp.key || key]);
}
});
}
})(target);
}
function has(target) {
let hasProhibited = false;
withEach(target, function(obj, val, key) {
if(TEST_REGEX.test(key)) {
hasProhibited = true;
return { shouldRecurse: false };
} else {
return { shouldRecurse: true };
}
});
return hasProhibited;
}
function sanitize(target, options) {
options = options || {};
let replaceWith = null;
if(!(TEST_REGEX.test(options.replaceWith))) {
replaceWith = options.replaceWith;
}
withEach(target, function(obj, val, key) {
let shouldRecurse = true;
if(!inWhitelist(key) && TEST_REGEX.test(key)) {
delete obj[key];
if(replaceWith) {
key = key.replace(REPLACE_REGEX, replaceWith);
obj[key] = val;
} else {
shouldRecurse = false;
}
}
return {
shouldRecurse: shouldRecurse,
key: key
};
});
return target;
}
function middleware(options) {
return function(req, res, next) {
['body', 'params', 'headers', 'query'].forEach(function(k) {
if(req[k]) {
req[k] = sanitize(req[k], options);
}
});
next();
};
}
function inWhitelist(key) {
// DEBUG
// console.log(`[${typeof key}] key=${key}`);
// console.log(`inWhitelist = ${whitelist.includes(key)}`);
return whitelist.includes(key);
}
module.exports = middleware;
module.exports.sanitize = sanitize;
module.exports.has = has;