From 956734a9b9392b5ed19c7fcfb60275ec0d4ac8ed Mon Sep 17 00:00:00 2001 From: Matthew Collier Date: Wed, 2 Jan 2019 12:40:49 -0500 Subject: [PATCH] Implement route conditional middleware. --- lib/index.js | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index 6fce1ab..2cfb8e8 100644 --- a/lib/index.js +++ b/lib/index.js @@ -190,8 +190,10 @@ function init(callback) { return callback(); } if(bedrock.config.express.useSession) { - server.use(api.middleware['express-session']( - bedrock.config.express.session)); + server.use(_routeConditionalMiddleware({ + fn: api.middleware['express-session'](bedrock.config.express.session), + routeBlackList: ['/foo'] + })); } callback(); }], @@ -353,3 +355,26 @@ function _acceptableContent(options) { res.status(415).send(); }; } + +function _routeConditionalMiddleware({fn/*, routeBlackList*/}) { + // TODO: this would be passed in and would originate in the bedrock config + const routeBlackList = new Set([ + '/consensus/continuity2017/voters/:voterId/gossip' + ]); + return function(req, res, next) { + // iterate backwards because top level routes are defined near the end + // TODO: is there some way to not have to iterate the stack on every + // call? Could the blackListed layers be stored somehow? + for(let i = server._router.stack.length - 1; i >= 0; --i) { + const layer = server._router.stack[i]; + if(!layer.route) { + continue; + } + if(routeBlackList.has(layer.route.path) && req.path.match(layer.regexp)) { + // blackList match do not execute the provided middeleware `fn` + return next(); + } + } + fn(req, res, next); + }; +}