Authorization to see only posts the current user created

Hi all -

Super newbie question: I’m working on an app and I would like only the logged in user to be able to CRUD posts that they create. I have Netlify Identity up and running, but everyone can see all posts currently. Do I lock this down in the models?

Here’s what I have for models:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}

model Post {
  id        Int      @id @default(autoincrement())
  rating    Int
  body      String
  createdAt DateTime @default(now())
}

Thanks, and pardon my dev 101 q’s,

Connor

Hi @CRR and welcome!

Redwood is a great framework with which to start off on in the developer journey :slight_smile:

Because you get to learn about front end work, back end apis, data modeling, queries and even a nice intro to GraphQL building a small app — like your Blog — is a deep slice into making most modern web apps. And you get to learn about auth, too.

That said, a great place to start is here:

This is a cookbook with a blog that has auth to allow only logged in users to post … and also introduces roles so that only certain types of users can do certain things (only admins can delete posts for example).

Here’s a GH repo of the code too:

Read through the code and hopefully it can guide you through.

Have fun!

1 Like

Hi @dthyresson,

Thanks for the RBAC intro. I think it makes sense. :smile: If I wanted to only allow the post creator to see their posts, and no one else, would roles be the way to accomplish this? I’m struggling to figure out how to implement that with roles. Basically, I want the post creator be able to CRED only their own posts.

Thanks,
Connor

When you findUnique your post, make sure its “authorId” or whomever posted it is the same as the currentUser’s id.

You can do this a few ways … which this issue https://github.com/redwoodjs/redwood/issues/1640#issuecomment-761679949 discusses.

Just noticed that it didn’t exactly cover the get case so:

const post = await db.user.findUnique({ where: { id, authorId: currentUser.id } })