1
0
Fork 0
mirror of synced 2024-06-27 18:40:42 +12:00
budibase/packages/server/src/middleware/authorized.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

const { getUserPermissions } = require("../utilities/security/roles")
const {
PermissionTypes,
doesHaveResourcePermission,
doesHaveBasePermission,
} = require("../utilities/security/permissions")
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
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
}
2020-06-19 03:59:31 +12:00
if (!ctx.user) {
2021-03-10 00:27:12 +13:00
return ctx.throw(403, "No user info found")
2020-06-19 03:59:31 +12:00
}
2021-04-11 22:35:55 +12:00
const isAuthed = ctx.isAuthenticated
const { basePermissions, permissions } = await getUserPermissions(
ctx.appId,
ctx.roleId
)
2020-05-28 04:23:01 +12:00
let isBuilder = ctx.user && ctx.user.builder && ctx.user.builder.global
if (permType === PermissionTypes.BUILDER && isBuilder) {
2021-04-12 22:20:01 +12:00
return next()
} else if (permType === PermissionTypes.BUILDER && !isBuilder) {
2021-04-12 22:20:01 +12:00
return ctx.throw(403, "Not Authorized")
}
2020-05-28 04:23:01 +12:00
if (
hasResource(ctx) &&
doesHaveResourcePermission(permissions, permLevel, ctx)
) {
return next()
}
if (!isAuthed) {
ctx.throw(403, "Session not authenticated")
}
if (!doesHaveBasePermission(permType, permLevel, basePermissions)) {
ctx.throw(403, "User does not have permission")
}
2020-05-28 04:23:01 +12:00
return next()
2020-05-28 04:23:01 +12:00
}