This commit is contained in:
Carl-Gerhard Lindesvärd
2024-09-03 21:17:40 +02:00
parent 4cdfe3aed2
commit 8e06bacdb0
13 changed files with 326 additions and 54 deletions

View File

@@ -5,7 +5,7 @@ import { has } from 'ramda';
import superjson from 'superjson';
import { ZodError } from 'zod';
import { getProjectAccessCached } from './access';
import { getOrganizationAccessCached, getProjectAccessCached } from './access';
import { TRPCAccessError } from './errors';
export function createContext({ req, res }: CreateFastifyContextOptions) {
@@ -45,7 +45,7 @@ const t = initTRPC.context<Context>().create({
},
});
const enforceUserIsAuthed = t.middleware(async ({ ctx, next, input }) => {
const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
if (!ctx.session?.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' });
}
@@ -66,7 +66,7 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next, input }) => {
});
// Only used on protected routes
const enforceProjectAccess = t.middleware(async ({ ctx, next, rawInput }) => {
const enforceAccess = t.middleware(async ({ ctx, next, rawInput }) => {
if (has('projectId', rawInput)) {
const access = await getProjectAccessCached({
userId: ctx.session.userId!,
@@ -78,6 +78,28 @@ const enforceProjectAccess = t.middleware(async ({ ctx, next, rawInput }) => {
}
}
if (has('organizationId', rawInput)) {
const access = await getOrganizationAccessCached({
userId: ctx.session.userId!,
organizationId: rawInput.organizationId as string,
});
if (!access) {
throw TRPCAccessError('You do not have access to this organization');
}
}
if (has('organizationSlug', rawInput)) {
const access = await getOrganizationAccessCached({
userId: ctx.session.userId!,
organizationId: rawInput.organizationSlug as string,
});
if (!access) {
throw TRPCAccessError('You do not have access to this organization');
}
}
return next();
});
@@ -86,4 +108,4 @@ export const createTRPCRouter = t.router;
export const publicProcedure = t.procedure;
export const protectedProcedure = t.procedure
.use(enforceUserIsAuthed)
.use(enforceProjectAccess);
.use(enforceAccess);