1
0
Fork 0
mirror of synced 2024-06-30 03:50:37 +12:00
budibase/packages/server/src/middleware/currentapp.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-06-16 06:39:40 +12:00
const { getAppId, setCookie, getCookie, clearCookie } =
require("@budibase/auth").utils
const { Cookies } = require("@budibase/auth").constants
const { getRole } = require("@budibase/auth/roles")
2021-05-28 01:55:48 +12:00
const { getGlobalSelf } = require("../utilities/workerRequests")
const { BUILTIN_ROLE_IDS } = require("@budibase/auth/roles")
const { generateUserMetadataID } = require("../db/utils")
const { dbExists } = require("@budibase/auth/db")
const CouchDB = require("../db")
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()
}
// 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()
}
}
let updateCookie = false,
appId,
roleId = BUILTIN_ROLE_IDS.PUBLIC
if (!ctx.user) {
// not logged in, try to set a cookie for public apps
updateCookie = true
appId = requestAppId
} else if (
requestAppId != null &&
(appCookie == null ||
requestAppId !== appCookie.appId ||
appCookie.roleId === BUILTIN_ROLE_IDS.PUBLIC ||
!appCookie.roleId)
) {
// Different App ID means cookie needs reset, or if the same public user has logged in
const globalUser = await getGlobalSelf(ctx, requestAppId)
updateCookie = true
appId = requestAppId
// retrieving global user gets the right role
roleId = globalUser.roleId || BUILTIN_ROLE_IDS.BASIC
} else if (appCookie != null) {
appId = appCookie.appId
roleId = appCookie.roleId || BUILTIN_ROLE_IDS.BASIC
}
// nothing more to do
if (!appId) {
return next()
}
ctx.appId = appId
if (roleId) {
ctx.roleId = roleId
2021-04-22 22:45:22 +12: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),
}
}
if (updateCookie) {
setCookie(ctx, { appId, roleId }, Cookies.CurrentApp)
}
return next()
}