How can I find the session Id when using express /

2019-03-10 20:23发布

If a user is already logged in and tries to login again in a new instance I'd like it to log out the other user instance. I don't want the same user to be logged in twice on my application.

Currently the session is stored in a Redis store, i'm using express / connect to handle the session storage. One of the functions available which could be used to destroy the session is as follows:

.destroy(sid, callback)

However I need to find that session id before I call .destroy(). In Redis the username is stored as a part of the session.

Question: Is it possible to query Redis to obtain the session id based on the username?

4条回答
一夜七次
2楼-- · 2019-03-10 21:00

req.sessionID will provide you the session's ID, where req is a request object.

查看更多
ら.Afraid
3楼-- · 2019-03-10 21:01

Question: Is it possible to query Redis to obtain the session id based on the username?

No. The session keys in redis are not named after the username.

Here's a thought, though: When an already logged in user tries to login again, can't you see that, in your application, and either destroy the old session immediately, or not allow them to login again?

查看更多
趁早两清
4楼-- · 2019-03-10 21:06

For recent readers;

Connect middlewares are not included in Express since version 4.

So in order to have req.sessionID work you must do following:

  1. Make sure you have cookie-parser abd express-session modules inside your package.json. If it's not added, add them:
npm install express-session --save
npm install cookie-parser --save
  1. Be careful about the order while requiring them in your app.js file and add required configuration parameters.
var cookieParser = require('cookie-parser');
var session = require('express-session')
app.use(cookieParser());
app.use(session({
    secret: '34SDgsdgspxxxxxxxdfsG', // just a long random string
    resave: false,
    saveUninitialized: true
}));
  1. Now you should be using req.sessionID and req.session.id.
查看更多
干净又极端
5楼-- · 2019-03-10 21:09

Store the SID with the account, when the user logs in during the database validation of the user account call .destroy(sid, fn), then update the SID in the database with the current SID of the user.

In my case using MongoDB this is how i've done it:

app.post('/login', function(req, res)
{
  var sid = req.sessionID;
  var username = req.body.user;
  var password = req.body.pass;

  users.findOne({username : username, password : password}, function(err, result)
  { 
    ...
    sessionStore.destroy(result.session, function(){
       ...
       users.update({_id: result._id}, {$set:{"session" : sid}});
       ...
    }
    ...
  }
}
查看更多
登录 后发表回答