Node express mono + session management + store user details into session table - node.js

I am using node js with express also mongoDb using.. When I loggedIn the session storing into sessions collection(table) like below
{_id: "1233..",session : "{ "cookie" : { "originalMaxAge" : null , "expire3s" : null, "httpOnly" : "true", "path": "/"} }, expires : 2020-03-27 }
But I am trying to achieve how many browsers/device loggedIn same user at the same time.. How we can store user details like user-id or email store into session table?
If i stored those details then I will get the total count of the records to the particular user.. Or have any best approach to do this..
import session from 'express-session';
import passport from 'passport';
app.use(passport.initialize());
app.use(session({
secret: config.secrets.session,
saveUninitialized: true,
resave: false,
store: new MongoStore({
mongooseConnection: mongoose.connection,
db: 'test'
})
}));

Related

Chrome bug "Unable to parse ciphertext object!" with connect-mongo 4.6.0 for Node.js to store Express session data

In connecting my MongoDB to Node.js for storing session information by connect-mongo v.4.6.0, when testing my app in Chrome (v.106.0.5249.121), browser sends me "Unable to parse ciphertext object!". Instead, in Brave and Edge all works and session data are ciphered and stored correctly.
This is my MongoStore and Express session configuration:
const MongoStore = require('connect-mongo');
const mongoStore = MongoStore.create({
mongoUrl: urlDBLocale,
crypto: { // this parameter causes "Unable to parse ciphertext object" in Chrome
secret: process.env.mdbssecret,
},
touchAfter: 24 * 3600
});
mongoStore.on("error", err=>console.log('MongoDB Session Storage error:', err));
const sessionOptions = {
cookie: {
httpOnly: true,
secure: false,
maxAge: 3600000
},
name: 'whatever',
saveUninitialized: false,
secret: process.env.sessionSecret,
store: mongoStore,
resave: false
};
app.use(session(sessionOptions));
While the above simply doesn't work in Chrome, no errors are given by Brave and Edge and here you can see that sessions are stored correctly in MongoDB when I try with those two browsers respectively:
> db.sessions.find()
{ "_id" : "tAD7alup3KP_8qzkBUkAQtgplM3QYjO_", "expires" : ISODate("2022-11-03T17:54:03.169Z"), "lastModified" : ISODate("2022-11-03T16:54:03.169Z"), "session" : "MIICkwSCAThtV0dUNGZKcGYrVFlPeURDbDlTT3VqcjdFQWswRURYdm1TQXFTL1RQT3dZVzBmYU5PajRnblU0bDNuZDB3T08xTFhhbHlncnZsWUwrMHZvdWEyUzJOYUd3Wm5pUnYyOUR6SnFhODAwTXFLN3NFWG5PandKdkZmQTlvZUZZRURUVUJaeDRiYWN4T3psbXFWaFFFUlNEZzNjMFNIdnJmTXhYc2xidTkwNlovcXlTaEVGaWppRml5cEFMNlFHS2ViM1A5RElVZi9HNHRrNkVDcFpReVlGaWp1U2ZxbXNRZS9rd0NnclRua2QyYTRSTmxlT29vc1F4WUVvcnFzQzYxanJUVDVUV21laWhHTzdYeUx4VFU2ejZYZlhyNnRHMHJ4WUxQUFg3ZWdUWXYxdGlvK1JrOVVHM3Z3PT0EWHJ5VXFFM3k2MEFab2JEU0orWG9lMjZMM1NEeG5HVUxaQlc1Q001VGtSdHdmZGhLWGlaNmhUVUFicmcwRzUzTk53MGVlMXpkaXRnRlhtS1JwU1k5aTFnPT0EDPUOA18tvmYDuzHydQSBgO4uqYbtOWt3/nWokZk2iHwCV2/L0dTDpVoHEfvZmFLQ3xlEUV4213b8HeyCnAjnz03TAf8f1p3ZEbEu9JqpnsGmM7T6fiN/1O8hOwRzRDwFyJKcT/+PUUTiaDda55FjinqNn9imwrdVl4kMCmkfcxafgaJE/aaj9nznUeJ/eE7SBBCYIePm5C0f9mYS8jJV4MtJBFhKQ3VHZlBYSUFGbEdMUXV5SFpuMnJORnQwUWRGb0ZydHpseHRleWh6QWFwaVNjdVBNcTJ0M0pReEZKdzBQWXg3N255Vit3czdzMjU4ZGJxamxMZDc4dz09" }
{ "_id" : "pUX3QV5yLOEImcckJdUO1jir_tkAFPXF", "expires" : ISODate("2022-11-03T17:56:28.397Z"), "lastModified" : ISODate("2022-11-03T16:56:28.398Z"), "session" : "MIICkwSCAThpL0RGTjJwTXRxcGtVdTBycGNkRVhVajhRRzhqanV2aVhXZjlPQ1pWclhEYkgwTkZGdms0T0EwSGpJSmlrRUJqcWNkMTMzR3dzdGgzUlhza1JtZWdCSGZGUVFvSWRmdXU1T3lXZEJkUC90bEEvcStuTnhnOFNiek96MXRDLzF0Nmx0dlNkaTEvSmx2SlRDMzZHdGdlQXZSKzJTbEZBUjVFaHlaYXhjbklLWkpBcm01b3ZWbWJzMUNFSERPSVZZKzJrU0dLT2JlOGN0aXZRRUZsYTlOcHloZm1JSEZiZk80emdRenRZdVN4WFMwZlVIbnFpMTEvdW1UbkZjRk9NN3IxRWswVjV3RW1mUGFDUTJsZ0NCVWUzMXg4TVFFN1ZGVUt0eDFWWURlbDZWMlRJd2hDMlFRZitBPT0EWHBNKzBrQnZkZkF3dnhIZWxMTUxHNjNVTWZyMVEvME9VaDVJdW03TTJ6aVpGUWFJVE8vRUNaTXlqQ3NKSFFxSmw1ZGZkN1hmUDJLTFFSK2xmeVhPK0JnPT0EDIMy9uY8STWtjjUHuASBgPuj70V3HlFuaXEYk7HNYTGy6dIbrLhGkW5Ra3xTgekdMQeAdmB4xmmTnIu099LCkNeuSiZZvSLrxz6Oj39ZJXB5GTGlBVbpoEFc3Iaf12jPBhuX8KkXtHGV4y+UsJw+qg/BC0lzfAKMpa3iGjdLgo9vwobrN03MyEKRBUHSEyQLBBAS7AfNVrZPfHqmyGyO4g68BFh2cFprY0taekQzZ0Q4Tjd5MEcweHFwQ2dwMTJHb1dsSk04clRURnp5Rmhpc1o1WjlkQ0pyeVBTTVNhUCthS1g1d2hFMDlpbS9veGpHUGhzYkUxYS8xZz09" }
What should I do? Try a previous version of connect-mongo - and if yes, which one and with what configuration in Node.js - or is there a solution to this Chrome bug?
Thanks!
Problem solved itself in Chrome's version 107.0.5304.88.

Express Session expiry vs First Time Loging in

How to differentiate whether the session expired or is it the first time logging in.
I am setting the session like this and storing the data in express-mysql-session.
const sessionStore = new MySQLStore({}, connection);
// session
const adminSession = session({
secret: process.env.ADMIN_SECRET,
resave: false,
saveUninitialized: false,
store: sessionStore,
name: "adminSession",
cookie: {
maxAge: 600000,
secure: false,
},
});
app.use("/api/admin", adminSession, adminRoutes);
//admin login
app.post("/api/admin/login",(req,res)=>{
req.session.adminAuthenticated = true;
});
By simply checking if there is req.session.adminAuthenticated, I can know if admin is logged in or not. But how can I know if the admin had already logged in earlier but the session expired.
Any help with this.

How to check if a given session ID exists in the database mongodb?

I am generating custom session IDs using the genid function with express-session and connect-mongo:
app.use(session({
store: new MongoStore({
mongooseConnection: db,
clear_interval: 60
}),
secret: 'someSecret',
name: 'secret',
genid: function(req){
return uuid4();
},
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: true,
maxAge: 60*1000
}
}));
Id generated by uuid4(), I know that it has uniqueness, but not always, I want to know 100% that there is no such ID in the database, I want to check every time this ID is generated, whether such ID already exists in the database. I dug the whole Internet, but did not find anything about how to check that a session with such an ID already exists. I would like to implement it in genid function, like this:
genid: function(req){
let newID = uuid4();
//check if a session with this `newID` exists in the database
}
I don't know how to access the session ring generated by connect-mongo. Sorry for my English. I would be grateful if someone could help! :)

