我正在使用快递和护照模块进行身份验证。在会话 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 过期事件,以便我可以重定向到另一个页面?谢谢你。