2014-01-24 163 views
1

插座具有以下策略:政策在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

您需要告訴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

FYI:在sails.js的未來版本Model.unsubscribe將被棄用的與req.leaveModel()取代。

+0

直視前進 - 謝謝! – pex

0

首先,如果您的策略是試圖限制的模型5號,它應該是:

if (result.length > 5) {

if (!result.length > 5) {

其次,設置策略ModelController的find操作不會停止創建模型。您需要將其放在create操作上。

+0

這不是關於限制創造,而是關於接受/獲取更新。 – pex