2

我有一个包含用户名密码字段的表单,该表单将用户名和密码存储在 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;
4

1 回答 1

0

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

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

代替:

loggedInUsers[username] = LoggedIn;
于 2013-10-16T08:37:10.453 回答