Sails.js中套接字的策略

时间:2014-01-24 20:57:53

标签: socket.io sails.js

遵守以下政策:

// 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重新连接时,我收到了相应的权限错误。

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

2 个答案:

答案 0 :(得分:2)

你需要告诉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()

答案 1 :(得分:0)

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

if (result.length > 5) {

if (!result.length > 5) {

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

相关问题