I am working on a blog in node.js and I need to know if there is a way to hide content, like 'edit', 'delete' and 'new post' buttons, for users that are not logged in? I could redirect 'guests' to pages without those buttons, but that seems kinda dumb. This is a login method I found, and it works, but how do I use this 'req.session.user = username;' in a good way?

exports.login = function(req, res){
    var username = req.body.username;
    var password = req.body.password;
    var hash = crypto.createHash('sha256').update(password).digest('base64');   

    r.connect( {host: 'localhost', port: 28015}, function(err, conn) {
        if (err) throw err;
        connection = conn;

        r.db("app").table("user").filter({username: username, password: hash}).run(conn, function(err, cursor){
            if (err) throw err;

            cursor.toArray(function(err, result){
                if(result.length == 0){
                    res.render("index", {msg: "No user with that name"})
                    }
                else{
                    console.log(username);
                    req.session.user = username;
                    res.redirect("index");
                    //res.render("menu");
                }
            });
        });
    });
};

I am working in node.js with express, jade and stylus. I hope you understand, and just tell me if I need to post any more information!

有帮助吗?

解决方案

One solution may be to set a flag on res.locals that you use in your views. You'd initialize say, res.locals.loggedIn = false; somewhere early on in your middleware stack if they are logged in or set it to true if they are (e.g. a session exists with some information showing they have successfully authenticated before).

Then in your view you just do something like if (loggedIn) { /* show buttons */ }

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top