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

80 lines
2 KiB
JavaScript
Raw Normal View History

const {
BUILTIN_ROLE_IDS,
getUserPermissions,
} = require("../utilities/security/roles")
const {
PermissionTypes,
doesHaveResourcePermission,
doesHaveBasePermission,
} = require("../utilities/security/permissions")
const env = require("../environment")
const { isAPIKeyValid } = require("../utilities/security/apikey")
const { AuthTypes } = require("../constants")
2020-05-28 04:23:01 +12:00
const ADMIN_ROLES = [BUILTIN_ROLE_IDS.ADMIN, BUILTIN_ROLE_IDS.BUILDER]
const LOCAL_PASS = new RegExp(["webhooks/trigger", "webhooks/schema"].join("|"))
function hasResource(ctx) {
return ctx.resourceId != null
}
module.exports = (permType, permLevel = null) => async (ctx, next) => {
// webhooks can pass locally
if (!env.CLOUD && LOCAL_PASS.test(ctx.request.url)) {
return next()
}
if (env.CLOUD && ctx.headers["x-api-key"] && ctx.headers["x-instanceid"]) {
2020-10-12 23:57:37 +13:00
// api key header passed by external webhook
if (await isAPIKeyValid(ctx.headers["x-api-key"])) {
ctx.auth = {
authenticated: AuthTypes.EXTERNAL,
apiKey: ctx.headers["x-api-key"],
}
2020-10-12 23:57:37 +13:00
ctx.user = {
appId: ctx.headers["x-instanceid"],
2020-10-12 23:57:37 +13:00
}
return next()
}
ctx.throw(403, "API key invalid")
}
// don't expose builder endpoints in the cloud
if (env.CLOUD && permType === PermissionTypes.BUILDER) return
if (!ctx.auth.authenticated) {
2020-05-28 04:23:01 +12:00
ctx.throw(403, "Session not authenticated")
}
2020-06-19 03:59:31 +12:00
if (!ctx.user) {
ctx.throw(403, "User not found")
}
const role = ctx.user.role
const { basePermissions, permissions } = await getUserPermissions(
ctx.appId,
role._id
)
if (ADMIN_ROLES.indexOf(role._id) !== -1) {
return next()
2020-05-28 04:23:01 +12:00
}
if (permType === PermissionTypes.BUILDER) {
2020-05-28 04:23:01 +12:00
ctx.throw(403, "Not Authorized")
}
if (
hasResource(ctx) &&
doesHaveResourcePermission(permissions, permLevel, ctx)
) {
return next()
}
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
}