diff --git a/ghost/session-service/lib/session-service.js b/ghost/session-service/lib/session-service.js index da1ccf117d..57bd721c49 100644 --- a/ghost/session-service/lib/session-service.js +++ b/ghost/session-service/lib/session-service.js @@ -235,13 +235,17 @@ module.exports = function createSessionService({ async function sendAuthCodeToUser(req, res) { const session = await getSession(req, res); const token = await generateAuthCodeForUser(req, res); - const user = await findUserById({id: session.user_id}); - if (!user) { + let user; + try { + user = await findUserById({id: session.user_id}); + } catch (error) { + // User session likely doesn't contain a valid user ID throw new BadRequestError({ message: 'Could not fetch user from the session.' }); } + const recipient = user.get('email'); const siteTitle = getSettingsCache('title'); const siteLogo = getBlogLogo(); diff --git a/ghost/session-service/test/SessionService.test.js b/ghost/session-service/test/SessionService.test.js index ed66b0b3b4..c61c6287e2 100644 --- a/ghost/session-service/test/SessionService.test.js +++ b/ghost/session-service/test/SessionService.test.js @@ -517,4 +517,53 @@ describe('SessionService', function () { should.equal(req.session.user_id, 'egg'); should.equal(req.session.verified, true); }); + + it('Throws if the user id is invalid', async function () { + const getSession = async (req) => { + if (req.session) { + return req.session; + } + req.session = { + user_id: 'user-123', + ip: '0.0.0.0', + user_agent: 'Fake' + }; + return req.session; + }; + + const findUserById = sinon.stub().rejects(new Error('User not found')); + + const mailer = { + send: sinon.stub().resolves() + }; + + const getSettingsCache = sinon.stub().returns('site-title'); + const getBlogLogo = sinon.stub().returns('logo.png'); + const urlUtils = { + urlFor: sinon.stub().returns('https://example.com') + }; + + const t = sinon.stub().callsFake(text => text); + + const sessionService = SessionService({ + getSession, + findUserById, + getSettingsCache, + getBlogLogo, + urlUtils, + mailer, + t, + labs: { + isSet: () => false + } + }); + + const req = Object.create(express.request); + const res = Object.create(express.response); + + await should(sessionService.sendAuthCodeToUser(req, res, {id: 'invalid'})) + .rejectedWith({ + message: 'Could not fetch user from the session.' + }); + }); });