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-12 19:31:58 +02:00
|
|
|
const { getGlobalUsers } = require("../utilities/workerRequests")
|
|
|
|
const { BUILTIN_ROLE_IDS } = require("../utilities/security/roles")
|
2021-04-20 18:17:44 +02:00
|
|
|
const {
|
|
|
|
getGlobalIDFromUserMetadataID,
|
|
|
|
generateUserMetadataID,
|
|
|
|
} = require("../db/utils")
|
2021-04-12 19:31:58 +02:00
|
|
|
|
|
|
|
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,
|
2021-04-13 19:12:35 +02:00
|
|
|
roleId = BUILTIN_ROLE_IDS.PUBLIC
|
2021-04-12 19:31:58 +02:00
|
|
|
if (!ctx.user) {
|
|
|
|
// not logged in, try to set a cookie for public apps
|
|
|
|
updateCookie = true
|
|
|
|
appId = requestAppId
|
|
|
|
} else if (
|
|
|
|
requestAppId != null &&
|
2021-04-13 17:56:45 +02:00
|
|
|
(appCookie == null ||
|
|
|
|
requestAppId !== appCookie.appId ||
|
|
|
|
appCookie.roleId === BUILTIN_ROLE_IDS.PUBLIC)
|
2021-04-12 19:31:58 +02:00
|
|
|
) {
|
2021-04-13 17:56:45 +02:00
|
|
|
// Different App ID means cookie needs reset, or if the same public user has logged in
|
2021-04-20 18:17:44 +02:00
|
|
|
const globalId = getGlobalIDFromUserMetadataID(ctx.user.userId)
|
|
|
|
const globalUser = await getGlobalUsers(ctx, requestAppId, globalId)
|
2021-04-12 19:31:58 +02:00
|
|
|
updateCookie = true
|
|
|
|
appId = requestAppId
|
2021-04-13 19:12:35 +02:00
|
|
|
if (globalUser.roles && globalUser.roles[requestAppId]) {
|
|
|
|
roleId = globalUser.roles[requestAppId]
|
|
|
|
}
|
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-20 18:17:44 +02:00
|
|
|
// nothing more to do
|
|
|
|
if (!appId) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.appId = appId
|
|
|
|
if (roleId) {
|
|
|
|
ctx.roleId = roleId
|
|
|
|
const userId = ctx.user ? generateUserMetadataID(ctx.user.userId) : null
|
|
|
|
ctx.user = {
|
|
|
|
...ctx.user,
|
|
|
|
// override userID with metadata one
|
|
|
|
_id: userId,
|
|
|
|
userId,
|
|
|
|
role: await getRole(appId, roleId),
|
2021-04-13 15:35:00 +02:00
|
|
|
}
|
|
|
|
}
|
2021-04-20 18:17:44 +02:00
|
|
|
if (updateCookie) {
|
2021-04-13 15:35:00 +02:00
|
|
|
setCookie(ctx, { appId, roleId }, Cookies.CurrentApp)
|
|
|
|
}
|
|
|
|
return next()
|
2021-04-12 19:31:58 +02:00
|
|
|
}
|