S
S
Sakolik2016-02-19 16:37:43
Node.js
Sakolik, 2016-02-19 16:37:43

Passport js and express js. How to create roles?

Hello! There is a mongoose schema like this:

var mongoose = require('mongoose');
  module.exports = mongoose.model('Admin',{
    username: String,
    password: String,
    role: { type: String, default: "user" },
    soft_token: { type: String, default: 0 }
});

How to deny access to the page using passportjs depending on whether the user is admin or user.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sakolik, 2016-02-19
@Sakolik

Decided like this:

var isAuthenticated = function (req, res, next) {
  var currentUserId = req.user ? req.user.id : false;
  if(!currentUserId){
    res.redirect('/');
    return;
  }
  Admin.findById(currentUserId,function (err, user) {
    if(!user || user.role !== "admin"){
      res.redirect('/');
    }else{
      next();
    }
  })
}

router:
router.get('/admin', isAuthenticated, function(req, res, next) {
    
    res.end();
  });

Now a simple user will not be able to go to "/admin"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question