首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >集成inherited_resources和授权

集成inherited_resources和授权
EN

Stack Overflow用户
提问于 2013-05-03 11:03:31
回答 1查看 262关注 0票数 0

我目前正在尝试将inherited_resources和authority集成到我的Rails应用程序中。

我有点纠结于检查基于资源执行控制器操作的能力的最佳位置。以下代码在authority中作为示例给出:

代码语言:javascript
复制
  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检查也添加到这些抽象的查找器上会很好。

注意在update (假设是create)的情况下授权机构的双重检查。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-19 17:41:20

我依靠ActiveSupport::Concern来简化模块。我将我的关注点存储在app下一个名为concerns的目录中。我将其称为inherited_resources_with_authority.rb,您可能需要在application.rb中修改您的autoload_paths,以便从该文件夹加载文件。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16350935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档