2012-07-28 106 views
3

我试图确定如何最好授权(除了验证)用户使用socket.io执行特定的任务。授权与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. 
    }); 

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

回答

0

您可以挂接到authorization功能socket.io如下:

var io = require('socket.io').listen(80); 

io.configure(function(){ 
    io.set('authorization', function (handshakeData, callback) { 
    // findDatabyip is an async example function 
    findDatabyIP(handshakeData.address.address, function (err, data) { 
     if (err) return callback(err); 

     if (data.authorized) { 
     handshakeData.foo = 'bar'; 
     for(var prop in data) handshakeData[prop] = data[prop]; 
     callback(null, true); 
     } else { 
     callback(null, false); 
     } 
    }) 
    }); 
}); 
+0

IP是用户来源的BAD指标。一个简单的例子是企业设置,许多用户使用相同的网关+ IP上网。与家庭路由器相同。 我正在为NodeJS + express + Backbone.JS + socket.io实现一个框架,我在这里使用了我自己放置在cookie上的令牌,所以你可以通过express写入,并在稍后通过socket.io读取。 如果您需要灵感,请随时在这里查看我的项目http://github.com/romansky/circuits – Roman 2014-05-03 13:54:49

+0

请注意,随着socket.io版本1.0和更高版本的改变,这已经发生了变化。关于如何将上面的代码迁移到新的范例的解释如下:http://socket.io/docs/migrating-from-0-9/#authentication-differences – Nathan 2015-07-28 14:11:35

0

看来好像你使用快递。
我强烈推荐Express Passport中间件(https://github.com/jaredhanson/passport)。

使用Passport,您可以实现任意数量的策略来验证用户(例如,通过Google,Yahoo,Facebook的OpenID;通过Twitter,Facebook的OAuth或本地策略(例如电子邮件注册))。

最后,回答您的确切问题:一个名为passport.socketio的项目令人惊讶,因为它与上面的身份验证策略配合良好,如果您设置了Express会话,则它也可以很好地发挥作用。 (https://github.com/jfromaniello/passport.socketio