|
|
|
@ -4,6 +4,8 @@ const { getUser } = require("../cache/user") |
|
|
|
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") |
|
|
|
|
|
|
|
function finalise( |
|
|
|
ctx, |
|
|
|
@ -16,6 +18,26 @@ function finalise( |
|
|
|
ctx.version = version |
|
|
|
} |
|
|
|
|
|
|
|
async function checkApiKey(apiKey, populateUser) { |
|
|
|
if (apiKey === env.INTERNAL_API_KEY) { |
|
|
|
return { valid: true } |
|
|
|
} |
|
|
|
const tenantId = apiKey.split(SEPARATOR)[0] |
|
|
|
const db = getGlobalDB(tenantId) |
|
|
|
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" |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* This middleware is tenancy aware, so that it does not depend on other middlewares being used. |
|
|
|
* The tenancy modules should not be used here and it should be assumed that the tenancy context |
|
|
|
@ -79,9 +101,19 @@ module.exports = ( |
|
|
|
const apiKey = ctx.request.headers[Headers.API_KEY] |
|
|
|
const tenantId = ctx.request.headers[Headers.TENANT_ID] |
|
|
|
// this is an internal request, no user made it
|
|
|
|
if (!authenticated && apiKey && apiKey === env.INTERNAL_API_KEY) { |
|
|
|
authenticated = true |
|
|
|
internal = true |
|
|
|
if (!authenticated && apiKey) { |
|
|
|
const populateUser = opts.populateUser ? opts.populateUser(ctx) : null |
|
|
|
const { valid, user: foundUser } = await checkApiKey( |
|
|
|
apiKey, |
|
|
|
populateUser |
|
|
|
) |
|
|
|
if (valid && foundUser) { |
|
|
|
authenticated = true |
|
|
|
user = foundUser |
|
|
|
} else if (valid) { |
|
|
|
authenticated = true |
|
|
|
internal = true |
|
|
|
} |
|
|
|
} |
|
|
|
if (!user && tenantId) { |
|
|
|
user = { tenantId } |
|
|
|
|