refactor admin functions in store to use active account - introduce admin middleware

This commit is contained in:
Michael Dausmann
2023-02-24 21:09:49 +11:00
parent f2b3a2617d
commit a341a641e8
6 changed files with 57 additions and 22 deletions

View File

@@ -9,6 +9,8 @@
*/
import { initTRPC, TRPCError } from '@trpc/server'
import { Context } from './context';
import { z } from 'zod';
import { ACCOUNT_ACCESS } from '@prisma/client';
const t = initTRPC.context<Context>().create()
@@ -26,10 +28,27 @@ const isAuthed = t.middleware(({ next, ctx }) => {
});
});
const isAdminForInputAccountId = t.middleware(({ next, rawInput, ctx }) => {
if (!ctx.dbUser) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
const result = z.object({ account_id: z.number() }).safeParse(rawInput);
if (!result.success) throw new TRPCError({ code: 'BAD_REQUEST' });
const { account_id } = result.data;
const test_membership = ctx.dbUser.memberships.find(membership => membership.account_id == account_id);
console.log(`isAdminForInputAccountId test_membership?.access:${test_membership?.access}`);
if(!test_membership || (test_membership?.access !== ACCOUNT_ACCESS.ADMIN && test_membership?.access !== ACCOUNT_ACCESS.OWNER)) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({ ctx });
});
/**
* Unprotected procedure
**/
export const publicProcedure = t.procedure;
export const protectedProcedure = t.procedure.use(isAuthed);
export const adminProcedure = protectedProcedure.use(isAdminForInputAccountId);
export const router = t.router;
export const middleware = t.middleware;