I have a function to login
app.post(\'/doLogin\', function(req,res){
db.users.findOne({username: req.body.username}, function(err, user) {
if
If {secure:true} is set, and you access your site over HTTP, the cookie will not be set. So, each request will create a new session.
The best way to do things is to always let Express deal with it, if it can.
https://flaviocopes.com/express-sessions/ ( Updated Session tutorial although links should not be considered answers )
There's a link that can show you how to set up redis for sessions in Express. You shouldn't have to even query redis yourself when dealing with sessions, that's a job for middleware in node.
Express-session uses the cookie to set or get the session id from the client
as stated on the documentation
Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.
Remember the below points:
If you are not hosting on HTTPS connection cookie secure flag should be set to false.
If the you are using a proxy thats hosted on the HTTPS you should set trust proxy to 1. Refer the documentation
cookie: { secure: false }
for example:
app.use(session({
// your settings
cookie: { secure: false }
}))
All answers so far are helpful but don't directly solve the issue with using secure:true.
In order to use secure:true you must have support for https for secure cookies. Additionally you must use withCredentials for cross-site access control. withCrendentials:true has no impact on same-site request.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Majority of libraries support this parameter in their configurations such as angular and dropzone.
Maybe there are some asynchronous errors in your code. Every time you have the asynchronous operation(like a callback), you should make sure that your rest code is executed after the callback function, so you may put the code into the callback function. Just like this:
db.users.findOne({username: req.body.username}, function(err, user) {
if( err ) {
console.log("Login fail");
}
else if (user != null) {
if (req.body.password == user.password) {
req.session.user_role = "user";
req.session.save();
res.send({redirect: "/"});
} else {
req.session.user_role = "null";
console.log("Wrong login");
res.send({redirect: "/"});
}
}
});
And the app.get
should look like:
app.get('/', function(req,res){
redis.get('sess:' + req.session.id, function(err, result){
console.log("Get session: " + util.inspect(JSON.parse(result),{ showHidden: true, depth: null }));
if ((req.session.user_role == "user")) {
console.log("Logged in");
} else {
console.log("Logged out");
}
});
});