Seltsam
Seltsam

Reputation: 944

Controlling/Restricting User-specific content in Mongo-Database

I'm wondering how to control/restrict access from different users to their content stored in mongodb (accessed via mongoose). Let's say there is a data-model to store last wills for users.

My approach would be:

  1. Login: authenticate via username and password, store username in session.
  2. Middleware: Check Login-Status, query user-model for the stored username and return the user id, attach it to req-object (req.userId)
  3. When hitting the route to get actual content (the last-will-model): query the will-model with two conditions: matching willId and matching userId (which is also stored in will-model)

Is this in any way reasonable or even save? Couldn't find any best-practises, all the examples basically end with authentication.

Upvotes: 1

Views: 1523

Answers (2)

robertklep
robertklep

Reputation: 203241

Steps 1 and 2 can be covered by using passport-local, although it's not too hard to implement manually.

Step 3 is reasonable, given that a will belongs to a user and both willId and userId are required to determine if that user should have access to a particular will document.

Since security is based on session id's, you should obviously use HTTPS and use httpOnly and secure session cookies.

Upvotes: 3

Borja Tur
Borja Tur

Reputation: 817

With any of the three ways you can implement authorization, IMO the option I would choose is to use a Middleware.

It would be a cleaner option, with little impact on the code functionality and easy to maintain for future changes, also separates the concept of authentication and authorization.

I've never used, but have in mind to use this package in a project that I have to make. You can define your rules and then use it on specific routes.

app.get('/', *user.can('access home page'), function (req, res) {
    res.render('private');
});
app.get('/private', *user.can('access private page'), function (req, res) {
    res.render('private');
});
app.get('/admin', *user.can('access admin page'), function (req, res) {
    res.render('admin');
});

*Predefined rules

Upvotes: 3

Related Questions