gpt4 book ai didi

ruby-on-rails - ApplicationController 未挽救 Pundit 未授权错误

转载 作者:行者123 更新时间:2023-12-04 16:06:57 25 4
gpt4 key购买 nike

我正在使用 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

如果用户是管理员,则他们可以访问管理仪表板。但是,如果用户不是管理员,则应使用即显消息将他们重定向到主页。

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

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

最佳答案

编辑:更新 —

您实际遇到的错误涉及 RailsAdmin 中的路径帮助程序——例如 root_urlroot_path。当 rescue_from 遇到错误时,它会自行转义。

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

关于ruby-on-rails - ApplicationController 未挽救 Pundit 未授权错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48351256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com