【问题标题】:Cancan abilities for inherited resources with nesting in controller具有嵌套在控制器中的继承资源的 Cancan 功能
【发布时间】:2011-11-17 16:14:08
【问题描述】:

我继承了在我的控制器中工作的资源,我使用 cancan 进行授权。但是,我在编写所需的能力时遇到了问题。

我可以通过 2 种方式显示特定顺序:

/profile/123/orders/321
/store/456/orders/321

在控制器中:

class OrdersController < ApplicationController
  inherit_resources 
  belongs_to :profile, :store, :optional => true
  load_and_authorize_resource
  ...
end

角色是:用户(模型中的has_one :profile)和经理(模型中的has_one :store)

要求(用文字表示)是:

  • 经理可以在(属于)他的上下文中显示订单 商店。
  • 经理无法在任何用户的上下文中显示订单 个人资料(应拒绝访问)
  • 用户可以在 他个人资料的背景
  • 用户无法在任何上下文中显示订单 存储(拒绝)

我无法满足这些要求,也许我应该以特殊方式或实际上以两种方式加载资源?直觉告诉我,在这两种情况下,对订单的访问都应该基于对父资源的访问。 谢谢你的帮助。

【问题讨论】:

    标签: ruby-on-rails nested cancan inherited-resources


    【解决方案1】:

    如果您在您的能力.rb 文件中拥有 profile 和 store 的权限,那么您也可以授权 parent。 IE。像这样:

    load_and_authorize_resource :profile
    load_and_authorize_resource :store
    load_and_authorize_resource :order
    

    或者您可以按照 CanCan wiki 中的说明进行操作:

    多态关联

    假设任务可以通过多态关联分配给项目或事件。可以将数组传递给 :through 选项,它将使用它找到的第一个。

     load_resource :project
     load_resource :event
     load_and_authorize_resource :task, :through => [:project, :event]
    

    这里它将检查@project 和@event 变量,并通过存在的任何一个来获取任务。请注意,这只是加载父模型,如果要授权父模型,则需要通过 before_filter 来完成,因为涉及特殊逻辑。

     before_filter :authorize_parent
     private
     def authorize_parent
       authorize! :read, (@event || @project)
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多