node.js中的用户会话

时间:2013-10-16 07:56:53

标签: node.js

我有一个带有用户名密码字段的表单,用于存储node.js中的用户名和密码 如何跟踪单个用户登录的次数。我想在登录用户列表中的每个用户名旁边输出用户的会话数

index.js:

var loggedInUsers = {};
var LoggedIn = 'TheUserIsLoggedIn';
function index(req, res) {
    if (req.session.username) {
        res.redirect("/users");
    } else {
debugger;
    res.render('index', { title: 'COMP 2406 Session Demo', 
                  error: req.query.error });
    }
}
function users(req, res) {
    if (req.session.username) {
    res.render("account.jade", {username:req.session.username,
                    title:"Account",
                    loggedInUsers: loggedInUsers});
    } else {
    res.redirect("/?error=Not Logged In");
    }
};
function login(req, res) {
    var username = req.body.username;
    req.session.username = username;
    loggedInUsers[username] = LoggedIn;
    res.redirect("/users")
}
function logout(req, res) {
    delete loggedInUsers[req.session.username];
    req.session.destroy(function(err){
        if(err){
            console.log("Error: %s", err);
        }
    });
    res.redirect("/");
}
exports.index = index;
exports.users = users;
exports.login = login;
exports.logout = logout;

1 个答案:

答案 0 :(得分:0)

没有任何持久层,我建议:

if( loggedInUsers[username] ) {    
    loggedInUsers[username].timesLoggedIn++;
    loggedInUsers[username].sessions.push( req.session );
}
else {
    loggedInUsers[username] = {
        timesLoggedIn : 0,
        sessions : []
    };
}

而不是:

loggedInUsers[username] = LoggedIn;