NodeJS ExpressJS PassportJS - 仅适用于管理员页面

时间:2013-06-20 06:14:23

标签: node.js mongodb express mongoose passport.js

我正在使用NodeJS,ExpressJS,Mongoose,passportJS&连接 - 确保登录。验证用户工作正常。

....
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('/');
});

现在,我想添加一些只能由admin访问的路由的限制。我怎样才能做到这一点?例如/admin/*

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

mongoose.model('User', schema);

任何提示?感谢

2 个答案:

答案 0 :(得分:13)

您可以将自定义中间件附加到/admin/*路由,该路由将在任何更具体的/admin/路由上传递请求之前检查管理员状态:

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/', ...);

答案 1 :(得分:-1)

//Add following function to your app.js above **app.use(app.router)** call;

//This function will be called every time when the server receive request.

app.use(function (req, res, next) {
  if (req.isAuthenticated || req.isAuthenticated())
  {
    var currentUrl = req.originalUrl || req.url;
    //Check wheather req.user has access to the above URL
    //If req.user don't have access then redirect the user
    // to home page or login page
    res.redirect('HOME PAGE URL');
  }
  next();
});

我没有尝试过,但我认为它会起作用。