ChristianC
Convex Community2y ago
16 replies
Christian

How is mutation authentication supposed to work?

In this template https://www.convex.dev/templates/nextjs-app-router

in the posts.ts inside the convex folder there is this code
export const create = mutation({
  args: { authorId: v.id("users"), text: v.string() },
  handler: async (ctx, { text, authorId }) => {

    if (text.length <= 0 || text.length > CHARACTER_LIMIT) {
      throw new Error("Message is too damn long! (or empty)");
    }

    const numSentRecently = (
      await ctx.db
        .query("posts")
        .withIndex("byAuthorId", (q) =>
          q
            .eq("authorId", authorId)
            .gte("_creationTime", Date.now() - 1000 * 60)
        )
        .take(3)
    ).length;

    if (numSentRecently >= 3) {
      throw new Error("Too fast, slow down!");
    }

    await ctx.db.insert("posts", { authorId, text });
    // Instead of computing the number of tweets when a profile
    // is loaded, we "denormalize" the data and increment
    // a counter - this is safe thanks to Convex's ACID properties!
    const author = (await ctx.db.get(authorId))!;
    await ctx.db.patch(authorId, { numPosts: author.numPosts + 1 });
  },
});

There is no check for what user is running this code and seemingly no safe guards against a bad actor trying to post as another user.

Am I missing something or is there more to add for a production ready app?
The backend application platform with everything you need to build your product.
Templates
Was this page helpful?