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.
This commit is contained in:
Fabien O'Carroll 2021-07-12 11:00:08 +01:00 committed by Fabien 'egg' O'Carroll
parent 5ea8e9b926
commit 62ee693310

View File

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