budibase/packages/server/src/middleware/currentapp.js

90 lines
2.6 KiB
JavaScript
Raw Normal View History

2021-06-15 20:39:40 +02:00
const { getAppId, setCookie, getCookie, clearCookie } =
require("@budibase/auth").utils
const { Cookies } = require("@budibase/auth").constants
const { getRole } = require("@budibase/auth/roles")
const { BUILTIN_ROLE_IDS } = require("@budibase/auth/roles")
const { generateUserMetadataID } = require("../db/utils")
2021-10-06 23:16:50 +02:00
const { dbExists, getTenantIDFromAppID } = require("@budibase/auth/db")
const { getTenantId } = require("@budibase/auth/tenancy")
2021-07-06 19:10:04 +02:00
const { getCachedSelf } = require("../utilities/global")
const CouchDB = require("../db")
2021-10-06 23:16:50 +02:00
const env = require("../environment")
const DEFAULT_TENANT_ID = "default"
module.exports = async (ctx, next) => {
// try to get the appID from the request
let requestAppId = getAppId(ctx)
// get app cookie if it exists
let appCookie = null
try {
appCookie = getCookie(ctx, Cookies.CurrentApp)
} catch (err) {
clearCookie(ctx, Cookies.CurrentApp)
}
if (!appCookie && !requestAppId) {
return next()
}
// check the app exists referenced in cookie
if (appCookie) {
const appId = appCookie.appId
const exists = await dbExists(CouchDB, appId)
if (!exists) {
clearCookie(ctx, Cookies.CurrentApp)
return next()
}
// if the request app ID wasn't set, update it with the cookie
requestAppId = requestAppId || appId
}
let appId,
roleId = BUILTIN_ROLE_IDS.PUBLIC
if (!ctx.user) {
// not logged in, try to set a cookie for public apps
appId = requestAppId
2021-07-06 19:10:04 +02:00
} else if (requestAppId != null) {
// Different App ID means cookie needs reset, or if the same public user has logged in
2021-07-06 19:10:04 +02:00
const globalUser = await getCachedSelf(ctx, requestAppId)
appId = requestAppId
// retrieving global user gets the right role
roleId = globalUser.roleId || BUILTIN_ROLE_IDS.BASIC
}
2021-10-06 23:16:50 +02:00
// nothing more to do
if (!appId) {
return next()
}
2021-10-06 23:16:50 +02:00
// If user and app tenant Ids do not match, 403
if (env.MULTI_TENANCY && ctx.user) {
const userTenantId = getTenantId()
const tenantId = getTenantIDFromAppID(ctx.appId) || DEFAULT_TENANT_ID
if (tenantId !== userTenantId) {
ctx.throw(403, "Cannot access application.")
}
}
ctx.appId = appId
if (roleId) {
ctx.roleId = roleId
2021-04-22 12:45:22 +02:00
const userId = ctx.user ? generateUserMetadataID(ctx.user._id) : null
ctx.user = {
...ctx.user,
// override userID with metadata one
_id: userId,
userId,
roleId,
role: await getRole(appId, roleId),
}
}
2021-07-08 01:30:55 +02:00
if (
requestAppId !== appId ||
appCookie == null ||
appCookie.appId !== requestAppId
) {
2021-07-06 19:10:04 +02:00
setCookie(ctx, { appId }, Cookies.CurrentApp)
}
return next()
}