会话与express.js + passport.js [英] Sessions with express.js + passport.js

查看:117
本文介绍了会话与express.js + passport.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标

我想做什么:


  • 为用户创建会话

  • 为套接字创建会话( socket.io

  • 使用 passport.js 验证登录名和套接字会话。

  • Create a session for the user
  • Create a session for the socket (socket.io)
  • Use passport.js to authenticate the login and socket sessions.

注意

我已经安装了 MongoStore passport.socket.io npm的。我可以登录并设置登录用户的 cookie connect.sid

I have installed MongoStore and passport.socket.io npm's. I can login and set the cookie of the user logged in (connect.sid)

QUESTION

如何设置系统存储 socket 会话,并将它们与用户的会话相结合

How do I setup the system to store socket sessions and couple them with the session of the user?

代码

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(护照部分) p>


app.js (the passport part)

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)


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


推荐答案

您将新的内存故事对象实例存储到变量中并将其传递给express和socket io,如此。
(请注意,我们正在使用不同的商店,但在理论上,只要您通过正确的方式控制正确的方式,您使用的商店就无关紧要)...

You store your new memory story object instance into a variable and pass it in to both express and socket io like so. (be aware that we are using different stores but in theory it should not matter what store you use as long as you pass off control the proper way)...

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

然后在app.configure中...

then in app.configure you...

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

最后在socket.io中配置

and finally in 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);
    }
}));

如果您已经正确完成并且您的用户成功验证那么你应该可以访问握手对象上的会话数据。

If you have done this correctly and your user successfully authenticates you should then be able to access the session data on the handshake object.

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

希望有所帮助。

这篇关于会话与express.js + passport.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