使用express.js + passport.js的会话

时间:2013-02-26 15:32:19

标签: express socket.io passport.js

目标

我想做什么:

  • 为用户创建会话
  • 为套接字(socket.io
  • 创建会话
  • 使用passport.js对登录和socket会话进行身份验证。

备注

我已安装MongoStorepassport.socket.io npm's。我可以登录并设置登录用户的cookieconnect.sid


问题

如何设置系统以存储socket个会话并将其与用户的session结合使用?


代码

app.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 part)

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);
});

1 个答案:

答案 0 :(得分: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 configure

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);

希望有所帮助。