From 3d003fca728951115ef2a1bbbef2233a3279e0ba Mon Sep 17 00:00:00 2001 From: Jan Oberhauser Date: Mon, 14 Sep 2020 19:58:21 +0200 Subject: [PATCH] :zap: Improve speed of basic-auth with hashed password --- packages/cli/src/Server.ts | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/Server.ts b/packages/cli/src/Server.ts index d09855bcd8..82682345a3 100644 --- a/packages/cli/src/Server.ts +++ b/packages/cli/src/Server.ts @@ -20,7 +20,7 @@ import { RequestOptions } from 'oauth-1.0a'; import * as csrf from 'csrf'; import * as requestPromise from 'request-promise-native'; import { createHmac } from 'crypto'; -import { compareSync } from 'bcrypt'; +import { compare } from 'bcrypt'; import { ActiveExecutions, @@ -189,7 +189,9 @@ class App { const basicAuthHashEnabled = await GenericHelpers.getConfigValue('security.basicAuth.hash') as boolean; - this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { + let validPassword: null | string = null; + + this.app.use(async (req: express.Request, res: express.Response, next: express.NextFunction) => { if (req.url.match(authIgnoreRegex)) { return next(); } @@ -201,12 +203,27 @@ class App { return ResponseHelper.basicAuthAuthorizationError(res, realm, 'Authorization is required!'); } - if (basicAuthData.name !== basicAuthUser || (!basicAuthHashEnabled && basicAuthData.pass !== basicAuthPassword) || (basicAuthHashEnabled && compareSync(basicAuthData.pass, basicAuthPassword) === false)) { - // Provided authentication data is wrong - return ResponseHelper.basicAuthAuthorizationError(res, realm, 'Authorization data is wrong!'); + if (basicAuthData.name === basicAuthUser) { + if (basicAuthHashEnabled === true) { + if (validPassword === null && await compare(basicAuthData.pass, basicAuthPassword)) { + // Password is valid so save for future requests + validPassword = basicAuthData.pass; + } + + if (validPassword === basicAuthData.pass && validPassword !== null) { + // Provided hash is correct + return next(); + } + } else { + if (basicAuthData.pass === basicAuthPassword) { + // Provided password is correct + return next(); + } + } } - next(); + // Provided authentication data is wrong + return ResponseHelper.basicAuthAuthorizationError(res, realm, 'Authorization data is wrong!'); }); }