2013-05-03 57 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