[英]Using declarative_authorization to limit results in the model
我正在使用聲明性授權 gem 來獲取 rails 項目中的權限,並且我正在嘗試根據用戶權限從 model 中限制 output。
我的縮寫授權文件如下所示:
roles do
role :supervisor
has_permission_on :people, :to => :manage_all
end
role :basic_user
has_permission_on :people, :to => :manage_subordinates
end
end
privileges do
privilege :manage_subordinates do
includes :subordinate_records
end
privilege :manage_all do
includes :all_records
end
end
在我的人 model 中,我有一個 static 方法,我想看起來像這樣
def self.supervised_by(user)
if user.permitted_to? :all_records
#return all of the records
elsif user.permitted_to? :subordinate_records
#return some of the records
else
#return none of the records
end
end
使用 with_permissions_to 或 allowed_to 的文檔中的 AuthorizationInModel object 似乎對此提供了支持。 我無法根據文檔弄清楚如何使用這些功能,或者如何返回當前用戶對當前 model 的權限列表。
有任何想法嗎?
我找到了使用內置 if-attribute 方法的替代解決方案。 我最初遠離它是因為我使用的是非命名空間模型和命名空間控制器和視圖。 這個結構是我正在處理的項目的原始版本的一個工件。 我的大部分工作都獲得了處理這種結構的聲明性授權。
我不清楚的主要信息是如何在部分命名空間的環境中命名權限。 The model expected the model name (:people), the controller expected the namespace and the model (:staff_people), and the views didn't care as long as you picked one. 我選擇的解決方案是使用 model 名稱並在每個 controller 中顯式設置上下文。 如果在 controller 中未設置上下文,則使用 filter_access_to 不起作用,因為它會尋找 staff_people 權限而不是正確的權限 people。
在聲明性授權配置文件中,我將完全權限授予管理員,部分權限授予主管。 person.supervised 返回其自身和所有其他受監督人員的數組。
roles do
role :administrator
has_permission_on :people, :to => [:create, :read, :update, :delete]
end
role :supervisor
has_permission_on :people do
to => [:create, :read, :update, :delete]
if_attribute :id => is_in { Person.find_by_user_id(user.id).supervised }
end
end
end
要在命名空間 controller 中訪問此信息,我使用的是 filer_resource_access。
module Staff
class PeopleController < ApplicationController
filter_resource_access :context => :people
def index
@people = People.with_permissions_to(:read)
end
我發現使用
filter_access_to :all, :with_attribute => true
不適用於需要使用 with_permissions_to 和 if_attribute 權限的方法。 我不知道為什么這是一個問題
對於不包括獲取單個記錄的 id 作為 arguments 的一部分的非標准 controller 操作,仍然需要使用 filter_access_to。 例如,如果一個名為 part_timers 的操作返回一個人員列表,那么這個解決方案似乎應該可以工作:
filter_resource_access :context => :people, :additional_member => { :part_timers => :read }
正確的解決方案是保持 filter_resource_access 原樣並為該操作添加 filter_access_to
filter_resource_access :context => :people
fitler_access_to :part_timers, :required => :read, :context => people
可能有更好的方法來做到這一點,但如果其他一切設置正確,這應該適用於您的supervised_by
方法。
def self.supervised_by(user)
if Person.new.permitted_to? :all_records, :user=>user
#return all of the records
elsif Person.new.permitted_to? :subordinate_records, :user=>user
#return some of the records
else
#return none of the records
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.