使用express和websockets的会话

时间:2016-04-12 02:19:05

标签: javascript node.js express websocket session-cookies

我在我的应用中使用Node,express和websockets。当用户登录时,他们的用户名是在他们的cookie中设置的,但是当他们重新加载页面时,它会被重置为空字符串。即使重新加载页面,如何使会话正常工作?

var Users = require(__dirname + '/db/databaseModel.js');

//server using express beginning of project
var express     = require('express');
var app         = express(); //create express object
var expressWs   = require('express-ws')(app); //create express websocket extension
var session     = require('express-session'); //used for user sessions
var password    = require('password-hash-and-salt'); //used for hashing password
var SQLiteStore = require('connect-sqlite3')(session);

app.use(session({ 
    key: 'express.sid',
    secret: 'keyboard cat',
    resave: true, 
    saveUninitialized: true,
    cookie: { 
        maxAge: 60000,
        username: "",
        store: new SQLiteStore
    }
}));

var gameStarted = false;
var clients = {};
var User = Users();
User.init();

app.ws('/auth', function(ws, req) { //route for checking user login
    //check for valid login
    ws.on('message', function(msg){
        console.log(msg);
        msg = JSON.parse(msg);

        if (msg.cmd === 'login'){
            User.verifyUser(msg.username, msg.password, ws, req);
        }
    });

    console.log('Login Good.');
});

app.use('/', express.static(__dirname + '/public')); //route to serve static login page

app.listen(3000, function () { //start listening for activity on port 3000
  console.log('Listening on port 3000!');
});

这是针对数据库的(我在会话cookie中设置用户名)

Users.verifyUser = function(username, password, ws, req){
    Users.db.serialize(function(){
        Users.db.get('SELECT * FROM users WHERE username = ?;', [username], function(err, row){
            var res = {redirect: false, url:  ''};
            if(row != null){
                verifyPass(username, password, row.hash, ws, res, req);
            }
            else{
                ws.send(JSON.stringify(res));
            }
        });
    });
};

function verifyPass (username, pass, hash, ws, res, req){
    // Verifying a hash 
    password(pass).verifyAgainst(hash, function(error, verified) {
        if (error)
            console.log("error");
        else if(verified) {
            req.session.cookie.username = username;
            res.redirect = true;
            res.url = game_url;
            // msg.url = 'localhost:3000/main.html';
        }
        ws.send(JSON.stringify(res));
    });
}

我一直在阅读有关快递的会话,但我真的很难搞清楚。当用户登录会话时,该页面上的cookie正常,但一旦将其重定向到游戏页面或刷新页面,会话就会重置。

0 个答案:

没有答案