Skip to content

Commit

Permalink
Fix JSONCookie to return undefined for non-string arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Sep 18, 2015
1 parent b1ab01d commit bb8b68c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
unreleased
==========

* Fix `JSONCookie` to return `undefined` for non-string arguments
* deps: cookie@0.1.5

1.3.5 / 2015-05-19
Expand Down
8 changes: 5 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,19 @@ function cookieParser(secret, options) {
* Parse JSON cookie string.
*
* @param {String} str
* @return {Object} Parsed object or null if not json cookie
* @return {Object} Parsed object or undefined if not json cookie
* @public
*/

function JSONCookie(str) {
if (!str || str.substr(0, 2) !== 'j:') return;
if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') {
return undefined;
}

try {
return JSON.parse(str.slice(2));
} catch (err) {
// no op
return undefined;
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/cookieParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ describe('cookieParser()', function(){
})

describe('cookieParser.JSONCookie(str)', function () {
it('should return undefined for non-string arguments', function () {
assert.strictEqual(cookieParser.JSONCookie(), undefined)
assert.strictEqual(cookieParser.JSONCookie(undefined), undefined)
assert.strictEqual(cookieParser.JSONCookie(null), undefined)
assert.strictEqual(cookieParser.JSONCookie(42), undefined)
assert.strictEqual(cookieParser.JSONCookie({}), undefined)
assert.strictEqual(cookieParser.JSONCookie([]), undefined)
assert.strictEqual(cookieParser.JSONCookie(function(){}), undefined)
})

it('should return undefined for non-JSON cookie string', function () {
assert.strictEqual(cookieParser.JSONCookie(''), undefined)
assert.strictEqual(cookieParser.JSONCookie('foo'), undefined)
Expand Down

0 comments on commit bb8b68c

Please sign in to comment.