Must be post owner to delete post

Hi Folks,

I am trying to take the awesome Redwood tutorial to another level. My goal is to have it so only the user associated with a post has the ability to delete a post.

Now sorting that on the front end is straightforward. I check to see if the user is associated with a post and then show the delete button based on that condition. But how could I go about securing the backend so only the correct user can delete a post (i.e making sure I prevent someone from coming in the backend and deleting another user’s post)

Is this something a custom directive may be able to help with?

I would appreciate it if someone can point me in the right direction for solving this the Redwood Way :tm:

PS. if you can suggest a better title for SEO purposes please go ahead

Thanks

1 Like

Interesting idea! Would you open to creating a how-to guide for this? With a link from the related section of the tutorial explaining that you can follow that guide for a more thorough usage of RBAC?

We don’t like making major changes to the tutorial as we have supporting assets (like videos) and making these kinds of changes would require re-recording them to get them to match up with the flow. That’s not really something we want to commit to at the moment.

But supporting docs are always welcome!

Yeah, would love to help.

I am going to need some guidance first. I started down this direction to check if the authenticated user is the same user but it does not feel right.

A thing I find hard about using any framework is knowing If i am using the framework to it’s full potential

export const deletePost = async ({ id }: Prisma.PostWhereUniqueInput) => {
  
const { userId } = await post({id})

  if (userId != context.currentUser.id) {
   return new RedwoodGraphQLError(
      'You do not have permission to delete this video'
    )
  } else {
    return db.post.delete({
      where: { id },
  })
}

nb. I’m a junior dev

What you’ve shown here is pretty much exactly what I would do! The only change might be to move that ownership check into its own function so that you can re-use it for the updatePost function as well.

We’ve also got Service Validations that are usually used to check that your data is formatted correctly before getting into the database, but we’ve also got a validateWith() function that lets you use whatever logic you want. And you are validating something, so it fits right in!

I haven’t done much with GraphQL Directives, but my understanding is that they’re more suited to transforming data in/out of the endpoint… like if you wanted everything to be UPPERCASE even though it’s stored in the database in lowercase.

Good to know Rob. Thanks.

I will keep plugging away and try to bash together a short guide soon

2 Likes