From 0f0e8b3462cec11dfc4661ba1d06283f35098533 Mon Sep 17 00:00:00 2001 From: Taekyoon Date: Thu, 10 Nov 2016 22:25:06 -0800 Subject: [PATCH] feat: validate account.tokens.type Added validating account.tokens.type in account.js that might cause invalidate form of tokens --- lib/account.js | 8 ++++++++ lib/utils/errors.js | 6 ++++++ test/unit/account/tokens-test.js | 26 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 test/unit/account/tokens-test.js diff --git a/lib/account.js b/lib/account.js index 3eeab57..5d59358 100644 --- a/lib/account.js +++ b/lib/account.js @@ -1,12 +1,20 @@ module.exports = account var addTokenToUserDoc = require('./utils/add-token-to-user-doc') +var errors = require('./utils/errors') var findUserDoc = require('./utils/find-user-doc-by-username-or-id-or-token') function account (setupPromise, state, findAccountOptions) { return { tokens: { add: function (tokenOptions) { + var validPattern = /^([a-z])([a-z0-9\-_])*$/ + + if (typeof tokenOptions.type !== 'string' || + !validPattern.test(tokenOptions.type)) { + return Promise.reject(errors.TOKEN_TYPE_INVALID) + } + return setupPromise .then(function () { diff --git a/lib/utils/errors.js b/lib/utils/errors.js index 885768f..4257b55 100644 --- a/lib/utils/errors.js +++ b/lib/utils/errors.js @@ -37,3 +37,9 @@ module.exports.USERNAME_EMPTY = hoodieError({ message: 'username must be set', status: 400 }) + +module.exports.TOKEN_TYPE_INVALID = hoodieError({ + name: 'Bad Request', + message: 'Type must be a string of lowercase characters, numbers, -, or _, and must begin with a character.', + status: 400 +}) diff --git a/test/unit/account/tokens-test.js b/test/unit/account/tokens-test.js new file mode 100644 index 0000000..e0e5761 --- /dev/null +++ b/test/unit/account/tokens-test.js @@ -0,0 +1,26 @@ +var test = require('tap').test + +var account = require('../../../lib/account') + +test('add', function (group) { + group.test('with invalid symbols', function (t) { + t.plan(3) + + account().tokens.add({ + id: 'secrettoken', + type: 'abc$123' + }) + + .then(function () { + t.fail('tokens.add should reject') + }) + + .catch(function (error) { + t.is(error.name, 'Bad Request') + t.is(error.status, 400) + t.is(error.message, 'Type must be a string of lowercase characters, numbers, -, or _, and must begin with a character.') + }) + }) + + group.end() +})