1
0
Fork 0
mirror of synced 2024-06-30 20:10:54 +12:00
budibase/packages/server/src/middleware/authorized.js

77 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]
function hasResource(ctx) {
return ctx.resourceId != null
}
module.exports = (permType, permLevel = null) => async (ctx, next) => {
if (env.isProd() && 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()
}
2021-03-10 00:27:12 +13:00
return ctx.throw(403, "API key invalid")
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
}
const role = ctx.user.role
const isAdmin = ADMIN_ROLES.includes(role._id)
2021-04-11 22:35:55 +12:00
// const isAuthed = ctx.auth.authenticated
const isAuthed = ctx.isAuthenticated
const { basePermissions, permissions } = await getUserPermissions(
ctx.appId,
role._id
)
2020-05-28 04:23:01 +12:00
// this may need to change in the future, right now only admins
// can have access to builder features, this is hard coded into
// our rules
2021-04-11 22:35:55 +12:00
// if (isAdmin && isAuthed) {
// return next()
// } else if (permType === PermissionTypes.BUILDER) {
// 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
}