2021-04-12 19:31:58 +02:00
|
|
|
const { getAppId, setCookie, getCookie, Cookies } = require("@budibase/auth")
|
|
|
|
const { getGlobalUsers } = require("../utilities/workerRequests")
|
|
|
|
const { BUILTIN_ROLE_IDS } = require("../utilities/security/roles")
|
|
|
|
|
|
|
|
function finish(ctx, next, { appId, roleId, cookie = false }) {
|
|
|
|
if (appId) {
|
|
|
|
ctx.appId = appId
|
|
|
|
}
|
|
|
|
if (roleId) {
|
|
|
|
ctx.roleId = roleId
|
|
|
|
}
|
|
|
|
if (cookie && appId) {
|
2021-04-13 14:26:13 +02:00
|
|
|
setCookie(ctx, { appId, roleId }, Cookies.CurrentApp)
|
2021-04-12 19:31:58 +02:00
|
|
|
}
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
return finish(ctx, next, {
|
|
|
|
appId: appId,
|
|
|
|
roleId: roleId,
|
|
|
|
cookie: updateCookie,
|
|
|
|
})
|
|
|
|
}
|