Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple models in passport.js

I have two types of account on my website:

Admin and User.

The admin will access to the administration portal and will use credentials and passport.js to authenticate.

The user will access to his account. He could list the products ... He will not have access to the admin portal but to the front.

So to summarize the admin account can add products, descriptions, manage stocks and the user will have an account to buy the products (ecommerce).

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

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

I need to pass the model to passport.js.

The solutions I am thinking about are:

  1. Have a user base model and inherit the base model in my Admin and User models. But I do not know how to do this.

  2. Pass the model type I will use to passport.js. But how to do that?

  3. Create an independent authentication system for every models. But it will complicate the code to do exactly the same things. Duplication and I hate this. :)

If you have other ideas or best practices and can help I would really appreciate.

Thanks,

like image 421
dalton5 Avatar asked Mar 12 '26 21:03

dalton5


1 Answers

What's the problem? You can store in your DB different roles for users, like: 1 - admin 2 - moderator 0 - user (Default)

And after authorization (you can use single route for admins and users in this case if you want) you can check in your routes a permissions:

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('/');
}
like image 61
Kevin Avatar answered Mar 14 '26 10:03

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!