Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIO 7964: add resource based select component validation #1714

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "formio",
"version": "4.0.0-dev.2",
"version": "4.0.0-bb.dev.13",
brendanbond marked this conversation as resolved.
Show resolved Hide resolved
"description": "The formio server application.",
"license": "OSL-3.0",
"main": "index.js",
Expand Down
51 changes: 2 additions & 49 deletions src/middleware/setFilterQueryTypes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
'use strict';

const _ = require('lodash');
const util = require('../util/util');
const moment = require('moment');
const Utils = require('../util/util');

/**
* Middleware function to coerce filter queries for a submission Index
Expand All @@ -25,52 +23,7 @@ module.exports = function(router) {
return next(err);
}

const prefix = 'data.';
const prefixLength = prefix.length;
_.assign(req.query, _(req.query)
.omit('limit', 'skip', 'select', 'sort', 'populate')
.mapValues((value, name) => {
// Skip filters not looking at component data
if (!name.startsWith(prefix)) {
return value;
}

// Get the filter object.
const filter = _.zipObject(['name', 'selector'], name.split('__'));
// Convert to component key
const key = util.getFormComponentKey(filter.name).substring(prefixLength);
const component = util.getComponent(currentForm.components, key);
// Coerce these queries to proper data type
if (component) {
switch (component.type) {
case 'number':
case 'currency':
return Number(value);
case 'checkbox':
return value !== 'false';
case 'datetime': {
const date = moment.utc(value, ['YYYY-MM-DD', 'YYYY-MM', 'YYYY', 'x', moment.ISO_8601], true);

if (date.isValid()) {
return date.toDate();
}
return;
}
case 'select': {
if (Number(value) || value === "0") {
return Number(value);
}
}
}
}
if (!component && ['true', 'false'].includes(value)) {
return value !== 'false';
}
return value;
})
.value()
);

Utils.coerceQueryTypes(req.query, currentForm, 'data.');
next();
});
};
Expand Down
4 changes: 3 additions & 1 deletion src/middleware/submissionHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,10 +229,12 @@ module.exports = (router, resourceName, resourceId) => {
hook.alter('validateSubmissionForm', req.currentForm, req.body, async form => { // eslint-disable-line max-statements
// Get the submission model.
const submissionModel = req.submissionModel || router.formio.resources.submission.model;
const submissionResource = router.formio.resources.submission;
const cache = router.formio.cache;
const tokenModel = router.formio.mongoose.models.token;

// Validate the request.
const validator = new Validator(req, submissionModel, tokenModel, hook);
const validator = new Validator(req, submissionModel, submissionResource, cache, tokenModel, hook);
await validator.validate(req.body, (err, data, visibleComponents) => {
if (req.noValidate) {
return done();
Expand Down
76 changes: 72 additions & 4 deletions src/resources/Validator.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,47 @@
'use strict';
const _ = require('lodash');
const {ObjectId} = require('mongodb');
const {
ProcessTargets,
process,
interpolateErrors,
escapeRegExCharacters
} = require('@formio/core');
const {evaluateProcess} = require('@formio/vm');
const util = require('../util/util');
const Utils = require('../util/util');
const fetch = require('@formio/node-fetch-http-proxy');
const debug = {
validator: require('debug')('formio:validator'),
error: require('debug')('formio:error')
};

// Promisify cache load form.
function loadFormById(cache, req, formId) {
return new Promise((resolve, reject) => {
cache.loadForm(req, null, formId, (err, resource) => {
if (err) {
return reject(err);
}
return resolve(resource);
});
});
}

// Promisify submission model find.
function submissionQueryExists(submissionModel, query) {
return new Promise((resolve, reject) => {
submissionModel.find(query, (err, result) => {
if (err) {
return reject(err);
}
if (result.length === 0 || !result) {
return resolve(false);
}
return resolve(true);
});
});
}

/**
* @TODO: Isomorphic validation system.
*
Expand All @@ -22,9 +50,9 @@ const debug = {
* @constructor
*/
class Validator {
constructor(req, submissionModel, tokenModel, hook) {
constructor(req, submissionModel, submissionResource, cache, tokenModel, hook) {
const tokens = {};
const token = util.getRequestValue(req, 'x-jwt-token');
const token = Utils.getRequestValue(req, 'x-jwt-token');
if (token) {
tokens['x-jwt-token'] = token;
}
Expand All @@ -40,6 +68,8 @@ class Validator {

this.req = req;
this.submissionModel = submissionModel;
this.submissionResource = submissionResource;
this.cache = cache;
this.tokenModel = tokenModel;
this.form = req.currentForm;
this.project = req.currentProject;
Expand Down Expand Up @@ -177,6 +207,43 @@ class Validator {
});
}

async validateResourceSelectValue(context, value) {
const {component} = context;
if (!component.data.resource) {
throw new Error('Did not receive resource ID for resource select validation');
}
const resource = await loadFormById(this.cache, this.req, component.data.resource);
if (!resource) {
throw new Error('Resource not found');
}
// Curiously, if a value property is not provided, the renderer will submit the entire object.
// Even if the user selects "Entire Object" as the value property, the renderer will submit only
// the data object. If we don't have a value property we can fallback to the _id, if we don't
// have an _id we can fall back to the data object OR the data object plus the "submit" property
// (which seems to sometimes be stripped and sometimes not).
const valueQuery = component.valueProperty
? {[component.valueProperty]: value}
: value._id
? {_id: value._id}
: {$or: [{data: value}, {data: {...value, submit: true}}]};
const filterQueries = component.filter.split(',').reduce((acc, filter) => {
const [key, value] = filter.split('=');
return {...acc, [key]: value};
}, {});
Utils.coerceQueryTypes(filterQueries, resource, 'data.');

const query = {
form: new ObjectId(component.data.resource),
deleted: null,
state: 'submitted',
$and:[
valueQuery,
this.submissionResource.getFindQuery({query: filterQueries})
]
};
return submissionQueryExists(this.submissionModel, query);
}

/**
* Validate a submission for a form.
*
Expand Down Expand Up @@ -216,7 +283,8 @@ class Validator {
isUnique: async (context, value) => {
return this.isUnique(context, submission, value);
},
validateCaptcha: this.validateCaptcha
validateCaptcha: this.validateCaptcha.bind(this),
validateResourceSelectValue: this.validateResourceSelectValue.bind(this)
}
}
};
Expand Down
45 changes: 45 additions & 0 deletions src/util/util.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const mongoose = require('mongoose');
const moment = require('moment');
const ObjectID = require('mongodb').ObjectId;
const _ = require('lodash');
const nodeUrl = require('url');
Expand Down Expand Up @@ -827,6 +828,50 @@ const Utils = {
// Skips hook execution in case of no hook by provided name found
// Pass as the last argument to formio.hook.alter() function
skipHookIfNotExists: () => _.noop(),

coerceQueryTypes(query, currentForm, prefix = 'data.') {
_.assign(query, _(query)
.omit('limit', 'skip', 'select', 'sort', 'populate')
.mapValues((value, name) => {
// Skip filters not looking at component data
if (!name.startsWith(prefix)) {
return value;
}

// Get the filter object.
const filter = _.zipObject(['name', 'selector'], name.split('__'));
// Convert to component key
const key = Utils.getFormComponentKey(filter.name).substring(prefix.length);
const component = Utils.getComponent(currentForm.components, key);
// Coerce these queries to proper data type
if (component) {
switch (component.type) {
case 'number':
case 'currency':
return Number(value);
case 'checkbox':
return value !== 'false';
case 'datetime': {
const date = moment.utc(value, ['YYYY-MM-DD', 'YYYY-MM', 'YYYY', 'x', moment.ISO_8601], true);

if (date.isValid()) {
return date.toDate();
}
return;
}
case 'select': {
if (Number(value) || value === "0") {
return Number(value);
}
}
}
}
if (!component && ['true', 'false'].includes(value)) {
return value !== 'false';
}
return value;
}).value());
}
};

module.exports = Utils;