budibase/packages/server/src/middleware/triggerRowActionAuthorised.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-08-26 17:13:52 +02:00
import { Next } from "koa"
2024-09-03 17:21:13 +02:00
import { UserCtx } from "@budibase/types"
2024-08-26 17:13:52 +02:00
import { paramSubResource } from "./resourceId"
import { docIds } from "@budibase/backend-core"
import * as utils from "../db/utils"
import sdk from "../sdk"
2024-09-03 17:53:25 +02:00
async function executeMiddleware(
ctx: UserCtx,
delegate: (ctx: UserCtx, next: any) => any
) {
await new Promise<void>(r => delegate(ctx, () => r()))
}
2024-08-26 17:13:52 +02:00
export function triggerRowActionAuthorised(
sourcePath: string,
actionPath: string
) {
2024-09-03 17:53:25 +02:00
async function extractResourceIds(ctx: UserCtx) {
2024-09-03 17:21:13 +02:00
ctx = { ...ctx }
2024-08-26 17:13:52 +02:00
// Reusing the existing middleware to extract the value
2024-09-03 17:53:25 +02:00
await executeMiddleware(ctx, paramSubResource(sourcePath, actionPath))
2024-09-03 17:21:13 +02:00
2024-09-03 17:53:25 +02:00
const sourceId: string = ctx.resourceId
const rowActionId: String = ctx.subResourceId
2024-08-26 17:13:52 +02:00
const isTableId = docIds.isTableId(sourceId)
const isViewId = utils.isViewID(sourceId)
if (!isTableId && !isViewId) {
ctx.throw(400, `'${sourceId}' is not a valid source id`)
}
const tableId = isTableId
? sourceId
: utils.extractViewInfoFromID(sourceId).tableId
2024-09-03 17:21:13 +02:00
const viewId = isTableId ? undefined : sourceId
return { tableId, viewId, rowActionId }
}
return async (ctx: UserCtx, next: Next) => {
const { tableId, viewId, rowActionId } = extractResourceIds(ctx)
2024-08-26 18:00:14 +02:00
2024-08-26 17:13:52 +02:00
const rowAction = await sdk.rowActions.get(tableId, rowActionId)
2024-09-03 17:21:13 +02:00
if (!viewId && !rowAction.permissions.table.runAllowed) {
2024-08-26 17:13:52 +02:00
ctx.throw(
403,
2024-09-03 17:21:13 +02:00
`Row action '${rowActionId}' is not enabled for table '${tableId}'`
2024-08-26 17:13:52 +02:00
)
2024-09-03 17:21:13 +02:00
} else if (viewId && !rowAction.permissions.views[viewId]?.runAllowed) {
2024-08-26 17:13:52 +02:00
ctx.throw(
403,
2024-09-03 17:21:13 +02:00
`Row action '${rowActionId}' is not enabled for view '${viewId}'`
2024-08-26 17:13:52 +02:00
)
}
2024-08-26 18:00:14 +02:00
// Enrich tableId
ctx.params.tableId = tableId
2024-08-26 17:13:52 +02:00
return next()
}
}