Search code examples
next.jsnestedformikprisma

Creating deeply nested object in Prisma securely


I am using Prisma and Nextjs with the following data structure, with authentication using Next-Auth.

user
|-->profile
     |-->log
           |-->sublog

Right now the CRUD is sent to the database via API routes on Nextjs. And I want to write to sublog securely via the API.

So when I write this, it is open-ended:

const sublog = await prisma.sublog.create({
 data: {
         name: req.body.name,
         content: req.body.content,
         log: {
            connect: {
               id: req.body.logId,
              }
          }
       }
})

I have access to the user session from the frontend and backend in order to get the userID. But I am not sure how to make the form submission secure that only if the user who owns the log can they be allowed to submit a sublog.

Any ideas on how to securely submit something securely while it is deeply nested?

P.S. Note that I can turn on and off any component that edit/delete data at the frontend - but that's only on the frontend, I want to secure it on the API so that even if the client somehow is able to access a form within the log that doesn't belong to them, it would still push an error from the API since the client don't belong there.


Solution

  • You'd need to make a prisma query that checks who owns the log before allowing the prisma.sublog.create to be executed. Prisma is agnostic to the concept of ownership - You need to add and check that logic yourself.

    const fullLog = await prisma.log.findUnique({
      select: { // don't know what your model looks like, just guessing
        id: true,
        profile: {
          select: {
            userId: true
          }
        }
      },
      where: {
        id: req.body.logId
      }
    });
    
    // currentUserId = however you get the current user's id
    if (fullLog && fullLog.profile.userId !== currentUserId) {
      // throw an error
    }