Invalidate all user sessions using express-sessions and knex - node.js

I have inherited a Express site which needs some updating. There is a route for resetting password, but I need to invalidate all the users sessions when this happen and allow for auto login on the current browser at the same time.
I'm kinda new to Express, so can anybody point me in the direction of a guide?
Setting up of sessionStore:
const sessionStore = knexSession(session)
const store = new sessionStore({
knex: db
})
app.use(session({
secret: sessionKey,
resave: false,
saveUninitialized: false,
store,
cookie: {
maxAge: null,
httpOnly: true,
secure: app.get('env') !== 'development' || app.get('port') === 443,
}
}))
Resetting password:
let data = {
password,
token: null,
expires: null
}
return models.user.update(user.id, user.id, data)
.then(_ => {
//reset session user sessions
//only invalidates the current session
req.logout()
req.session.destroy(function (err) {
res.clearCookie('connect.sid')
res.redirect('/')
});
})

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?

Express Session lose data before cookie expires

I'm using express-session with redis in my NodeJS Backend.
let redisClient = redis.createClient(6380, process.env.REDISCACHEHOSTNAME, {auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
app.use(session({
store: new RedisStore({ client: redisClient }),
saveUninitialized: false,
secret: process.env.secret,
resave: true,
cookie: {
maxAge: 1 * 1 * 60 * 60 * 1000
}
}));
On login I store some user details in the session:
req.session.user = result;
And I build a middleware, which log my current session and refresh it on each request:
isOnline = (req, res, next) => {
console.log(req.session);
if (!req.session.user) {
return res.status(401).json({ result: 'Keine Session vorhanden', status: 'failure' });
}
req.session.touch();
next();
};
The extending of my cookie is working well. The cookie expiration datetime is everytime reset to 60 minutes from the request time. Which I can see by the console.log:
Session {
cookie: {
path: '/',
_expires: 2022-03-07T18:46:30.727Z,
originalMaxAge: 120000,
httpOnly: true
},
user: { ... }
}
The issue is, that my user data are lost after 60 minutes. So the cookie itself refreshs, but not the data. So how I can avoid this?

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
}));

Passport's 'req.user' becomes undefined sometimes

I am using passport for authorization and I am saving the session in mongodb using 'connect-mongo-session' module. I noticed that after sometime when I try to login the req.user object becomes undefined, although the session object is present in the database and passport and session details are present in the req object. Here is my session setup:
let store;
if(env === "development")
store = new MongoDBStore({ //Allows session to be stored and retreived even when server restarts.
uri: config.db,
collection: 'mySessions'
})
else {
store = new MongoDBStore({ //Allows session to be stored and retreived even when server restarts.
uri: config.db,
collection: 'Cosmos'
})
}
app.use(session({
store: store,
saveUninitialized: true,
resave: true,
secret: config.app.sessionSecret
}));
app.use(passport.initialize());
app.use(passport.session());
and here is the code responsible for serializing and :
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Use Passport's 'deserializeUser' method to load the user document
passport.deserializeUser((id, done) => {
User.findOne({
_id: id
}, '-password -salt', (err, user) => {
done(err, user);
});
});
I was able to solve the problem by changing saveUninitialized to false and resave to false, so it looks like this now:
app.use(session({
store: store,
saveUninitialized: false,
maxAge: 1000 * 60 * 60 * 84, // I added this just in case
resave: false,
secret: config.app.sessionSecret
}));

Resources