#`findById` vs `findByIdAndUser`

2 messages · Page 1 of 1 (latest)

long mountain
#

Lets say we have a resource that should only be accessible by a user, we could use findById to get the record and then in our business logic to handle whether or not if it was found (NotFound) and then validate whether or not the user can access the resource (Unauthorized/Forbidden). Alternatively we can combine the first and second parts by querying both the id and the user on the record but then we lose a little context, was the resource found or was it not accessible? Based on your experience, which of the following is more appropriate for this API? Feel free to throw in more wisdom!

cold moss
#

Depends. If it's a public app and one user asks for a content that belongs to another user, you might want to return NotFound, otherwise you'll hint to a potential attacker that the content exists.
You can see this behavior on GitHub when you try to access a pribate repository that you're not a part of - you get a 404 error.
On the other hand, in a multi-tenant application, where a user wants to access a document that is inside their tenant but they don't have sufficient privileges, you might return 401 so they can reach out to the workspace admin. You can see this behavior in Notion and other CMS applications.