bridge-node-server/node_server/swagger_api/api_body_middleware.js
Martin Donnelly 57bd6c8e6a init
2018-06-24 21:15:03 +01:00

47 lines
1.5 KiB
JavaScript

/**
* @fileoverview Middleware to both parse the request body as JSON, and keep a raw copy of it
* for HMAC calculations in `req.bodyRaw`.
*/
const bodyParser = require('body-parser');
const iconv = require('iconv-lite');
const utils = require('../ComServe/utils.js');
module.exports = {
bridgeBodyParser
};
/**
* This mildly abuses the `verify` callback in bodyParser.json() middleware to
* store the raw body in `req.bodyRaw` so we can use it to correctly verify the HMAC.
* This is called before bodyParser has done its own decoding to string so we
* have to repeat that ourselves.
* We don't do any real verification, though the encoding handling could cause an
* exception to be thrown.
*
* @param {Object} req - the express request object
* @param {Object} res - the express response object
* @param {Object} buf - the buffer containing the raw body
* @param {string} encoding - the specified encoding
*/
function storeRawBody(req, res, buf, encoding) {
if (encoding !== null) {
req.bodyRaw = iconv.decode(buf, encoding);
}
}
/**
* Factory function to generate the middleware we need to store the raw and parsed
* bodies in the request. We mostly use the `body-parser` from Express, with
* our own function as a fake verifier to store the raw body.
* We also limit the max size of body we allow according to the setting in utils.
*/
function bridgeBodyParser() {
return bodyParser.json({
limit: utils.maxPacketSize,
verify: storeRawBody
});
}