TheGabornator
TheGabornator

Reputation: 551

How would you approach Node.js access authorization and restriction of the access in the database?

I can find tons of articles about how to build user authorization, but I still can't grasp how to restrict that a certain user can access only to it's own files? How do pros approach this access control? Is the user data within the user number's array, which can be accessed by the authenticated user with this number?

Could you maybe recommend any source, tutorial or literature for it? Maybe one in which you have to build an API for a diary or something? How do you know this process specifically?

Thanks a lot for any hint in advance.

Cheers,

GT

PS. If you don't know Node.js but PHP or else, it would be also helpful just to learn more on the theory of authorization.

Upvotes: 0

Views: 59

Answers (1)

Tom Jardine-McNamara
Tom Jardine-McNamara

Reputation: 2618

If you're trying to restrict users to content they "own", then a simple approach is to store a user id/document on each protected record. In your api routes/controllers you can then add a filter to the find call to filter by the current user's id. I'm avoiding specifics as I don't know your exact setup.

For example, a diary entry route might look something like:

app.get('/diary-entry', function(req, res, next) {
  DiaryEntry.find({ user: req.user._id }, function(err, entries) {
    if(err) return next(err);
    red.send(entries);
  });
});

Upvotes: 1

Related Questions