From 62ee693310af076cefbb2e8c87cb6d5f8e42ebdd Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Mon, 12 Jul 2021 11:00:08 +0100 Subject: [PATCH] Lazily instantiated express-session middleware refs https://github.com/TryGhost/Team/issues/756 When running the tests it was possible for this middleware to be instantiated before the settings cache, resulting in an undefined 'session_secret' setting being passed. This would cause tests to fail. Tracking this down proved difficult, so the fix was made here, by instantiating the express-session middleware only once a request needs to use it, we can be confident that Ghost has completely started. --- .../services/auth/session/express-session.js | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/core/server/services/auth/session/express-session.js b/core/server/services/auth/session/express-session.js index d8361b8868..9186250597 100644 --- a/core/server/services/auth/session/express-session.js +++ b/core/server/services/auth/session/express-session.js @@ -9,25 +9,33 @@ const urlUtils = require('../../../../shared/url-utils'); const SessionStore = require('./store'); const sessionStore = new SessionStore(models.Session); -const expressSessionMiddleware = session({ - store: sessionStore, - secret: settingsCache.get('session_secret'), - resave: false, - saveUninitialized: false, - name: 'ghost-admin-api-session', - cookie: { - maxAge: constants.SIX_MONTH_MS, - httpOnly: true, - path: urlUtils.getSubdir() + '/ghost', - sameSite: 'lax', - secure: urlUtils.isSSL(config.get('url')) +let unoExpressSessionMiddleware; + +function getExpressSessionMiddleware() { + if (!unoExpressSessionMiddleware) { + unoExpressSessionMiddleware = session({ + store: sessionStore, + secret: settingsCache.get('session_secret'), + resave: false, + saveUninitialized: false, + name: 'ghost-admin-api-session', + cookie: { + maxAge: constants.SIX_MONTH_MS, + httpOnly: true, + path: urlUtils.getSubdir() + '/ghost', + sameSite: 'lax', + secure: urlUtils.isSSL(config.get('url')) + } + }); } -}); + return unoExpressSessionMiddleware; +} module.exports.getSession = async function getSession(req, res) { if (req.session) { return req.session; } + const expressSessionMiddleware = getExpressSessionMiddleware(); return new Promise((resolve, reject) => { expressSessionMiddleware(req, res, function (err) { if (err) {