1
0
Fork 0
mirror of synced 2024-06-21 11:51:00 +12:00
budibase/packages/server/src/middleware/authorized.js

71 lines
2.2 KiB
JavaScript
Raw Normal View History

const {
getUserRoleHierarchy,
getRequiredResourceRole,
BUILTIN_ROLE_IDS,
} = require("@budibase/backend-core/roles")
const {
PermissionTypes,
doesHaveBasePermission,
} = require("@budibase/backend-core/permissions")
const builderMiddleware = require("./builder")
const { isWebhookEndpoint } = require("./utils")
function hasResource(ctx) {
return ctx.resourceId != null
}
2021-06-16 06:39:40 +12:00
module.exports =
(permType, permLevel = null) =>
async (ctx, next) => {
// webhooks don't need authentication, each webhook unique
// also internal requests (between services) don't need authorized
if (isWebhookEndpoint(ctx) || ctx.internal) {
2021-06-16 06:39:40 +12:00
return next()
}
2020-10-12 23:57:37 +13:00
2021-06-16 06:39:40 +12:00
if (!ctx.user) {
return ctx.throw(403, "No user info found")
}
2020-06-19 03:59:31 +12:00
2021-06-16 06:39:40 +12:00
// check general builder stuff, this middleware is a good way
// to find API endpoints which are builder focused
await builderMiddleware(ctx, permType)
2020-05-28 04:23:01 +12:00
2021-06-16 06:39:40 +12:00
const isAuthed = ctx.isAuthenticated
// builders for now have permission to do anything
let isBuilder = ctx.user && ctx.user.builder && ctx.user.builder.global
const isBuilderApi = permType === PermissionTypes.BUILDER
if (isBuilder) {
return next()
} else if (isBuilderApi && !isBuilder) {
return ctx.throw(403, "Not Authorized")
}
// need to check this first, in-case public access, don't check authed until last
const roleId = ctx.roleId || BUILTIN_ROLE_IDS.PUBLIC
const hierarchy = await getUserRoleHierarchy(ctx.appId, roleId, {
idOnly: false,
})
const permError = "User does not have permission"
let possibleRoleIds = []
if (hasResource(ctx)) {
possibleRoleIds = await getRequiredResourceRole(ctx.appId, permLevel, ctx)
}
// check if we found a role, if not fallback to base permissions
if (possibleRoleIds.length > 0) {
const found = hierarchy.find(
role => possibleRoleIds.indexOf(role._id) !== -1
)
return found ? next() : ctx.throw(403, permError)
} else if (!doesHaveBasePermission(permType, permLevel, hierarchy)) {
ctx.throw(403, permError)
2021-06-16 06:39:40 +12:00
}
2020-05-28 04:23:01 +12:00
// if they are not authed, then anything using the authorized middleware will fail
2021-06-16 06:39:40 +12:00
if (!isAuthed) {
ctx.throw(403, "Session not authenticated")
}
return next()
}