#Do i need to check if the currently logged in user is the owner of the document I am deleting?

1 messages · Page 1 of 1 (latest)

unborn osprey
#

All the docs show just calling delete without checking on user id of requester.

burnt fossilBOT
#

Hi @unborn osprey. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, it is recommended to check if the currently logged in user is the owner of the document before deleting it. This is to prevent one user from editing or deleting another user's data.

You can achieve this by checking that the authenticated user is the one that "owns" the mutated document. Here's an example of how you can do it:

export const deleteSomething = mutation(
  args: { id: v.id("somethings") },
  handler: async (ctx, { id }) => {
    // getCurrentUser uses `ctx.auth.getUserIdentity()`
    const user = await getCurrentUser(ctx);
    const something = ctx.db.get(id);
    if (user === null || user._id !== something.ownerId) {
      throw new Error("Unauthenticated");
    }
    await ctx.db.delete(id);
  },
});

In this example, getCurrentUser uses ctx.auth.getUserIdentity() to get the current user. Then it checks if the user is null or if the user's id does not match the ownerId of the document. If either of these conditions is true, it throws an "Unauthenticated" error. Otherwise, it deletes the document.

This approach ensures that only the user who created the document can delete it, providing an additional layer of security for your application.

Source (https://discord.com/channels/1019350475847499849/1237357470926508043)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: