diff --git a/README.md b/README.md index b8ecd7b..a103de5 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Create a new cookie parser middleware function using the given `secret` and - `options` an object that is passed to `cookie.parse` as the second option. See [cookie](https://www.npmjs.org/package/cookie) for more information. - `decode` a function to decode the value of the cookie + - `allowedCookie` an array of allowed cookie name to parse The middleware will parse the `Cookie` header on the request and expose the cookie data as the property `req.cookies` and, if a `secret` was provided, as diff --git a/index.js b/index.js index dd6d479..d782eef 100644 --- a/index.js +++ b/index.js @@ -52,6 +52,22 @@ function cookieParser (secret, options) { req.cookies = Object.create(null) req.signedCookies = Object.create(null) + if( cookies && options && options.allowedCookie ){ + var cookiesList = cookies.split(';'); + cookies = ''; + var found = 0; + for (var cookieItem of cookiesList) { + var cookieParts = cookieItem.trim().split('='); + if (options.allowedCookie.includes(cookieParts[0])) { + cookies += cookieParts[0] + '=' + cookieParts[1] + ';'; + found++; + } + if (found === options.allowedCookie.length) { + break; + } + } + } + // no cookies if (!cookies) { return next() diff --git a/test/cookieParser.js b/test/cookieParser.js index 6031823..fa91411 100644 --- a/test/cookieParser.js +++ b/test/cookieParser.js @@ -283,8 +283,25 @@ describe('cookieParser.signedCookies(obj, secret)', function () { }) }) -function createServer (secret) { - var _parser = cookieParser(secret) +describe('cookieParser with allowedCookie', function () { + describe('when no cookies are sent', function () { + it('should default req.cookies to {}', function (done) { + request(createServer('keyboard cat', { allowedCookie: ['foo'] })) + .get('/') + .expect(200, '{}', done) + }) + + it('should req.cookies to allowedCookie', function (done) { + request(createServer('keyboard cat', { allowedCookie: ['foo', 'baz'] })) + .get('/') + .set('Cookie', 'foo=xxx; bar=yyy; baz=zzz;') + .expect(200, '{"foo":"xxx","baz":"zzz"}', done) + }) + }) +}) + +function createServer (secret, options) { + var _parser = cookieParser(secret, options) return http.createServer(function (req, res) { _parser(req, res, function (err) { if (err) {