权威人士:: PolicyScopingNotPerformedError

Pau*_*ane 4 ruby-on-rails devise pundit

我使用这个Pundit宝石相当新,但似乎无法理解政策系统.从我读过的所有内容看起来都是正确的,尽管我仍然收到错误

应用控制器

class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery
  before_filter :authenticate_person!

  # Verify that controller actions are authorized. Optional, but good.
  after_filter :verify_authorized,  except: :index
  after_filter :verify_policy_scoped, only: :index


  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def pundit_user
    Person.find_by_id(current_person)
  end

  def user_not_authorized
    flash[:alert] = "You are not authorized to perform this action."
    # redirect_to(request.referrer || root_path)
  end
end
Run Code Online (Sandbox Code Playgroud)

申请政策

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    raise Pundit::NotAuthorizedError, "must be logged in" unless user
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

错误信息

Pundit::AuthorizationNotPerformedError in Devise::SessionsController#new
Run Code Online (Sandbox Code Playgroud)

Ale*_*s K 11

答案是检查它是否是devise控制器.

after_action :verify_authorized, :except => :index, unless: :devise_controller?

来自:https://github.com/elabs/pundit/issues/113https://gorails.com/forum/using-pundit-with-activeadmin


dim*_*ura 6

你可能需要检查 从 Pundit 的自述文件中此部分

它基本上是说,当 usingverify_authorized用于 in 时after_action,它会检查是否authorized被实际调用。

Pundit 添加了一个调用verify_authorized控制器的方法。如果authorize尚未调用此方法,则会引发异常。您应该在 an 中运行此方法after_action以确保您没有忘记authorize该操作。

对于 也是如此verify_policy_scoped,但是对于policy_scope

同样,Pundit 也会添加verify_policy_scoped到您的控制器中。这将在verify_authorized. 但是,它会跟踪是否policy_scope使用 代替authorize。这对于控制器操作非常有用,例如index查找具有范围的集合并且不授权单个实例。

在您的情况下,异常是由您没有在Devise::SessionsController#new操作中调用授权造成的。

我认为,处理它的最佳方法是after_actionApplicationController子类中删除检查并将它们移动到子类中。