-
Say I have an app that has an Does anyone know if any examples or open source blitz projects that do this and could be used as a reference? I imagine you'd add |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
My current solution is to add this into the get org query. Not sure if there's a better way of doing this?
|
Beta Was this translation helpful? Give feedback.
-
Another way of doing this is to restrict your database queries: await db.project.findMany({
where: { orgId: ctx.session.orgId }
}) That way, unauthorized users will be unable to see projects that they shouldn't access. |
Beta Was this translation helpful? Give feedback.
-
Here's how I do it. Add My resolver looks like this: import { resolver, NotFoundError } from "blitz"
import db, { TestResult as TestResultBase } from "db"
import { ReportData } from "../types"
import * as z from "zod"
import { enforceAdminIfNotCurrentOrganization, setDefaultOrganizationId } from "app/core/utils"
const GetTestResult = z.object({
id: z.number(),
organizationId: z.number().optional(),
})
export default resolver.pipe(
resolver.zod(GetTestResult),
resolver.authorize(),
setDefaultOrganizationId,
enforceAdminIfNotCurrentOrganization,
async ({ id, organizationId }) => {
const testResult = await db.testResult.findFirst({
where: { id, organizationId },
})
if (!testResult) throw new NotFoundError()
return testResult
}
) And those utilities are here: import { Ctx } from "blitz"
import { Prisma, Role } from "db"
function assert(condition: any, message: string): asserts condition {
if (!condition) throw new Error(message)
}
export const setDefaultOrganizationId = <T extends Record<any, any>>(
input: T,
{ session }: Ctx
): T & { organizationId: Prisma.IntNullableFilter | number } => {
assert(session.orgId, "Missing session.orgId in setDefaultOrganizationId")
if (input.organizationId) {
return input as T & { organizationId: number }
} else if (session.roles?.includes(Role.ADMIN) || session.roles?.includes(Role.PROCTOR)) {
// Allow viewing any organization
return { ...input, organizationId: { not: 0 } }
} else {
return { ...input, organizationId: session.orgId }
}
}
export const enforceAdminIfNotCurrentOrganization = <T extends Record<any, any>>(
input: T,
ctx: Ctx
): T => {
if (!ctx.session.orgId) throw new Error("missing session.orgId")
if (!input.organizationId) throw new Error("missing input.organizationId")
if (input.organizationId !== ctx.session.orgId) {
ctx.session.$authorize(Role.ADMIN)
}
return input
} |
Beta Was this translation helpful? Give feedback.
Here's how I do it.
Add
orgId
to session PublicData.My resolver looks like this: