Reputation: 1100
I am working on a Web App with an Angular 2 frontend and a Flask backend that access a PostgreSQL database. My app sends requests to my backend such as GET /items/{user_id}
, GET /items/{user_id}/{item_id}
and POST /items/{user_id}/{item_id}
I am relatively new to Web Development and its my first time designing a REST API, how do I allow a user to only be able to access items under his user_id ? For example, if their user_id=123 GET /items/123
would work but GET /items/234
would not ?
Is is something that is done from the PostgreSQL side or I do have to write logic in the backend code server code to do something like this: ?
if current_user.id != req.params.user_id:
// Send response status 403
else
// Send response 200 with items as the body
Is there a better way to accomplish this ?
Thank you.
Upvotes: 0
Views: 65
Reputation: 7774
Since this is a pretty broad question with a lot of exceptions, I'll be pretty general. But this should be represented as a One-to-Many/Many-to-One relation within your database. In other words, a User can own multiple Items, but an Item can only be owned by one User. You'll want to have a Foreign Key constraint within your Items table that represents a user_id
, or the ID of the owner. From their you'll want to query the database for only items that match the requesting User's ID.
In terms of keeping users from requesting other items, you might have to implement some kind of middleware that runs on your backend to check when a user is requesting a specific item that returns an error if they do not own it (Like what you suggested).
To be honest though, if its security you are concerned about you should consider restructuring your API calls. Since you are determining identity based on the user_id
parameter within the url you are opening yourself up to users changing their advertised ID at will. Using web tokens to establish identity will go a long way in terms of beefing up the security of your application.
Upvotes: 2