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

66 lines
1.8 KiB
JavaScript
Raw Normal View History

const { getUserPermissions } = require("@budibase/auth/roles")
const {
PermissionTypes,
doesHaveResourcePermission,
doesHaveBasePermission,
} = require("@budibase/auth/permissions")
const builderMiddleware = require("./builder")
function hasResource(ctx) {
return ctx.resourceId != null
}
const WEBHOOK_ENDPOINTS = new RegExp(
["webhooks/trigger", "webhooks/schema"].join("|")
)
2020-10-12 23:57:37 +13:00
2021-06-16 06:39:40 +12:00
module.exports =
(permType, permLevel = null) =>
async (ctx, next) => {
// webhooks don't need authentication, each webhook unique
if (WEBHOOK_ENDPOINTS.test(ctx.request.url)) {
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
const { basePermissions, permissions } = await getUserPermissions(
ctx.appId,
ctx.roleId
)
2021-06-16 06:39:40 +12:00
// builders for now have permission to do anything
// TODO: in future should consider separating permissions with an require("@budibase/auth").isClient check
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")
}
2021-06-16 06:39:40 +12:00
if (
hasResource(ctx) &&
doesHaveResourcePermission(permissions, permLevel, ctx)
) {
return next()
}
2020-05-28 04:23:01 +12:00
2021-06-16 06:39:40 +12:00
if (!isAuthed) {
ctx.throw(403, "Session not authenticated")
}
if (!doesHaveBasePermission(permType, permLevel, basePermissions)) {
ctx.throw(403, "User does not have permission")
}
return next()
}