2016-03-03 81 views
0

我有一個模型:api/models/Agency.jsSailsJs保護藍圖與政策

attributes: { 

     // attributes for agency 

     // One agency can have many owners 
     owners: { 

      collection: 'user', 
      required: true, 
      via: 'agencies' 
     }, 

     employees: { 

      collection: 'user', 
      via:   'employer' 
     } 
    } 

該型號具有許多與許多的用戶關係;許多用戶可以擁有許多代理商。

我想用政策保護代理機構的藍圖控制器(AgencyController.js),稱爲isOwner.js;這可以確保用戶在允許他們進行編輯之前是該機構的所有者。我已經根據Sails.js docs中的示例創建了該策略,其中我試圖確保userId(在會話中找到)是資源的所有者。

api/policies/isOwner.js

module.exports = function(req, res, next) { 

    var userId = req.session.passport.user; 

    req.options.where = req.options.where || {}; 

    req.options.where.owners = userId; 

    return next(); 

}; 

然後在我的config/policies.js文件我已經添加了以下內容:

AgencyController: { 

      destroy: ['isOwner'], 
      update: ['isOwner'] 
    }, 

這是行不通的。我認爲這是因爲兩種模式之間存在着多對多的關係。我的問題是我可以創建一個可以查詢多對多關係的策略嗎?或者只有通過一對多的關係纔有可能?

謝謝。

回答

0

我找不到一種很好地保護藍圖方法的方法,因此我創建了一個檢查用戶是模型所有者的服務,然後在我的控制器中擴展了更新和銷燬方法。

API /服務/ isOwner.js:

/** 
* Only allow access to models if they are the owner. 
* Assumes an attribute called owners on the model and assumes it has a relationship that can be queried through the 
* 'populate' waterline method. 
*/ 
var actionUtil = require('sails/lib/hooks/blueprints/actionUtil'); 
var _ = require('underscore'); 

/** 
* @param req 
* @param res 
* @param is {function} called if the user is the owner 
* @param isnt {function} called if the user is not the owner. If not present will redirect 403 not authorised. 
*/ 
module.exports = function isOwner(req, res, is, isnt){ 

    var ownerEmail = req.options.where.owner; 
    var Model = actionUtil.parseModel(req); 

    isnt = isnt || res.forbidden; 

    is = is || function(){ 

      sails.log.warn('No callback defined for isOwner'); 
      res.ok(); 
     }; 


    Model.findOne({ id: req.params.id }).populate('owners').exec(function(error, model){ 

     var canEdit = _.find(model.owners, function(owner){ 

      return owner.email === ownerEmail; 
     }); 

     canEdit ? is() : isnt(); 
    }); 
}; 

API /控制器/ AgencyController.js:

var update = require('sails/lib/hooks/blueprints/actions/update'); 
var isOwner = require('../services/isOwner'); 

module.exports = { 

    /** 
    * Override the default blueprint update behaviour so only the owner can update a record. 
    * 
    * @param req 
    * @param res 
    */ 
    update: function(req, res){ 

     isOwner(req, res, update); 
    } 
}; 

不覺得這樣做的最好的方式,但它是唯一的方法我能想到。只是以爲我會在這裏分享它,只是因爲有人遇到同樣的問題或者有人有更好的解決方案。