3

我正在尝试确定如何最好地授权(除了验证)用户使用 socket.io 执行特定任务。

简而言之,这是相当简单的。我首先有一个登录/密码表单,它查询数据库以确定记录是否存在,如果确实存在,那么我将用户附加到 req.session 数据。

exports.session = function(req, res){
    User.authenticate(req.body.username, req.body.password, function(err, user){
        if (user){
            req.session.user = user;
            res.redirect('/');
        } else {
            console.log("authentication failed");
            res.render('user/login');
        }
    });
};

一旦有了这个,我就可以使用中间件来授权某些请求。例如,

app.put('/api/users/:userId', m.requiresLogin, m.isUser, api.putUser);

//Middleware
exports.isUser = function(req, res, next){
  if (req.session.user._id == req.user._id){
    next();
  } else {
    res.send(403);
  }
};

但我对如何使用 socket.io 执行此操作有点困惑。假设我有一个事件侦听器,它会根据用户的配置文件 JSON 对象更改数据库中的用户配置文件。

    socket.on('updateProfile', function(data){
    // query the database for data.user._id, and update it with the data attribute
    // but only do this if the data.user._id is equal to the user trying to do this. 
    });

关于如何实现这一目标的任何建议?可以通过会话信息来完成吗?

4

2 回答 2

0

It appears as though you're using Express.
I would highly recommend Express middleware called Passport (https://github.com/jaredhanson/passport).

Using Passport, you can implement any number of strategies to authenticate users (ex. OpenID through Google, Yahoo, Facebook; OAuth through Twitter, Facebook; or local strategies (ex. email registration)).

Finally, to answer your precise question: a project called passport.socketio is amazing in that it plays well with the above authentication strategies and, if you set Express's session, it will play well with that too. (https://github.com/jfromaniello/passport.socketio)

于 2014-09-16T20:52:44.140 回答
-2

请参阅此处的文档:

https://socket.io/docs/migrating-from-0-9/#authentication-differences

io.set('authorization', function (handshakeData, callback) {
// make sure the handshake data looks good
callback(null, true); // error first, 'authorized' boolean second 

});

于 2012-07-28T15:21:29.140 回答