Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS ExpressJS PassportJS - for Admin Pages Only

Im using NodeJS, ExpressJS, Mongoose, passportJS & connect-ensure-login. Authenticating users works perfectly.

....
var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy
  , ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

var app = express();
...
app.use(passport.initialize());
app.use(passport.session());    
...


passport.use(new LocalStrategy({usernameField: 'email', passwordField: 'password'},
    function(email, password, done) {
  User.findOne({ 'email': email, 'password': password },
               {'_id': 1, 'email':1}, function(err, user) {

    if (err) { return done(err); }

    if (!user) {
      return done(null, false, { message: 'Incorrect username.' });
    }

    return done(null, user);
  });
}));

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {  
  done(null, user);
});

app.post('/login', passport.authenticate('local',
    { successReturnToOrRedirect: '/home', failureRedirect: '/login' }));

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

Now, I want to add restrictions to some routes to be accessible only by admin. How can I do that? e.g. /admin/*

var schema = new mongoose.Schema({
    name: String,
    email: String,
    password: String,
    isAdmin: { type: Boolean, default: false }
});

mongoose.model('User', schema);

Any hint? Thanks

like image 213
JR Galia Avatar asked Jun 20 '13 06:06

JR Galia


1 Answers

You could attach a custom middleware to the /admin/* route that would check for admin status before passing the request on the any of the more specific /admin/ routes:

var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;
...
var requiresAdmin = function() {
  return [
    ensureLoggedIn('/login'),
    function(req, res, next) {
      if (req.user && req.user.isAdmin === true)
        next();
      else
        res.send(401, 'Unauthorized');
    }
  ]
};

app.all('/admin/*', requiresAdmin());
app.get('/admin/', ...);
like image 81
robertklep Avatar answered Sep 28 '22 10:09

robertklep