diff --git a/sanitiser/_private.js b/sanitiser/_private.js new file mode 100644 index 00000000..f419abdd --- /dev/null +++ b/sanitiser/_private.js @@ -0,0 +1,31 @@ +var isObject = require('is-object'); +var isTruthy = require('./_truthy'); + +// validate inputs, convert types and apply defaults +function sanitize( req, default_value ){ + + req.clean = req.clean || {}; + var params= req.query; + + if (default_value === undefined) { + default_value = true; + } + + default_value = !!default_value; + + // ensure the input params are a valid object + if( !isObject( params ) ){ + params = {}; + } + + if (params.private === undefined) { + req.clean.private = default_value; + } else { + req.clean.private = isTruthy(params.private); + } + + return {'error':false}; + +} + +module.exports = sanitize; diff --git a/test/unit/run.js b/test/unit/run.js index 03960674..7b512faf 100644 --- a/test/unit/run.js +++ b/test/unit/run.js @@ -9,6 +9,7 @@ var tests = [ require('./service/mget'), require('./service/search'), require('./sanitiser/_details'), + require('./sanitiser/_private'), require('./sanitiser/_source'), require('./sanitiser/_truthy'), require('./sanitiser/search'), diff --git a/test/unit/sanitiser/_private.js b/test/unit/sanitiser/_private.js new file mode 100644 index 00000000..8cebf566 --- /dev/null +++ b/test/unit/sanitiser/_private.js @@ -0,0 +1,53 @@ +var sanitize = require('../../../sanitiser/_private'); + +module.exports.tests = {}; + +module.exports.tests.sanitize_private = function(test, common) { + var invalid_values = [null, -1, 123, NaN, 'abc']; + invalid_values.forEach(function(privateValue) { + test('invalid private param ' + privateValue, function(t) { + var req = {query: { private: privateValue }}; + sanitize(req); + t.equal(req.clean.private, false, 'default private set (to false)'); + t.end(); + }); + }); + + var valid_values = ['true', true, 1, '1', 'yes', 'y']; + valid_values.forEach(function(privateValue) { + test('valid private param ' + privateValue, function(t) { + var req = {query: { private: privateValue }}; + sanitize(req); + t.equal(req.clean.private, true, 'private set to true'); + t.end(); + }); + }); + + var valid_false_values = ['false', false, 0, '0', 'no', 'n']; + valid_false_values.forEach(function(privateValue) { + test('test setting false explicitly ' + privateValue, function(t) { + var req = {query: { private: privateValue }}; + sanitize(req); + t.equal(req.clean.private, false, 'private set to false'); + t.end(); + }); + }); + + test('test default behavior', function(t) { + var req = {query: {}}; + sanitize(req); + t.equal(req.clean.private, true, 'private set to true'); + t.end(); + }); +}; + +module.exports.all = function (tape, common) { + + function test(name, testFunction) { + return tape('SANTIZE _private ' + name, testFunction); + } + + for( var testCase in module.exports.tests ){ + module.exports.tests[testCase](test, common); + } +};