diff --git a/index.js b/index.js index 367bdba..9172c65 100644 --- a/index.js +++ b/index.js @@ -66,6 +66,10 @@ function csurf (options) { var ignoreMethod = getIgnoredMethods(ignoreMethods) return function csrf (req, res, next) { + if (verifyCsurfIsInitializedRepeatedly(req, cookie)) { + return next(new Error('csurf({cookie: true}) or csurf({cookie: {}}}) is repeatedly called with same middleware in the cooke mode, first validation will result in the invalid token')) + } + // validate the configuration against request if (!verifyConfiguration(req, sessionKey, cookie)) { return next(new Error('misconfigured csrf')) @@ -295,3 +299,24 @@ function verifyConfiguration (req, sessionKey, cookie) { return true } + +/** + * Check csurf initialization status. + * This function is only used in cookie mode. + * @param {IncomingMessage} req + * @param {Object} cookie + * @returns {boolean} csurf is initializaed repeatedly or not in cookie mode. + * @api private + */ + +function verifyCsurfIsInitializedRepeatedly (req, cookie) { + if (!cookie) { + return false + } + var _name = '@@isCsurfInitialized@@' + if (!req[_name]) { + req[_name] = true + return false + } + return true +} diff --git a/test/test.js b/test/test.js index 2e5d7b8..a27cda0 100644 --- a/test/test.js +++ b/test/test.js @@ -232,6 +232,20 @@ describe('csurf', function () { .expect(200, done) }) }) + + it('should return error when call csurf twice in middleware.', function (done) { + var app = connect() + app.use(cookieParser('keyboard cat')) + app.use(csurf({ cookie: true })) + app.use(csurf({ cookie: true })) + app.use(function (req, res) { + res.end(req.csrfToken() || 'none') + }) + + request(app) + .get('/') + .expect(500, /csurf\({cookie: true}\) or csurf\({cookie: {}}}\) is repeatedly called with same middleware in the cooke mode, first validation will result in the invalid token/, done) + }) }) describe('when an object', function () {