Skip to content

Commit

Permalink
feat: Improve fetchParams
Browse files Browse the repository at this point in the history
* Add geo-info to extra options
* protect against HTTP Parameter Pollution attacks
* Add int, float type options for parameters
  • Loading branch information
tiggerk committed Mar 2, 2017
1 parent 4ea89e5 commit db94f73
Showing 1 changed file with 40 additions and 8 deletions.
48 changes: 40 additions & 8 deletions lib/fetchParams.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,21 @@ var TYPE_DELIMETER = ':'
, extraOption;

function getValue(req, keyName) {
var value;

if (req.params && req.params[keyName] !== undefined) {
return req.params[keyName];
value = req.params[keyName];
} else if (req.body && req.body[keyName] !== undefined) {
return req.body[keyName];
value = req.body[keyName];
} else if (req.query && req.query[keyName] !== undefined) {
return req.query[keyName];
} else {
return undefined;
value = req.query[keyName];
}

if (Array.isArray(value)) {
value = value[value.length - 1];
}

return value;
}

function getPath(req, keyName) {
Expand Down Expand Up @@ -117,6 +123,17 @@ function getOptionalParams(req, option_expressions) {

val = getFunc(req, key);

var typeMap = {
int: parseInt,
float: parseFloat,
number: parseFloat
};

var idx = Object.keys(typeMap).indexOf(keyInfo.type);
if (idx >= 0) {
options[key] = typeMap[keyInfo.type](val);
}

if (keyInfo.type === 'number') {
if (val !== undefined && val !== '')
options[key] = parseFloat(val);
Expand Down Expand Up @@ -178,7 +195,7 @@ function requiredParameter(req, required_expressions) {
, key
, val;

for (var i = 0, li = required_expressions.length; i <li ; i++) {
for (var i = 0, li = required_expressions.length; i < li; i++) {
var keyInfo;
try {
keyInfo = getRequiredKeyInfo(required_expressions[i]);
Expand All @@ -196,13 +213,28 @@ function requiredParameter(req, required_expressions) {
getFunc = getValue;

val = getFunc(req, key);
if (keyInfo.type === 'number') {

var typeMap = {
int: parseInt,
float: parseFloat,
number: parseFloat
};

var idx = Object.keys(typeMap).indexOf(keyInfo.type);
if (idx >= 0) {
if (isNaN(val)) {
err = new Error('The parameter value is not a number : ' + key);
err.code = 400;
break;
}
options[key] = parseFloat(val);

if (keyInfo.type == 'int' && !_.isSafeInteger(val)) {
err = new Error('The parameter value is not a integer : ' + key);
err.code = 400;
break;
}

options[key] = typeMap[keyInfo.type](val);
} else {
options[key] = val;
}
Expand Down

0 comments on commit db94f73

Please # to comment.