【问题标题】:Policies for sockets in Sails.jsSails.js 中的套接字策略
【发布时间】:2014-02-16 00:27:54
【问题描述】:

有以下政策:

// file: api/policies/foo.js
module.exports = function(req, res, next) {
  Model.find().done(function(err, result) {
    if (result.length > 5) {
      return res.forbidden();
    } else {
      return next();
    }
  });
};

// file: config/policies.js
module.exports.policies = {
  ModelController: {
    'find': 'foo'
  }
};

以及默认的ModelModelController。我现在在两个客户端上执行以下操作:

// client 1
socket.get('/model', function(result) { console.log(result) });

// client 2
var i = 10;
while (i--) { socket.post('/model', { foo: 'bar' }); }

客户端 1 实际上接收了 10 个更新,尽管他只被允许接收 5 个。 通过socket.get 重新连接时,出现相应的权限错误。

我的问题: 在通过套接字发送更新之前检查权限的最佳做法是什么?

【问题讨论】:

    标签: socket.io sails.js


    【解决方案1】:

    你需要告诉 socket.io 离开它正在广播的房间。 这可以通过使用Model.unsubscribe(req.socket); 来完成。

    // file: api/policies/foo.js
    module.exports = function(req, res, next) {
        Model.find().done(function(err, result) {
            if (result.length > 5) {
                Model.unsubscribe(req.socket);
                return req.forbidden();
            } else {
                return next();
            }
        });
    };
    

    文档:socket.io rooms

    代码:sails.js unsubscribe

    仅供参考:在以后的sails.js 版本中,Model.unsubscribe 将被弃用,取而代之的是req.leaveModel()

    【讨论】:

      【解决方案2】:

      首先,如果您的政策试图将模型数量限制为 5 个,则应该是:

      if (result.length > 5) {

      不是

      if (!result.length > 5) {

      其次,在 ModelController 的 find 操作上设置策略不会阻止模型的创建。您需要将其放在 create 操作上。

      【讨论】:

      • 这不是限制创作,而是接收/geting 更新。
      猜你喜欢
      • 2011-12-21
      • 2011-06-08
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2011-07-23
      • 2014-04-20
      • 1970-01-01
      • 2015-03-09
      相关资源
      最近更新 更多