From 5b79126dbf0f8ec378f8c93263d6d2c549cf5b69 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Mon, 14 Mar 2022 19:05:02 +0000 Subject: [PATCH] Fixing an issue with the public API loading for the first time in a multi-tenant environment, also fixing an issue in self host when switching between environments with different secrets. --- .../src/middleware/authenticated.js | 35 +++++++++++-------- .../worker/src/api/controllers/global/auth.js | 7 +++- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/packages/backend-core/src/middleware/authenticated.js b/packages/backend-core/src/middleware/authenticated.js index ee815ea330..ef982c799b 100644 --- a/packages/backend-core/src/middleware/authenticated.js +++ b/packages/backend-core/src/middleware/authenticated.js @@ -5,7 +5,7 @@ const { getSession, updateSessionTTL } = require("../security/sessions") const { buildMatcherRegex, matches } = require("./matchers") const env = require("../environment") const { SEPARATOR, ViewNames, queryGlobalView } = require("../../db") -const { getGlobalDB } = require("../tenancy") +const { getGlobalDB, doInTenant } = require("../tenancy") const { decrypt } = require("../security/encryption") function finalise( @@ -25,20 +25,25 @@ async function checkApiKey(apiKey, populateUser) { } const decrypted = decrypt(apiKey) const tenantId = decrypted.split(SEPARATOR)[0] - const db = getGlobalDB(tenantId) - // api key is encrypted in the database - const userId = await queryGlobalView( - ViewNames.BY_API_KEY, - { - key: apiKey, - }, - db - ) - if (userId) { - return { valid: true, user: await getUser(userId, tenantId, populateUser) } - } else { - throw "Invalid API key" - } + return doInTenant(tenantId, async () => { + const db = getGlobalDB() + // api key is encrypted in the database + const userId = await queryGlobalView( + ViewNames.BY_API_KEY, + { + key: apiKey, + }, + db + ) + if (userId) { + return { + valid: true, + user: await getUser(userId, tenantId, populateUser), + } + } else { + throw "Invalid API key" + } + }) } /** diff --git a/packages/worker/src/api/controllers/global/auth.js b/packages/worker/src/api/controllers/global/auth.js index 7b0e50c099..0f0201f5da 100644 --- a/packages/worker/src/api/controllers/global/auth.js +++ b/packages/worker/src/api/controllers/global/auth.js @@ -85,7 +85,12 @@ exports.setInitInfo = ctx => { } exports.getInitInfo = ctx => { - ctx.body = getCookie(ctx, Cookies.Init) || {} + try { + ctx.body = getCookie(ctx, Cookies.Init) || {} + } catch (err) { + clearCookie(ctx, Cookies.Init) + ctx.body = {} + } } /**