简体   繁体   English

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

[英]Store user sessions: node.js, express, mongoose-auth

I've got a newbie node.js question about authentication ans sessions. 我有一个关于身份验证和会话的新手node.js问题。

I've made an authentication with: express.js and mongoose-auth (mongodb): 我已经通过express.js和mongoose-auth(mongodb)进行了身份验证:

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

I've got not much understanding of all that staff deeply. 我对所有这些员工没有太多了解。 After users are authenticated they stay to be so unless server restarts. 用户通过身份验证后,除非重新启动服务器,否则它们将保持不变。 I want to have more persistent state of authentication, how can I manage this? 我想拥有更持久的身份验证状态,该如何管理呢?

Thanks for help. 感谢帮助。

If you want the sessions to persist even after a server has crashes / restarted then you should use one of the following modules: 如果您希望会话在服务器崩溃/重新启动后仍然存在,则应使用以下模块之一:

You can also set the lifetime of a cookie using the maxAge param when adding the session middleware. 添加会话中间件时,还可以使用maxAge参数设置cookie的生存期。 For example if we were using connect-mongodb: 例如,如果我们使用connect-mongodb:

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

If you use a mongostore it will persist for longer than a server restart. 如果使用mongostore,它将持续的时间比重新启动服务器的时间更长。

This is configurable with the maxAge property. 这可以通过maxAge属性进行配置。 It defaults to 14400000 which I believe is in ms, so 4 hours. 它的默认值为14400000 ,我相信是以毫秒为单位,所以是4个小时。

See the documentation for details: http://senchalabs.github.com/connect/middleware-session.html 有关详细信息,请参见文档: http : //senchalabs.github.com/connect/middleware-session.html

I'm using express V2.5.11. 我正在使用Express V2.5.11。 Here the maxAge option is not seems to be working. 在这里,maxAge选项似乎不起作用。 So I rewrite session configure code as follows. 因此,我重写了会话配置代码,如下所示。

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  
    })
}));

The code is working as pretty good. 该代码工作得很好。

Authentication Using 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 单击以获取更多示例信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM