From 49b46fd5a6f960dea066c9bfbabb334c876eb106 Mon Sep 17 00:00:00 2001 From: Brian Warner <warner@lothar.com> Date: Mon, 9 Jul 2012 17:07:10 -0700 Subject: [PATCH] wsapi cleanup: factor out checkCSRF() --- lib/wsapi.js | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/lib/wsapi.js b/lib/wsapi.js index 7cee435e2..d17083853 100644 --- a/lib/wsapi.js +++ b/lib/wsapi.js @@ -97,6 +97,26 @@ function authenticateSession(session, uid, level, duration_ms) { } } +function checkCSRF(req, resp, next) { + // only on POSTs + if (req.method === "POST") { + if (req.session === undefined || typeof req.session.csrf !== 'string') { // there must be a session + logger.warn("POST calls to /wsapi require a cookie to be sent, this user may have cookies disabled"); + return httputils.forbidden(resp, "no cookie"); + } + + // and the token must match what is sent in the post body + else if (!req.body || !req.session || !req.session.csrf || req.body.csrf != req.session.csrf) { + // if any of these things are false, then we'll block the request + var b = req.body ? req.body.csrf : "<none>"; + var s = req.session ? req.session.csrf : "<none>"; + logger.warn("CSRF validation failure, token mismatch. got:" + b + " want:" + s); + return httputils.badRequest(resp, "CSRF violation"); + } + } + next(); +} + function langContext(req) { return { lang: req.lang, @@ -207,24 +227,9 @@ exports.setup = function(options, app) { return cookieParser(req, resp, function() { bodyParser(req, resp, function() { cookieSessionMiddleware(req, resp, function() { - // only on POSTs - if (req.method === "POST") { - - if (req.session === undefined || typeof req.session.csrf !== 'string') { // there must be a session - logger.warn("POST calls to /wsapi require a cookie to be sent, this user may have cookies disabled"); - return httputils.forbidden(resp, "no cookie"); - } - - // and the token must match what is sent in the post body - else if (!req.body || !req.session || !req.session.csrf || req.body.csrf != req.session.csrf) { - // if any of these things are false, then we'll block the request - var b = req.body ? req.body.csrf : "<none>"; - var s = req.session ? req.session.csrf : "<none>"; - logger.warn("CSRF validation failure, token mismatch. got:" + b + " want:" + s); - return httputils.badRequest(resp, "CSRF violation"); - } - } - return next(); + checkCSRF(req, resp, function() { + return next(); + }); }); }); }); -- GitLab