ExpressJS / connect-mongo update session

I'm using connect-mongo to store PassportJS sessions.
My conf in server.js is:
app.use(session({
name: 'Example',
secret:'exampleasd',
saveUninitialized: false,
resave: false,
cookie: { maxAge: 1000*60*60*2 },
store: new MongoStore({
url: 'mongodb://localhost/example',
host: 'localhost',
collection: 'user-sessions',
autoReconnect: true,
clear_interval: 3600
})
}));
My problem is that when I update the users data like the username or email I have to logout and login to get the changes.
I've already tried with req.session.save and req.session.reload, no luck.
Can I update session fields without logout?
Thanks!
You have to use req.user to properly update req.session.passsport.user so:
if you want to change the username just do:
req.user.username = newUsername;
req.session.save(function(err){
//msg here
});

connect-mongo cross-domains session issue

I am having a problem with sessions across sub-domains
I use connect mongo like so:
app.use(session({ // req.session is populated
secret: 'xxxxxx',
saveUninitialized: true,
resave: true,
store: new MongoStore({
db: 'nnn'
}),
cookie: {
path: '/',
maxAge: new Date(Date.now() + time),
domain : 'mydomain.com' ,
httpOnly: true
}
}));
However, when I redirect to a subdomain xyz.mydomian.com the session is invalidated. Can anyone recommend a strategy for getting cross domain login to work with connect-mongo ?

Resources