Home > other >  Passport.js - disconnect specific user
Passport.js - disconnect specific user

Time:10-06

When an administrator blocks a user, I want to disconnect his active session, so that he cannot using the application until the session ends, something like that:

app.post('/admin/users/block-user', (req, res) => {
    const { userId } = req.body;
    UsersModel.update({ status: 'blocked' }, { where: { id: userId } });
    passport.forceLogout(userId)// << ??
})

how do I do it?

CodePudding user response:

Basically you have to use connect-mongostore to store the sessions of each user when they log in. Then you use the existing mongoose connection to do a raw mongodb query to delete a specific user session based on user_id, after hitting the logout api. They will be logged out the next thing they try to do that requires user information on the site.

In app.js:

var session = require('express-session');
var MongoStore = require('connect-mongostore')(session);
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection})
}));

in my controller file:

mongoose.connection.db.collection('sessions').deleteMany({
        "session.passport.user": username
    })
  • Related