diff --git a/lib/wsapi.js b/lib/wsapi.js index 7cee435e2afba35e628923bb3a1c2583447eca40..d1708385354624123f10c89f254efee576f1287a 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(); + }); }); }); });