Extract token param to a middleware

This commit is contained in:
Daniel García Aubert 2017-09-22 18:49:21 +02:00
parent f7b9287c93
commit 0e8fb68794

View File

@ -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);