Multiple models in .js passport

I have two types of accounts on my website:

Administrator and User.

The administrator will have access to the administrative portal and will use credentials and pass.js for authentication.

The user will have access to their account. He could list the products ... He won't have access to the admin portal, but to the front.

So, to summarize the admin account, you can add products, descriptions, manage inventory, and the user will have an account to buy products (e-commerce).

Now my question is that the authentication protocol is the same, but my models are different.

So what is the best way to allow pass.js to authenticate my two accounts?

I need to pass a model to a .js passport.

The solutions I am thinking about are as follows:

  • Has a base user model and inherits the base model in my Admin and User models. But I don't know how to do it.

  • Pass the type of the model I will be using to the .js passport. But how to do that?

  • Create an independent authentication system for each model. But this will make it harder for the code to do the same. Duplication and I hate it. :)

If you have any other ideas or best practices and I can really appreciate it.

Thank,

+3


source to share


1 answer


What's the problem? You can store different roles for users in your databases, for example: 1 - admin 2 - moderator 0 - user (by default)

And after authorization (you can use the same route for admins and users in this case if you like), you can check permissions on your routes:



app.get('/admin/dashboard', isAdmin, function(req, res, next) {
  // you will get inside only if user is authentificated and has role of admin
  // otherwise he will be redirected to the mainpage '/'
  res.send('Hi, admin');
});

function isAdmin(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated()) {
       // if user is admin, go next
       if (req.user.role == 1) {
         return next();
       }
    }
    res.redirect('/');
}

      

+2


source







All Articles