我试图确定如何最好授权(除了验证)用户使用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.
});
作为如何实现这一目标的任何建议?它可以通过会话信息完成吗?
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
请注意,随着socket.io版本1.0和更高版本的改变,这已经发生了变化。关于如何将上面的代码迁移到新的范例的解释如下:http://socket.io/docs/migrating-from-0-9/#authentication-differences – Nathan 2015-07-28 14:11:35