added input sanitization

This commit is contained in:
Ritchie Martori
2012-03-26 17:29:01 -07:00
parent 6c27ad1f02
commit 55752ac596
2 changed files with 21 additions and 2 deletions

View File

@@ -15,6 +15,7 @@ module.exports = function (req, res, next) {
, resource = req.resource
, validation
, err
, sanitized = {}
;
// rewrite queries from references
@@ -37,7 +38,14 @@ module.exports = function (req, res, next) {
}
// if trying to write data
if((method === 'POST' || method === 'PUT') && resource && resource.properties) {
if((method === 'POST' || method === 'PUT') && req.body && resource && resource.properties) {
// sanitize data
Object.keys(resource.properties).forEach(function (key) {
sanitized[key] = req.body[key];
})
// replace input with sanitized data
req.body = req.data = sanitized;
// validate JSON
validation = revalidator.validate(req.body, resource);

View File

@@ -12,7 +12,7 @@ describe('Resource Actions', function(){
describe('POST /todos', function(){
it('should return an error when provided invalid data', function(done) {
todos.post({foo: 'bar', bat: 'baz'}, function (err, todo, req, res) {
todos.post({title: 123}, function (err, todo, req, res) {
expect(err).to.exist;
expect(err.valid).to.equal(false);
expect(err.errors).to.have.length(1);
@@ -21,6 +21,17 @@ describe('Resource Actions', function(){
})
})
it('should ignore properties outside the schema', function(done) {
todos.post({title: 'foo', bat: 'baz'}, function (err, todo, req, res) {
todos.get(function (err, todos) {
var todo = todos[0];
expect(todo.title).to.equal('foo');
expect(todo.bat).to.not.exist;
done(err);
})
})
})
it('should save the todo when valid', function(done) {
todos.post({title: 'feed the cat'}, function (err, todo) {
expect(todo._id).to.exist;