2021-04-12 19:31:58 +02:00
|
|
|
const { getAppId, setCookie, getCookie, Cookies } = require("@budibase/auth")
|
2021-04-13 15:35:00 +02:00
|
|
|
const { getRole } = require("../utilities/security/roles")
|
2021-04-13 16:27:47 +02:00
|
|
|
const { generateUserMetadataID } = require("../db/utils")
|
2021-04-12 19:31:58 +02:00
|
|
|
const { getGlobalUsers } = require("../utilities/workerRequests")
|
|
|
|
const { BUILTIN_ROLE_IDS } = require("../utilities/security/roles")
|
|
|
|
|
|
|
|
module.exports = async (ctx, next) => {
|
|
|
|
// try to get the appID from the request
|
|
|
|
const requestAppId = getAppId(ctx)
|
|
|
|
// get app cookie if it exists
|
|
|
|
const appCookie = getCookie(ctx, Cookies.CurrentApp)
|
|
|
|
if (!appCookie && !requestAppId) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
|
|
|
let updateCookie = false,
|
|
|
|
appId,
|
|
|
|
roleId
|
|
|
|
if (!ctx.user) {
|
|
|
|
// not logged in, try to set a cookie for public apps
|
|
|
|
updateCookie = true
|
|
|
|
appId = requestAppId
|
|
|
|
roleId = BUILTIN_ROLE_IDS.PUBLIC
|
|
|
|
} else if (
|
|
|
|
requestAppId != null &&
|
2021-04-13 14:32:09 +02:00
|
|
|
(appCookie == null || requestAppId !== appCookie.appId)
|
2021-04-12 19:31:58 +02:00
|
|
|
) {
|
|
|
|
const globalUser = await getGlobalUsers(ctx, requestAppId, ctx.user.email)
|
|
|
|
updateCookie = true
|
|
|
|
appId = requestAppId
|
|
|
|
roleId = globalUser.roles[requestAppId] || BUILTIN_ROLE_IDS.PUBLIC
|
2021-04-13 14:32:09 +02:00
|
|
|
} else if (appCookie != null) {
|
2021-04-12 19:31:58 +02:00
|
|
|
appId = appCookie.appId
|
|
|
|
roleId = appCookie.roleId || BUILTIN_ROLE_IDS.PUBLIC
|
|
|
|
}
|
2021-04-13 15:35:00 +02:00
|
|
|
if (appId) {
|
|
|
|
ctx.appId = appId
|
|
|
|
if (roleId) {
|
2021-04-13 16:27:47 +02:00
|
|
|
const userId = ctx.user
|
|
|
|
? generateUserMetadataID(ctx.user.email)
|
|
|
|
: undefined
|
2021-04-13 15:35:00 +02:00
|
|
|
ctx.roleId = roleId
|
|
|
|
ctx.user = {
|
|
|
|
...ctx.user,
|
2021-04-13 16:27:47 +02:00
|
|
|
_id: userId,
|
|
|
|
userId,
|
2021-04-13 15:35:00 +02:00
|
|
|
role: await getRole(appId, roleId),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (updateCookie && appId) {
|
|
|
|
setCookie(ctx, { appId, roleId }, Cookies.CurrentApp)
|
|
|
|
}
|
|
|
|
return next()
|
2021-04-12 19:31:58 +02:00
|
|
|
}
|