2015-01-08 18 views
1

我查看了文檔並做了一些搜索,但我沒有看到全能用戶(超級用戶)級別的選項,或者如何創建一個選項。如何將全能用戶級別添加到權威

有沒有人看到或創建了這樣做的原因?即時通訊認爲它可能會綁定到核心認證系統,但我不知道該在哪裏搭配。

許多感謝..

回答

0

要做到這一點是讓你的授權檢查對於已指定的用戶或角色返回true的唯一途徑「超級用戶」。因此,它應該是這樣的:

def update? 
    *normal authorization logic* or is_superuser? 
end 
def edit? 
    *normal authorization logic* or is_superuser? 
end 
#etc... 

private 

def is_superuser? 
    # configure how to determine who the super users are and return true/false 
end 

您可以定義在ApplicationPolicyis_superuser?私有方法假設你繼承了應用策略類一級的政策;否則,您需要在每個策略中定義它。

+0

感謝nikkon266 ..我有一種感覺,這是做到這一點的唯一方法。我希望我錯過了一個在Pundit中的自建方法。 –

0

我發現了一種方法,使用ApplicationPolicy的繼承一點DRYer。我使用別名訪問方法,並且在調用它們之前綁定超級用戶測試。如果用戶是超級用戶,我只需返回true即可。在初始化之前,我需要將實例方法定義爲別名。

ALIAS_PREFIX = '__original_' 

def initialize(user, record) 
@user = user 
@record = record 
[:index?,:show?,:create?,:new?, :update?, :edit?, :destroy?].each do |access_method| 
    alias_name = ALIAS_PREFIX+access_method.to_s 
    aliasing_original_method(access_method,alias_name) 
    self.class.send(:define_method, access_method) do |*args| 
    superuser? ? (return true) : send(alias_name, *args) 
    end 
end 
end 

private 
def superuser? 
    #whatever you want to define a super user 
end 
def aliasing_original_method(old_name, new_name) 
self.class.send(:alias_method, new_name, old_name) 
self.class.send(:private, new_name) 
end 

而在[AnyFile]政策我做的:

def initialize(user, record) 
super(user, record) 
end 

這將確保在子策略的每個方法的真實回報。

[更新]

第一個解決方案是有點亂,而我的紅寶石(和最後期限)知識不允許我去更遠推動它。無論如何,我找到了另一種方式。由於我總是改變用戶的角色,所以我在ApplicationPolicy中實現了一個for_roles方法。

def for_roles(*args,&block) 
    return true if superuser? 
    if args.include?(:all) || (@user.role_symbols & args).any? 
     block.call 
    else false 
    end 
end 

然後,在任何政策,比如,你可以做

for_roles(:client_admin,:technician) do 
    #any rule computation, DB request you want 
end 
#or 
for_roles(:all) do 
    #any rule computation, DB request you want 
end 
+0

我仍然在尋找範圍... – hachpai

+0

第一次打電話很好,第二次打電話時我有一個無限循環。 – hachpai

相關問題