From 939768eec0193b6dc907ae490cd863547fab0035 Mon Sep 17 00:00:00 2001 From: Nick O'Leary Date: Sat, 28 Jan 2017 14:44:47 +0000 Subject: [PATCH] Cache auth details to save needlessly recalculating hashes --- red.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/red.js b/red.js index 8969f2e4c..2cea58be2 100755 --- a/red.js +++ b/red.js @@ -196,6 +196,7 @@ try { function basicAuthMiddleware(user,pass) { var basicAuth = require('basic-auth'); var checkPassword; + var localCachedPassword; if (pass.length == "32") { // Assume its a legacy md5 password checkPassword = function(p) { @@ -207,12 +208,26 @@ function basicAuthMiddleware(user,pass) { } } + var checkPasswordAndCache = function(p) { + // For BasicAuth routes we know the password cannot change without + // a restart of Node-RED. This means we can cache the provided crypted + // version to save recalculating each time. + if (localCachedPassword === p) { + return true; + } + var result = checkPassword(p); + if (result) { + localCachedPassword = p; + } + return result; + } + return function(req,res,next) { if (req.method === 'OPTIONS') { return next(); } var requestUser = basicAuth(req); - if (!requestUser || requestUser.name !== user || !checkPassword(requestUser.pass)) { + if (!requestUser || requestUser.name !== user || !checkPasswordAndCache(requestUser.pass)) { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); return res.sendStatus(401); }