【问题标题】:Do I have to define all methods in Pundit policy?我是否必须在 Pundit 政策中定义所有方法?
【发布时间】:2017-08-19 06:35:39
【问题描述】:

我有一个只有超级用户或管理员才能访问的项目政策。
现在看起来像这样:

class ProjectPolicy < ApplicationPolicy

  def index?
    super_or_admin?
  end

  def new?
    super_or_admin?
  end

  def create?
    super_or_admin?
  end

  def update?
    super_or_admin?
  end

  def show?
    super_or_admin?
  end

  def super_or_admin?
    user.role.name == 'superadmin' or user.role.name == 'admin'
  end
end

是否可以让权威人士自动将super_or_admin? 应用于所有路由,而不是手动定义每个路由?

【问题讨论】:

  • 不确定 Pundit,但如果所有这些方法都在做只是调用 super_or_admin? 你可以给它们都取别名:alias :index? :super_or_admin? 并以这种方式减少一些代码

标签: ruby-on-rails pundit


【解决方案1】:

您可以这样定义您的策略:

class ProjectPolicy < ApplicationPolicy
  def initialize(user, record)
    raise Pundit::NotAuthorizedError.new(policy: 'project') unless super_or_admin?
  end

  def method_missing(name, *args)
    true
  end

  def super_or_admin?
    user.role.name == 'superadmin' or user.role.name == 'admin'
  end
end

所以它会在初始化时检查权限。在这种情况下定义method_missing 是必要的,因为否则您将收到NoMethodError 用于特定于操作的方法(create?update? 等)。但是您不需要定义它们,因为您在 initialize 方法中检查权限,无论如何都会调用它。

然后,如果您需要在所有操作中授权,您可以在控制器或其祖先中定义:

include Pundit

def authorize_project
  authorize :project
end

并像这样使用before_action 回调:

before_action :authorize_project

【讨论】:

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