express-session has different results based on browser. Why? - node.js

I'm reading https://www.npmjs.com/package/express-session and am in a world of confusion.
The store I'm using is https://www.npmjs.com/package/express-mysql-session
var options = {
host: 'localhost',
user: 'root',
password: 'somepass',
database: 'somedb'
};
var sessionStore = new SessionStore(options);
app.use(session({
genid: function(req) {;
return genuuid(function(err, uuid){
return uuid;
});
},
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: sessionStore,
resave: true,
saveUninitialized: true
}));
Consider this route
router.get('/generateUser', function (req, res, next) {
if (req.session.user == null) {
req.session.user = "d";
} else {
req.session.user += "1";
}
res.render('index', {title: 'Express', userId: req.session.user});
});
On a normal chrome browser, each visit to /generateUser is seeing the previous user value. So 5 refreshes and I have a user value of "d11111". But now if I do this incognito or on safari the value is always "d". What are these browsers doing differently?

Related

express-session cookie still exist despite logout

I have this logout route with expressJS using express-session :
router.post('/logout', (req, res) => {
req.session.user = null;
req.session.destroy((err) => {
if (err) {
return res.status(400).end();
} else {
return res.status(200).end();
}
});
});
Although the user is logged out Correctly and the sid changes, The cookie still exists!! which freaking me out.
I want to completely remove the cookie to calm my heart.
This is the config of the express-session package
app.use(
session({
store: new MariaDBStore({
pool: require('./config/db_pool')
}),
name: 'sid',
secret: process.env.KEY,
saveUninitialized: false,
resave: false,
cookie: {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'development' ? false : true
}
})
);
I git the answer from #Joe comment above and this like
Answer from here
using this close completely removes the cookie.
the options of res.clearCookie are not optional .
res.clearCookie('sid', { path: '/' });

Persist expired session data into new session in express js

const adminSession = session({
secret: process.env.ADMIN_SECRET,
resave: false,
saveUninitialized: false,
store: sessionStore,
name: "adminSession",
cookie: {
maxAge: 600000,
secure: false,
},
});
app.use(adminSession());
app.get("/sessionViews", function (req, res, next) {
if (req.session.views) {
req.session.views++;
res.send(`Number of view: ${req.session.vies}`);
} else {
req.session.views = 1;
res.send(" No views");
}
});
Here after the session is expired, req.session.views value is also gone. And new session will be generated with req.session.views=0.
That's how we create the number of views in the certain page, isn't it?
How to keep value persistent with another session?

How to create a node.js session with express?

i am using nodejs and mongodb, the problem is that my express session doesn't work
Frontend code:
$(document).on('click', "#signin", function(){
$.ajax({
type: "POST",
url: "/conectare",
data: {username: $(".username").val(), password: $(".password").val()},
success: function(res){
atentionare(res); // this is a function that displays a message on the screen
load_signin_options(); // this is a function that appends more buttons on my navbar
}
})
});
and my server code:
app.post('/conectare', function(req,res ){
var user = req.body.username;
var pass = req.body.password;
MongoClient.connect(uri, function(err,db){
var dbc=db.db("mydb");
dbc.collection('user').find({username: {$eq: user}}).toArray(function (err, result){
let len= result.length;
if( len == 0 ){
res.send("User does not exist");
}
else{
var a = result[0];
if(pass===a.password){
res.send("successfully connected");
req.session.username = user;
console.log("parola e buna");
}
else{
res.send("Incorrect password");
}
}
});
db.close();
});
});
this is my session, i also installed express-session
app.use(session({
secret: 'secret',
resave: true,
cookie: { maxAge: 0 },
saveUninitialized: true
}));
i tryed to follow this post How to create sessions in node.js
but and i found out that my session doesnt work, but i don;t understand how to make it work
You set your cookie to maxAge = 0, meaning you're never creating the cookie needed to hold the sessionId.
Change to:
app.use(session({
secret: 'secret',
resave: true,
cookie: { maxAge: 3600 },// one hour
saveUninitialized: true
}));

Creating session within monk's findOne command

This simple bit of code illustrates the problem: The second session does not save. How can I make this work?
router.post('/users/login', function (req, res) {
var db = req.usersDb;
var users = db.get('users');
req.session.test = "This works";
req.session.save();
users.findOne({ username: req.body.username}).on('success', function (doc) {
console.log(doc.email); //this works
req.session.email = doc.email; //This not working
req.session.save();
});
});
Changing the express-session 'resave' property in the options object to false solved the problem.
example:
app.use(session({ genid: function(req) { return guid() }, secret: 'secret', resave: false, saveUninitialized: true }))

node+express+redis persistent session/remember me

I am developing in node and express. And I am trying to make a remember me login. I am reading a lot of things on the web, but can't make it work. I don't know if there is a receipe, and if there it is, I could't find it.
I was trying with redis and express session. And is working partially.
If a restart node server, or close and reopen chrome. Session is active. So going into "/" will redirect me to "/index.html".
But if I restart the pc, I lost session. So goning into "/" will redirect me to "login"
Here some significant code from my server:
var redisClient = require('redis').createClient();
var RedisStore = require('connect-redis')(express);
app.use(bodyParser());
app.use(cookieParser());
app.use(express.session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 0,
cookie: { maxAge: (24*3600*1000*30)}, // 30 Days in ms
client : redisClient
}),
secret: 'seeeecret'
}));
app.get('/', function(req, res, next) {
res.redirect('/index.html');
});
app.post('/login', function(req, res) {
function loginSuccess() {
req.session.regenerate(function() {
req.session.user = req.body.usuario;
res.sendfile('index.html', {root: './static'});
});
}
function loginFailure(errText, errCode) {
console.log("failed to login. "+errCode+": "+errText);
res.redirect('/login');
}
//Imap email login (the user will authenticate with his email, end email's pass)
checkPassword(req.body.usuario, req.body.server, req.body.password, loginSuccess, loginFailure);
});
function restrict(req, res, next) {
if (req.session.user) {
next();
} else {
req.session.error = 'Access denied!';
res.redirect('/login');
}
}
It seems that you have the "cookie" in the wrong place:
app.use(express.session({
cookie: { maxAge: (24*3600*1000*30)}, // <-- where it belongs
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 0,
client : redisClient
}),
secret: 'seeeecret'
}));

Resources