会话cookie过期后如何重定向到页面?

时间:2012-12-13 14:29:30

标签: node.js express passport.js

我正在使用快递和护照模块进行身份验证。我尝试以不同的方式在会话cookie到期后进行重定向而没有结果。 目前我正在尝试登录操作后使用日程安排功能。我有以下代码:

    var express = require('express')
  , passport = require('passport')
  , util = require('util')
  , LocalStrategy = require('passport-local').Strategy
  , schedule = require('node-schedule');


var users = [
    {id: 1, username: 'user', password: 'passwd'}
];

function findById(id, fn) {
  var idx = id - 1;
  if (users[idx]) {
    fn(null, users[idx]);
  } else {
    fn(new Error('User ' + id + ' does not exist'));
  }
}

function findByUsername(username, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
      return fn(null, user);
    }
  }
  return fn(null, null);
}

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

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    process.nextTick(function () {
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
));

var app = express.createServer();

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat', cookie: {maxAge: 10000}}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/../../public'));
});

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user, message: 'error' });
});

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', dfailureFlash: true }),
  function(req, res) {
    res.redirect('/');
    dateExpiration = new Date(Date.now() + 10000);
    var j = schedule.scheduleJob(dateExpiration, function(){
        console.log('Cookie expiration event');
        // How can I redirect to login page after cookie session expires?
        //redirect('/login')
    });
  });

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

app.listen(3000);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

是否有其他方法可以在node.js中检测会话cookie过期事件,以便我可以重定向到另一个页面? 谢谢。

1 个答案:

答案 0 :(得分:0)

所以,如果我理解你的要求是正确的,那么你本身就无法“检测”一个cookie过期。

如果cookie过期,浏览器将不会将其发送到服务器,也就是说,cookie过期实际上发生在浏览器端,而不是服务器端。

但是,如果你想“伪造”它,你可以尝试类似下面的伪代码:

on "login":
    set a cookie that expires in 100x \
    the amount of time it takes your session to expire

on "ensureAuthenticated":
    check for req.user
    if i don't have req.user but have my other cookie
        Fire my expiration event, which unsets the other cookie
    if i don't have req.user or my other cookie
        Send the user to the login page
    if i've got req.user
        Re-set my other cookie so that i update the expiration

可能不是你想要的100%,但应该接近。