【问题标题】:Ruby On Rails Pundit Gem Authorizing DashboardRuby On Rails Pundit Gem 授权仪表板
【发布时间】:2018-03-15 23:31:06
【问题描述】:

如何为提供来自各种模型的数据的仪表板控制器提供权威人士授权?

我的 DashboardsController 如下所示:

class DashboardsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_user
  before_action :set_business
  after_action :verify_authorized

  def index

  end


  private

  def set_user
    @user = current_user
  end
  def set_business
    @business = current_user.business
  end


end

如何在我的 DashboardsPolicy 中同时授权 @user 和 @business?

【问题讨论】:

    标签: ruby-on-rails ruby pundit


    【解决方案1】:

    我认为尝试访问仪表板不是基于名为仪表板的资源的策略,而只是业务策略中的一种特殊方法。

    因此,我会将其添加到 BusinessPolicy 作为方法 dashboard

    # in your controller
    authorize @business, :dashboard?
    
    # and the business_policy
    class BusinessPolicy < ApplicationPolicy
      def dashboard?
        # condition depending on a `user` (current_user) and a record (business)
        user.admin? || user.business == record
      end
    end
    

    或者它可能更简单。如果允许某人在允许显示业务时查看仪表板,则只需在您的控制器中重新使用BusinessPolicy#show?

    authorize @business, show?
    

    【讨论】:

    • 在我的 DashboardController 中,如何让 Pundit 使用 BusinessPolicy?我同意简单地尝试访问仪表板不是基于资源的策略。
    • @Rich Pundit 魔术!这只是authorize 方法的默认行为。 authorize 方法自动推断@busniess(它是Business 的一个实例)将有一个匹配的BusinessPolicy 类,并实例化这个类,将当前用户和给定的@business 记录交上。
    【解决方案2】:

    Pundit 期望将当前用户和模型对象传递给它。在这种情况下,我认为你想要的是一个 DashboardsPolicy 类,你会像这样授权它:

      def index
        authorize(@business)
      end
    

    来自README

    Pundit 将调用 current_user 方法来检索要发送到的内容 这个论点

    authorize 方法自动推断 Post 将有一个 匹配 PostPolicy 类,并实例化该类,上交 当前用户和给定记录

    README 中还有一个特定部分是关于使用仪表板作为示例操作的无头策略:https://github.com/varvet/pundit#headless-policies

    您还可以创建一个带有两个实体的普通 ruby​​ 对象,并将其用作您的授权对象:

    class UserBusiness
      def initialize(user, business)
      end
    
      ...other methods here
    end
    
    @model = UserBusiness.new(user, business)
    authorize(@model)
    

    【讨论】:

    • 嘿,杰德,如果我创建了一个普通的 ruby​​ 对象,那将是一个模型,不是吗?如果我创建了那个模型(不是 AR 模型,只是一个普通的 ruby​​ 对象),我将如何让我的 Policy 引用该对象?更清楚地说,我将如何执行您的指示?感谢您的帮助!
    • 嗨@Rich,Pundit 不在乎您的模型是否由 ActiveRecord 支持。选择它的原因之一是它在这方面没有固执己见。您的“模型”对象需要能够做的就是能够针对对象进行查询以做出策略决策。由您决定这些业务规则与操作的允许性有关。我觉得你想多了。
    猜你喜欢
    • 1970-01-01
    • 2016-06-27
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多