Where to check if user is owner

Hello, I have and app with three entities User, Deck and Card, and now for any operation on card/deck I need to check if user is owner of that deck I'm doing it like this:
export const isUserDeckOwner = async (
deckId: string,
userId: string,
prisma: PrismaClient
) => {
const deck = await prisma.deck.findFirst({
where: {
id: deckId,
},
});

if (deck?.userId != userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You don't have permission to access this deck",
});
}
};
export const isUserDeckOwner = async (
deckId: string,
userId: string,
prisma: PrismaClient
) => {
const deck = await prisma.deck.findFirst({
where: {
id: deckId,
},
});

if (deck?.userId != userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You don't have permission to access this deck",
});
}
};
But I need to call this in each router method, now I wonder could I create a procedure for this? And if answer is yes how could I pass deckID variable to procedure? Thanks in advance
11 Replies
cje
cje2y ago
don't create a procedure, create a function checkIfUserOwnsDeck(userId, deck) or actually in this specific case you can even do it in the prisma query where: { id: deckid, userId: userId } im on phone so syntax might be wrong
cje
cje2y ago
Christopher Ehrlich
YouTube
Advanced tRPC - Callers, functions, and gSSP
Repo for this video: https://github.com/c-ehrlich/you-dont-need-callers If you want to use schema in the frontend, they cannot be imported from the same file as things that run specifically in the backend. One solution would be to put them into a procedureName.schema.ts or similar file. tRPC: https://trpc.io/docs Create T3 App: https://crea...
iDarkLightning
Are you getting deckId from input?
Bozic0909
Bozic0909OP2y ago
yes @thanks you @cje should I call that inside every route method?? and for example in prisma query, I can do that for deck but not in card router for cards also thank you for video I will take a look!
cje
cje2y ago
best thing to do depends on how often you are doing this basically you don't want to call procedures from other procedures a lot of unnecessary overhead we don't know enough about your app to tell you what the logic should be but a reusable function seems reasonable
Bozic0909
Bozic0909OP2y ago
well I have 2 routers and each has 3-4 methods, soo I guess calling function is fine in this situation, but I wonder what would be example if there is an app a lot larger?
iDarkLightning
Why not make a procedure that wraps a middleware
Bozic0909
Bozic0909OP2y ago
input can be passed to middleware, or custom prop?
iDarkLightning
inputs are merged if your initial procedure has a .input it will merge later
Bozic0909
Bozic0909OP2y ago
ouhh didn't know that, will try that in morning thank you people!
iDarkLightning
yeah I believe it happened during one of the release canidates for v10? rather late into it but that should work fine
Want results from more Discord servers?
Add your server