尝试与passport.session分享io.request.session时出现问题

时间:2018-03-14 08:47:06

标签: node.js socket.io passport.js

我的设置:

护照:

基本序列化,反序列化用户:

passport.serializeUser(function(user, done) { //serialize user
    done(null, user.id);
});

passport.deserializeUser(function(id, done) { // deserialize user
    User.findById(id, function(err, user) {
        if(err) {
            console.error('There was an error accessing the records of' +
            ' user with id: ' + id);
            return done(err);
        }
        return done(null, user);
    })
});

使用local-login。

SessionMiddleWareStore和应用程序配置:

sessionStore = new mongoStore({
  mongooseConnection: mongoose.connection,
  touchAfter: 24 * 3600});
var sessionMware =  session({
    name: 'socialify.sess', store: sessionStore, secret: sessionSecret, resave: false,
    saveUninitialized: true, cookie: {maxAge: 1000 * 60 * 60 * 24},
    secret: "eknfdjsnfjsdfn852"
});
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser());

app.use(sessionMware)

io.use(function (socket, next) {
  sessionMware(socket.request, socket.request.res, next);
});

Server.js(主文件):

var httpsServer = https.createServer(options, app)
io.listen(httpsServer);
httpsServer.listen(port, function () {
    return console.log('Socialify server listening on %s at port %d in %s mode', host, port, env);
});

问题:

我试图管理如何在所有内容之间共享会话(passport,httpRequest和socket.io) 似乎我有一个会议,但不是好的会议。因为:

var userSockets = {};
io.on('connection', function (socket) {
  console.log(socket.request.session) // is ok but doesn't contain passport array.
  var ID = socket.request.session.passport.user; // passport.user undefined.. grrr !
  userSockets[ID] = socket;
  socket.on('disconnect', function () {
    delete userSockets[ID];
    return console.log('The client has disconnected');
  });
});

当我尝试存储所有用户[id]并导出它以便可以共享时,我需要有这个id来访问http请求中的套接字。

1 个答案:

答案 0 :(得分:0)

发现错误......

我将护照cookie存储到www.mydomain.com,将io存储到mydomain.com,以便中间件为每个人创建一个商店...... 现在它解决了!