Whats happening :- I am using connect-mongo to store user session. As far as I read, we can store multiple user session in db as long as server is not restarted(?). I have a login page and whenever user logs in I store email address in session. I can see an entry created in mongodb. Server is still running and log-in with different credentials using incognito tab, I see the previous entry is deleted and replaced by new user. Hence at any time, there is just one recently logged in user in db.
What I want :- I want to store sessions for each user who has logged in. And when one logout, I check email address of log out request against db entries and delete that session. So my server.js contain this code :-
var cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongo')(session);
app.use(cookieParser());
app.use(session({
cookie: { maxAge: 1000*60*2 } ,
secret: "session secret" ,
store:new MongoStore({
db: 'express',
host: '127.0.0.1',
port: 27017,
url:"mongodb://localhost:27017/db",
collection: 'session',
auto_reconnect:true,
resave: true,
saveUninitialized: true
})
}));
apiRoutes.post('/login', function(req, res) {
User.findOne({
email: req.body.email
}, function(err, user) {
if(!err)
req.session.email = req.body.email;
return res.json({ success: true ,message:"Session saved",status:200});
});
});
apiRoutes.post('/logout',function(req,res){
mongoose.connection.db.collection('sessions').find({session.email:req.body.email}, function(err, data) {
if(err){
console.log("Error");
}
else{
//delete entry
}
})
});
via user2714823
No comments:
Post a Comment