2018-08-01 17:11:08 -04:00
|
|
|
const sanitizer = require('sanitizer');
|
2018-07-28 16:49:54 -04:00
|
|
|
|
2018-08-01 17:11:08 -04:00
|
|
|
// Verifies a single property is well formed
|
|
|
|
const verifyProp = (prop, expected) => new Promise((resolve, reject) => {
|
2018-08-01 13:07:52 -04:00
|
|
|
if (!expected.optional && !prop)
|
|
|
|
return reject({code: 400, message: expected.name + ' not specified.'});
|
|
|
|
|
|
|
|
if (prop && expected.type && typeof prop !== expected.type)
|
|
|
|
return reject({code: 400, message: expected.name + ' malformed.'});
|
2018-07-28 16:49:54 -04:00
|
|
|
|
2018-08-01 13:07:52 -04:00
|
|
|
if (prop && expected.instance && !(prop instanceof expected.instance))
|
|
|
|
return reject({code: 400, message: expected.name + ' malformed.'});
|
2018-07-28 16:49:54 -04:00
|
|
|
|
2018-08-01 13:07:52 -04:00
|
|
|
if (prop && expected.maxLength && prop.length > expected.maxLength)
|
2018-08-01 17:11:08 -04:00
|
|
|
return reject({code: 400, message: expected.name + ' too long.'});
|
2018-07-28 16:49:54 -04:00
|
|
|
|
2018-08-01 17:11:08 -04:00
|
|
|
if (prop && expected.sanitize && sanitizer.sanitize(prop) !== prop)
|
|
|
|
return reject({code: 400, message: expected.name + ' contains invalid characters.'});
|
2018-08-01 12:34:15 -04:00
|
|
|
|
2018-08-01 13:07:52 -04:00
|
|
|
if (prop && expected.restrict && prop.replace(expected.restrict, '') !== prop)
|
2018-08-01 17:11:08 -04:00
|
|
|
return reject({code: 400, message: expected.name + ' contains invalid characters.'});
|
2018-08-01 12:34:15 -04:00
|
|
|
|
2018-08-01 13:07:52 -04:00
|
|
|
resolve();
|
|
|
|
});
|
2018-08-01 12:34:15 -04:00
|
|
|
|
2018-08-01 13:07:52 -04:00
|
|
|
// Verifies the entire request body is well formed
|
|
|
|
// expectedProps follows the format:
|
|
|
|
// [{name: 'myList', instance: 'Array'}, {name: 'myVar', type: 'string', optional: true}, etc.]
|
2018-08-01 17:11:08 -04:00
|
|
|
const verifyBody = (body, expectedProps) =>
|
|
|
|
Promise.all(expectedProps.map(expected => verifyProp(body[expected.name], expected)));
|
|
|
|
|
|
|
|
const bodyVerifier = expectedProps =>
|
2018-08-01 13:07:52 -04:00
|
|
|
(req, res, next) => {
|
2018-08-01 17:11:08 -04:00
|
|
|
verifyBody(req.body, expectedProps)
|
2018-08-01 13:07:52 -04:00
|
|
|
.then(() => next())
|
|
|
|
.catch(err => res.status(err.code).json({message: err.message}));
|
2018-07-28 16:49:54 -04:00
|
|
|
};
|
|
|
|
|
2018-08-01 17:11:08 -04:00
|
|
|
exports.verifyBody = verifyBody;
|
|
|
|
exports.bodyVerifier = bodyVerifier;
|