本文介绍了Pundit :: PolicyScopingNotPerformedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用此Pundit gem尚不陌生,但似乎在理解政策体系方面遇到困难。从我读过的所有内容来看,尽管我仍然遇到错误,但一切似乎都是正确的

I am fairly new to using this Pundit gem but seem to be having trouble understanding the policy system. From everything I have read it all appears to be correct though I am still getting an error

应用程序控制器

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

应用程序策略

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

错误消息

Pundit::AuthorizationNotPerformedError in Devise::SessionsController#new


推荐答案

您可能需要检查摘自Pundit自述文件。

You probably need to check this section from Pundit's readme.

基本上,在 after_action 中使用 verify_authorized 时,它将检查 authorized

It basically says, that when using verify_authorized is used in after_action, it will check if authorized was actually called.

verify_policy_scoped 也是这样,但 policy_scope

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

In your case exception is caused by the fact that you didn't called authorize in Devise::SessionsController#new action.

我认为,最好的处理方法是从 ApplicationController after_action 支票并将其移至子类。

I think, the best way to deal with it, is to remove after_action checks from ApplicationController and move them to a subclass.

这篇关于Pundit :: PolicyScopingNotPerformedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 04:53