加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Pundit :: PolicyScopingNotPerformedError

发布时间:2020-12-17 04:02:32 所属栏目:百科 来源:网络整理
导读:我使用这个Pundit宝石相当新,但似乎无法理解政策系统.从我读过的所有内容看起来都是正确的,尽管我仍然收到错误 应用控制器 class ApplicationController ActionController::Base include Pundit protect_from_forgery before_filter :authenticate_person! #
我使用这个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

申请政策

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

解决方法

您可能需要从Pu??ndit的自述文件中查看 this section.

它基本上说,当在after_action中使用verify_authorized时,它将检查是否实际调用了授权.

Pundit adds a method called verify_authorized to your controllers. This method will raise an exception if authorize has not yet been called. You should run this method in an after_action to ensure that you haven’t forgotten to authorize the action.

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

Likewise,Pundit also adds verify_policy_scoped to your controller. This will raise an exception in the vein of verify_authorized. However,it tracks if policy_scope is used instead of authorize. This is mostly useful for controller actions like index which find collections with a scope and don’t authorize individual instances.

在你的情况下,异常是由你没有在Devise :: SessionsController #new action中调用authorize引起的.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读