最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Store user sessions: node.js, express, mongoose-auth - Stack Overflow

matteradmin4PV0评论

I've got a newbie node.js question about authentication ans sessions.

I've made an authentication with: express.js and 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.

I've got a newbie node.js question about authentication ans sessions.

I've made an authentication with: express.js and 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.

Share Improve this question edited Jul 9, 2012 at 1:22 Kijewski 26k14 gold badges107 silver badges147 bronze badges asked Dec 19, 2011 at 20:53 WHITECOLORWHITECOLOR 26.2k40 gold badges125 silver badges188 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

If you want the sessions to persist even after a server has crashes / restarted then you should use one of the following modules:

  • connect-redis (in memory db, which is usually used) < sessions are stored in a Redis db
  • connect-mongodb < sessions stored in MongoDB
  • other session stores found here, such as couchdb or memcached: https://github./senchalabs/connect/wiki

You can also set the lifetime of a cookie using the maxAge param when adding the session middleware. For example if we were using 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.

This is configurable with the maxAge property. It defaults to 14400000 which I believe is in ms, so 4 hours.

See the documentation for details: http://senchalabs.github./connect/middleware-session.html

I'm using express V2.5.11. Here the maxAge option is not seems to be working. 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

Post a comment

comment list (0)

  1. No comments so far