6

我正在使用 NodeJS、ExpressJS、Mongoose、passportJS 和 connect-ensure-login。对用户进行身份验证非常有效。

....
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/*

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

mongoose.model('User', schema);

有什么提示吗?谢谢

4

2 回答 2

17

您可以将自定义中间件附加到/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/', ...);
于 2013-06-20T06:41:50.257 回答
-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();
});

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

于 2013-06-20T06:43:28.557 回答