2021-05-14 16:43:41 +02:00
|
|
|
const { getUserPermissions } = require("@budibase/auth/roles")
|
2020-11-12 18:06:55 +01:00
|
|
|
const {
|
|
|
|
PermissionTypes,
|
2021-02-08 18:52:22 +01:00
|
|
|
doesHaveResourcePermission,
|
|
|
|
doesHaveBasePermission,
|
2021-05-14 16:43:41 +02:00
|
|
|
} = require("@budibase/auth/permissions")
|
2021-05-21 14:07:10 +02:00
|
|
|
const builderMiddleware = require("./builder")
|
2021-11-03 15:08:47 +01:00
|
|
|
const { isWebhookEndpoint } = require("./utils")
|
2020-11-11 18:34:15 +01:00
|
|
|
|
2021-02-08 18:52:22 +01:00
|
|
|
function hasResource(ctx) {
|
|
|
|
return ctx.resourceId != null
|
|
|
|
}
|
|
|
|
|
2021-06-15 20:39:40 +02:00
|
|
|
module.exports =
|
|
|
|
(permType, permLevel = null) =>
|
|
|
|
async (ctx, next) => {
|
|
|
|
// webhooks don't need authentication, each webhook unique
|
2021-11-03 15:08:47 +01:00
|
|
|
if (isWebhookEndpoint(ctx)) {
|
2021-06-15 20:39:40 +02:00
|
|
|
return next()
|
|
|
|
}
|
2020-10-12 12:57:37 +02:00
|
|
|
|
2021-06-15 20:39:40 +02:00
|
|
|
if (!ctx.user) {
|
|
|
|
return ctx.throw(403, "No user info found")
|
|
|
|
}
|
2020-06-18 17:59:31 +02:00
|
|
|
|
2021-06-15 20:39:40 +02: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-27 18:23:01 +02:00
|
|
|
|
2021-06-15 20:39:40 +02:00
|
|
|
const isAuthed = ctx.isAuthenticated
|
|
|
|
const { basePermissions, permissions } = await getUserPermissions(
|
|
|
|
ctx.appId,
|
|
|
|
ctx.roleId
|
|
|
|
)
|
2021-02-08 18:52:22 +01:00
|
|
|
|
2021-06-15 20:39:40 +02: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-02-09 18:24:36 +01:00
|
|
|
|
2021-06-15 20:39:40 +02:00
|
|
|
if (
|
|
|
|
hasResource(ctx) &&
|
|
|
|
doesHaveResourcePermission(permissions, permLevel, ctx)
|
|
|
|
) {
|
|
|
|
return next()
|
|
|
|
}
|
2020-05-27 18:23:01 +02:00
|
|
|
|
2021-06-15 20:39:40 +02:00
|
|
|
if (!isAuthed) {
|
|
|
|
ctx.throw(403, "Session not authenticated")
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!doesHaveBasePermission(permType, permLevel, basePermissions)) {
|
|
|
|
ctx.throw(403, "User does not have permission")
|
|
|
|
}
|
|
|
|
|
|
|
|
return next()
|
|
|
|
}
|