refactor admin functions in store to use active account - introduce admin middleware
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user