6

目标

我想做的事:

  • 为用户创建会话
  • 为套接字创建会话 ( socket.io)
  • 用于passport.js验证登录和socket会话。

笔记

我已经安装MongoStorepassport.socket.io npm's. 我可以登录并设置登录cookie用户的(connect.sid


问题

如何设置系统来存储socket会话并将它们与用户耦合session


代码

应用程序.js

  /* The usual express setup */
  passport = require('passport'),
  LocalStrategy = require('passport-local').Strategy,
  User = require('./models/user.js'),
  MongoStore = require('connect-mongo')(express);

app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.session({
    secret: 'chuck norris', 
    store: new MongoStore({db: User.name}, // the db's name
        function(err) {
          console.log(err || 'connect ok!');
        })
  }));
  app.use(express.methodOverride());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);

app.js(护照部分)

passport.use(new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password'
  },
  function(username, password, done) {
    User.findOne({username: username}, function(err, user) {
      if(!user) {
        return done(null, false, {message: 'Incorrect Username!'});
      }
      if(!user.validPassword(password)) {
        return done(null, false, {message: 'Incorrect Password!'});
      }
      return done(null, user);
    });
  }
));


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

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

app.post('/',
  passport.authenticate('local'),
    function(req, res) {
      res.redirect('/home/'+req.user.username);
    });

app.js(socket.io 部分)

io.set('authorization', passportSocket.authorize({
  key: 'connect.sid',
  secret: 'chuck norris',
  store: /* Not entirely sure what goes here */
  fail : function(data, accept) { accept(null, false); },
  success: function(data, accept) { accept(null, true); }
}));


io.sockets.on('connection', function(socket) {
  console.log('User Connected: ' + socket.handshake.user.username);
});
4

1 回答 1

10

您将新的内存故事对象实例存储到一个变量中,然后像这样将它传递给 express 和 socket io。(请注意,我们使用的是不同的商店,但从理论上讲,只要您以正确的方式传递控制权,您使用哪家商店并不重要)...

var ...
,MemoryStore = express.session.MemoryStore
,sessionStore = new MemoryStore();

然后在 app.configure 你...

app.use(express.session({store:sessionStore,secret:'secret',key:'express.sid'}));

最后在 socket.io 中配置

io.configure(function (){
io.set("authorization", passportSocketIo.authorize({
    key:    'express.sid',       //the cookie where express (or connect) stores its session id.
    secret: 'secret', //the session secret to parse the cookie
    store:   sessionStore,     //the session store that express uses
    fail: function(data, accept) {
        // console.log("failed");
        // console.log(data);// *optional* callbacks on success or fail
        accept(null, false);             // second param takes boolean on whether or not to allow handshake
    },
    success: function(data, accept) {
      //  console.log("success socket.io auth");
     //   console.log(data);
        accept(null, true);
    }
}));

如果您已正确执行此操作并且您的用户成功通过身份验证,那么您应该能够访问握手对象上的会话数据。

console.log(socket.handshake.user.username);
//or sometimes it might be...
console.log(socket.handshake.user[0].username);

希望有帮助。

于 2013-02-28T00:31:08.133 回答