From 0e8fb687944a4197aa31f4d5bd578b0273e95529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa=20Aubert?= Date: Fri, 22 Sep 2017 18:49:21 +0200 Subject: [PATCH] Extract token param to a middleware --- lib/cartodb/middleware/prepare-context.js | 72 ++++++++++++++--------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/lib/cartodb/middleware/prepare-context.js b/lib/cartodb/middleware/prepare-context.js index f48d4047..345efe7f 100644 --- a/lib/cartodb/middleware/prepare-context.js +++ b/lib/cartodb/middleware/prepare-context.js @@ -36,39 +36,53 @@ module.exports = function prepareContextMiddleware (authApi, pgConnection) { next(); }, - function prepareContext (req, res, next) { + function parseTokenParam (req, res, next) { + if (!req.params.token) { + return next(); + } + var user = req.context.user; - if ( req.params.token ) { - // Token might match the following patterns: - // - {user}@{tpl_id}@{token}:{cache_buster} - var tksplit = req.params.token.split(':'); - req.params.token = tksplit[0]; - if ( tksplit.length > 1 ) { - req.params.cache_buster= tksplit[1]; - } - tksplit = req.params.token.split('@'); - if ( tksplit.length > 1 ) { - req.params.signer = tksplit.shift(); - if ( ! req.params.signer ) { - req.params.signer = user; - } - else if ( req.params.signer !== user ) { - var err = new Error( - 'Cannot use map signature of user "' + req.params.signer + '" on db of user "' + user + '"' - ); - err.http_status = 403; - req.profiler.done('req2params'); - next(err); - return; - } - if ( tksplit.length > 1 ) { - /*var template_hash = */tksplit.shift(); // unused - } - req.params.token = tksplit.shift(); - } + // Token might match the following patterns: + // - {user}@{tpl_id}@{token}:{cache_buster} + var tksplit = req.params.token.split(':'); + + req.params.token = tksplit[0]; + + if ( tksplit.length > 1 ) { + req.params.cache_buster= tksplit[1]; } + tksplit = req.params.token.split('@'); + + if ( tksplit.length > 1 ) { + req.params.signer = tksplit.shift(); + + if ( ! req.params.signer ) { + req.params.signer = user; + } else if ( req.params.signer !== user ) { + var err = new Error( + `Cannot use map signature of user "${req.params.signer}" on db of user "${user}"` + ); + err.http_status = 403; + req.profiler.done('req2params'); + + return next(err); + } + + // skip template hash + if (tksplit.length > 1) { + tksplit.shift(); + } + + req.params.token = tksplit.shift(); + } + + next(); + }, + function prepareContext (req, res, next) { + var user = req.context.user; + // bring all query values onto req.params object _.extend(req.params, req.query);