0

Imagine a personal notes app. Users can add, view and edit their own notes, but not notes that belong to other users.

The notes are accessed this way: app.dev/notes/{id}

So naturally, if I own a note that has an ID of 140, but change the id to 160 in the URL, I will be able to view this note.

I want to prevent that from happening. I thought of using middleware for this, but I've read people saying that we shouldn't use middleware for this because it isn't flexible, and I should use FormRequests instead.

The problem is, I don't understand how I could use FormRequests in this case. I've used FormRequests to prevent a user from editing a note that doesn't belong to them. If I own a note with ID of 140, and try to edit/POST a note with ID of 160, my form request won't let me do it.

But this FormRequest doesn't actually prevents me from viewing the note with ID of 160.

Can someone please point me to the right way of doing this?

Thank you

munich
  • 500
  • 1
  • 6
  • 16

2 Answers2

1

You can use policy. Cleaner and easier way for Authorization.

Authorization Policy : Laravel

After creating and registering your policy you can do something like

public function access(User $user, Note $note) 
{ 
    return $user->id === $note->user_id; 
} 

Then in your method

if (!$user->cannot('access', $note)) 
{ 
    // throw error or redirect somewhere else 
}
Himanshu Raval
  • 790
  • 7
  • 19
0

I would use middleware for this. Have the middleware get the current user, check if they have access to the specified note, and abort if they do not have access.

If you use a repository pattern, make sure you make use of the middleware's construct function to pass in any required repositories/dependencies.

owenconti
  • 400
  • 3
  • 6