与socket.io授权 [英] authorization with socket.io

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

问题描述

我试图确定如何最好地授权(除认证)用户使用socket.io执行特定的任务。

I'm attempting to determine how best to authorize (in addition to authenticate) a user to perform a specific task using socket.io.

在EX preSS,这是相当简单的。我首先有一个查询数据库,以确定是否记录存在一个登录/密码的形式,如果它确实存在,那么我将用户连接到req.session数据。

In express, this is fairly straightforward. I first have a login/password form that queries the database to determine if the record exists, and if it does exist, then I attach the User to the req.session data.

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

一旦我有这个,我可以用中间件授权的请求。例如,

And once I have this, I can use middleware to authorize certain requests. For example,

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对象。

But I'm a bit confused about how to do this using socket.io. Say I have a event listener which alters a user's profile in the database, given that user's profile JSON object.

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

任何建议,如何实现这一目标?可以通过它的会话信息,怎么办?

Any suggestions as how to achieve this? Can it be done through the session information?

推荐答案

您可以挂接到的授权以socket.io功能如下:

You can hook into the authorization function for socket.io as follows:

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

这篇关于与socket.io授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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