【问题标题】:Restrict all access to a model based on information from another model (rails)根据来自另一个模型(rails)的信息限制对模型的所有访问
【发布时间】:2015-11-10 06:06:07
【问题描述】:

我最初在 Restricting any access to a model in rails 中提出了类似的问题 - 但这并没有满足我的全部需求。

我有一个包含许多条目的 Dataapi 模型:

create_table "dataapis", force: :cascade do |t|
  t.string   "device_id"
  t.datetime "start_time"
  t.datetime "end_time"
end

我有一个沙盒模型,其中包含有关如何限制访问的信息(沙盒条目在我的管理面板中定义)。

create_table "sandboxes", force: :cascade do |t|
  t.integer  "device_id"
  t.integer  "user_id"
  t.datetime "start_date"
  t.datetime "end_date"
end

实际上,我只希望用户在沙盒中有适当的条目时才能访问 dataapi,这通过以下方式限制访问: - 用户 - 开始日期时间 - 结束日期时间 - 访问发送 dataapi 的设备(已在上一个问题中处理了该部分)。

我似乎无法找到一种方法来做到这一点 - 模型无权访问@user,所以我无法在默认范围内检查它。有什么建议吗?我试过查看 gem(CanCanCan、Pundit 等),但它们只进行基于控制器的授权。我希望此限制适用于对 dataapi 的 所有 查询,无论控制器调用它。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql


    【解决方案1】:

    您可能想尝试在模型级别提供授权的声明式授权 gem。

    https://github.com/stffn/declarative_authorization

    它为您提供了一种根据用户权限进行过滤的查询方法...

    Employee.with_permissions_to(:read).find(:all, :conditions => ...) 
    

    另一种选择是您可以将 current_user 存储在 Dataapi 模型中并使用 around_filter 填充它。

    在模型中...

    class Dataapi < ActiveRecord::Base
      def self.current_user
        Thread.current[:current_user]
      end
    
      def self.current_user=(some_user)
        Thread.current[:current_user] = some_user
      end
    end
    

    在应用程序控制器中...

    class ApplicationController < ActionController::Base
      around_filter :store_current_user
    
      def store_current_user
        Dataapi.current_user = User.find(session[:user_id])
        yield
      ensure
        Dataapi.current_user = nil
      end             
    end
    

    然后您可以使用 Dataapi.current_user 引用 Dataapi 模型中的 current_user

    【讨论】:

    • 我会研究 Delcarative 授权,不知道那个。管理员有时会冒充其他用户来查看数据,因此它需要基于我们的自定义变量 posed_user 而不是当前用户。我该怎么做呢?
    • 使用declarative_authorization?只需更改设置当前用户身份的 before_filter 即可。他们建议……before_filter { |c| Authorization.current_user = c.current_user }……但你可以这样做……before_filter { |c| Authorization.current_user = c.posed_user }
    • 如果可行,我会试一试并选择它作为正确答案,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多