ApplicationController没有抢救Pundit Not Authorized Error

时间:2018-01-20 00:07:42

标签: ruby-on-rails rails-admin pundit

我正在使用Rails 5.2,Pundit 1.1和rails_admin 1.2

我在application_controller.rb中有以下内容:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include Pundit

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized(exception)
    flash[:alert] = "You are not authorized to perform this action."
    redirect_to root_path
  end
end

我在application.policy.rb中有以下内容:

class ApplicationPolicy
.
.
.
  def rails_admin?(action)
    case action
      when :dashboard
        user.admin?
      when :index
        user.admin?
      when :show
        user.admin?
      when :new
        user.admin?
      when :edit
        user.admin?
      when :destroy
        user.admin?
      when :export
        user.admin?
      when :history
        user.admin?
      when :show_in_app
        user.admin?
      else
        raise ::Pundit::NotDefinedError, "unable to find policy #{action} for #{record}."
    end
  end
end

在我的config / initializers / rails_admin.rb中,我有以下内容:

    RailsAdmin.config do |config|
      ### Popular gems integration

      ## == Devise ==
      config.authenticate_with do
        warden.authenticate! scope: :user
      end
      config.current_user_method(&:current_user)

      ## == Pundit ==
      config.authorize_with :pundit

    end

module RailsAdmin
  module Extensions
    module Pundit
      class AuthorizationAdapter
        def authorize(action, abstract_model = nil, model_object = nil)
          record = model_object || abstract_model && abstract_model.model
          if action && !policy(record).send(*action_for_pundit(action))
            raise ::Pundit::NotAuthorizedError.new("not allowed to #{action} this #{record}")
          end
          @controller.instance_variable_set(:@_pundit_policy_authorized, true)
        end

        def authorized?(action, abstract_model = nil, model_object = nil)
          record = model_object || abstract_model && abstract_model.model
          policy(record).send(*action_for_pundit(action)) if action
        end

        def action_for_pundit(action)
          [:rails_admin?, action]
        end
      end
    end
  end
end

如果用户是管理员,则他们可以访问管理信息中心。 但是,如果用户不是管理员,则应使用Flash消息将其重定向到主页。

当我尝试访问非管理员用户的Rails管理仪表板时,我得到以下内容: enter image description here 为什么ApplicationController没有抢救Pundit :: NotAuthorizedError?

我创建了一个重现此错误的示例应用:https://github.com/helphop/sampleapp

2 个答案:

答案 0 :(得分:1)

编辑:更新 -

您实际遇到的错误涉及路径助手 - 例如root_urlroot_path - 在RailsAdmin中。当rescue_from遇到错误时,它会自行逃脱。

话虽如此,更改redirect_to "/"应解决问题。

答案 1 :(得分:0)

您应在config.parent_controller = 'ApplicationController'之前添加config.authorize_with :pundit。它会说Rails Admin从您的ApplicationController继承而来的RailsAdmin :: ApplicationController将起作用。 希望有帮助。