@dwp/govuk-casa
Version:
A framework for building GOVUK Collect-And-Submit-Applications
55 lines • 2.99 kB
JavaScript
;
// Sanitise the fields submitted from a form
// - Coerce each field to its correct type
// - Remove an extraneous fields that are not know to the application
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const field_js_1 = __importDefault(require("../lib/field.js"));
const JourneyContext_js_1 = __importDefault(require("../lib/JourneyContext.js"));
exports.default = ({ waypoint, fields = [] }) => {
// Add some common, transient fields to ensure they survive beyond this sanitisation process
fields.push((0, field_js_1.default)("_csrf", { persist: false }).processor((value) => String(value)));
fields.push((0, field_js_1.default)("contextid", { persist: false }).processor((value) => String(value)));
fields.push((0, field_js_1.default)("edit", { persist: false }).processor((value) => String(value)));
fields.push((0, field_js_1.default)("editorigin", { persist: false }).processor((value) => String(value)));
// Middleware
return [
(req, res, next) => {
// First, prune all undefined, or unknown fields from `req.body` (i.e.
// those that do not have an entry in `fields`)
// EsLint disabled as `fields`, `i` & `name` are only controlled by dev
/* eslint-disable security/detect-object-injection */
const prunedBody = Object.create(null);
for (let i = 0, l = fields.length; i < l; i++) {
if (Object.hasOwn(req.body, fields[i].name) &&
req.body[fields[i].name] !== undefined) {
prunedBody[fields[i].name] = req.body[fields[i].name];
}
}
/* eslint-enable security/detect-object-injection */
const journeyContext = JourneyContext_js_1.default.fromContext(req.casa.journeyContext, req);
journeyContext.setDataForPage(waypoint, prunedBody);
// Second, prune any fields that do not pass the validation conditional,
// and process those that do.
const sanitisedBody = Object.create(null);
for (let i = 0, l = fields.length; i < l; i++) {
const field = fields[i]; /* eslint-disable-line security/detect-object-injection */
const fieldValue = field.getValue(prunedBody);
if (fieldValue !== undefined &&
field.testConditions({
fieldValue,
waypoint,
journeyContext,
})) {
field.putValue(sanitisedBody, field.applyProcessors(fieldValue));
}
}
// Finally, write the sanitised body back to the request object
req.body = sanitisedBody;
next();
},
];
};
//# sourceMappingURL=sanitise-fields.js.map