存储用户会话:node.js,express,mongoose-auth

时间:2011-12-19 20:53:15

标签: javascript node.js authentication mongodb mongoose

我有一个关于身份验证和会话的新手node.js问题。

我使用了:express.js和mongoose-auth(mongodb)进行了身份验证:

app.use(express.cookieParser());
app.use(express.session({ secret: 'esoognom'}));
app.use(auth.mongooseAuth.middleware());

我对那些工作人员的了解并不多。用户通过身份验证后,除非服务器重新启动,否则他们将保持原状。我想拥有更持久的身份验证状态,我该如何管理?

感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

如果您希望会话在服务器崩溃/重新启动后仍然存在,那么您应该使用以下模块之一:

您还可以在添加会话中间件时使用maxAge参数设置cookie的生命周期。例如,如果我们使用connect-mongodb:

app.use(express.session({
    secret : "Stays my secret",
    maxAge : new Date(Date.now() + 3600000), //1 Hour
    store  : new MongoStore({ db: 'myDB' })
}));

答案 1 :(得分:2)

如果使用mongostore,它将持续的时间超过服务器重启。

这可以使用maxAge属性进行配置。它默认为14400000,我认为是ms,所以4小时。

有关详细信息,请参阅文档: http://senchalabs.github.com/connect/middleware-session.html

答案 2 :(得分:1)

我使用快递V2.5.11。这里的maxAge选项似乎不起作用。所以我重写会话配置代码如下。

var MongoStore = require('connect-mongo')(express);
app.use(express.session({
    secret : "basic server",
    cookie : {
        maxAge : 20000 //20 seconds
    }, 
    //maxAge:  new Date(Date.now() + 20000),
    store : new MongoStore({
        host : 'localhost',
        port : 27017,
        db : 'yourdb',
        collection : 'session',
        stringify : false,
        clear_interval : (10)//search db to clear the expired every 10 seconds  
    })
}));

代码工作得非常好。

答案 3 :(得分:-1)

使用Passport进行身份验证

var express = require('express'),
routes = require('./routes'),
api = require('./routes/api'),
http = require('http'),
path = require('path'),
mysql = require('mysql'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;

//MySQL

var sqlInfo = {
    host: 'localhost', 
    user: 'root',
    password: '', 
    database: 'dbname'
}


global.client = mysql.createConnection(sqlInfo);

client.connect();




var app = module.exports = express();




/**
 * Configuration
 */

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

app.use(express.cookieParser("secret"));
app.use(express.session({
    secret: 'keyboard cat'
}));
app.use(passport.initialize());
app.use(passport.session());

app.use(app.router);




passport.use(new LocalStrategy(

    function(username, password, done) {

        return check_auth_user(username,password,done);

    }

    ));


// development only
if (app.get('env') === 'development') {
    app.use(express.errorHandler());
}

// production only
if (app.get('env') === 'production') {
// TODO
}



/**
 * routes start---------------------------------------------------------------
 */
// home page contain login form 
app.get('/home', function(reg, res){
    //check user session value, is logged in 
    if(req.user)
        res.render('dash',{
            username: req.user['member_id']//req.user array contains serializeUser data
        });
    else
        res.render('index');

});

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

    req.logout();
    res.redirect('/home');
});

//login form submit as post

app.post('/login',
    passport.authenticate('local', {
        successRedirect: '/dashboard',
        failureRedirect: '/home'
    })
    );
//to project dashboard
app.get('/dash',routes.dash);
//to project dashboard
app.get('/signup',routes.signup);
//to project dashboard

app.get('*', routes.index);

/**
 * routes end---------------------------------------------------------------------
 */


/**
 * Start Server
 */

http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

click for more details with example