2013-05-03 58 views
0

我目前正在嘗試將inherited_resources和權限集成到我的Rails應用程序中。集成inherited_resources和權限

對於檢查基於資源執行控制器操作的能力,我有點卡住了。此代碼是作爲一個例子給出權威:

def edit 
    @llama = Llama.find(params[:id]) 
    authorize_action_for(@llama)  # Check to see if you're allowed to edit this llama. failure == SecurityViolation 
    end 

    def update 
    @llama = Llama.find(params[:id]) 
    authorize_action_for(@llama)  # Check to see if you're allowed to edit this llama. 
    @llama.attributes = params[:llama] # Don't save the attributes before authorizing 
    authorize_action_for(@llama)  # Check again, to see if the changes are allowed. 
    if @llama.save? 
    # etc 
    end 

由於inherited_resources的發現者被抽離,我認爲這會是不錯的也釘在authorise_action_for檢查到這些抽象的發現者。

注意權限的更新情況下的雙重檢查(可能是創建)。

回答

1

我依靠ActiveSupport::Concern來簡化模塊。我將我的疑慮存儲在下的目錄app下。我稱這一個爲inherited_resources_with_authority.rb,您可能需要修改autoload_pathsapplication.rb以從此文件夾加載文件。

module InheritedResourcesWithAuthority 

    extend ActiveSupport::Concern 

    included do 
     inherit_resources 
     authorize_actions_for :resource_class 

     alias_method_chain :resource, :authority 
     alias_method_chain :build_resource, :authority 
     alias_method_chain :update_resource, :authority 
    end 

    protected 

    def resource_with_authority 
     resource_without_authority 
     authorize_action_for(get_resource_ivar) 
    end 

    def build_resource_with_authority 
     build_resource_without_authority 
     authorize_action_for(get_resource_ivar) 
    end 

    def update_resource_with_authority(object, attributes) 
     object.assign_attributes(*attributes) 
     authorize_action_for(object) 
     object.save 
    end 

end 

我們基本上鍊重要inherited_resources'抽象方法和插入我們的授權碼在必要。最後一個是最棘手的,因爲我們不能調用我們要鏈接的原始方法,所以我們必須在這裏複製一些inherited_resources的代碼。

要使用此問題,只需從您的控制器調用include InheritedResourcesWithAuthority即可。

注意您不能在控制器上使用激活inherited_resources的類繼承方法,因爲我們已經在使用其他方法來解決這個問題。

完整的書面記錄在這裏:https://coderwall.com/p/tp5sig

建議是絕對歡迎:d

+0

請注意,你應該在這裏發佈答案的重要部分,在這個網站上,或者被刪除您的帖子風險[參見常見問題解答它提到的答案几乎不超過鏈接。](http://stackoverflow.com/faq#deletion)如果您願意,您可能仍然包含鏈接,但僅作爲「參考」。答案應該獨立,不需要鏈接。 – Taryn 2013-07-19 11:32:48