@@ -166,21 +166,7 @@ export const userRouter = createTRPCRouter({
166166 )
167167 . mutation ( async ( { input, ctx } ) => {
168168 if ( input . expenseId ) {
169- const expenseParticipant = await db . expenseParticipant . findUnique ( {
170- where : {
171- expenseId_userId : {
172- expenseId : input . expenseId ,
173- userId : ctx . session . user . id ,
174- } ,
175- } ,
176- } ) ;
177-
178- if ( ! expenseParticipant ) {
179- throw new TRPCError ( {
180- code : 'UNAUTHORIZED' ,
181- message : 'You are not the participant of the expense' ,
182- } ) ;
183- }
169+ await validateEditExpensePermission ( input . expenseId , ctx . session . user . id ) ;
184170 }
185171
186172 try {
@@ -438,21 +424,7 @@ export const userRouter = createTRPCRouter({
438424 deleteExpense : protectedProcedure
439425 . input ( z . object ( { expenseId : z . string ( ) } ) )
440426 . mutation ( async ( { input, ctx } ) => {
441- const expenseParticipant = await db . expenseParticipant . findUnique ( {
442- where : {
443- expenseId_userId : {
444- expenseId : input . expenseId ,
445- userId : ctx . session . user . id ,
446- } ,
447- } ,
448- } ) ;
449-
450- if ( ! expenseParticipant ) {
451- throw new TRPCError ( {
452- code : 'UNAUTHORIZED' ,
453- message : 'You are not the participant of the expense' ,
454- } ) ;
455- }
427+ await validateEditExpensePermission ( input . expenseId , ctx . session . user . id ) ;
456428
457429 await deleteExpense ( input . expenseId , ctx . session . user . id ) ;
458430 } ) ,
@@ -558,4 +530,25 @@ export const userRouter = createTRPCRouter({
558530 } ) ,
559531} ) ;
560532
533+ const validateEditExpensePermission = async ( expenseId : string , userId : number ) : Promise < void > => {
534+ const [ expenseParticipant , addedBy ] = await Promise . all ( [
535+ db . expenseParticipant . findUnique ( {
536+ where : {
537+ expenseId_userId : {
538+ expenseId : expenseId ,
539+ userId : userId ,
540+ } ,
541+ } ,
542+ } ) ,
543+ db . expense . findUnique ( { where : { id : expenseId } , select : { addedBy : true } } ) ,
544+ ] ) ;
545+
546+ if ( ! expenseParticipant && ! addedBy ?. addedBy ) {
547+ throw new TRPCError ( {
548+ code : 'UNAUTHORIZED' ,
549+ message : 'You are not the participant of the expense' ,
550+ } ) ;
551+ }
552+ } ;
553+
561554export type UserRouter = typeof userRouter ;
0 commit comments