【发布时间】:2020-09-14 00:50:57
【问题描述】:
我最近创建了一个errors_controller.rb 文件,该文件基本上会将所有不存在的页面(甚至非管理员用户未经授权的页面)路由到 404 页面:
class ErrorsController < ApplicationController
def page_not_found
show_404
end
end
然后在我的routes.rb 文件上:
match '*path', via: :all, to: 'errors#page_not_found'
我正在使用Pundit gem 进行授权,这是我的用户政策:
class UserPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
def index?
user.admin?
end
end
现在的问题是,每当我访问一个不存在的页面时,它都会向我显示:
但如果非管理员用户访问未经授权访问的页面(例如 localhost:3000/users-list),则会显示以下内容:
当未经授权的用户访问只能由管理员访问的页面时,如何确保在我的公用文件夹中显示 404 页面或特定页面?
更新:这是我的application_controller.rb 文件的内容:
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
rescue_from ActiveRecord::RecordNotFound, with: :show_404
def after_sign_in_path_for(resource)
stored_location_for(resource) || contacts_path
end
def after_sign_up_path_for(resource)
after_sign_in_path_for(resource)
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:user_avatar, :name, :email, :password, :password_confirmation)}
devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:user_avatar, :name, :email, :password, :current_password)}
end
private
def user_not_authorized
flash[:danger] = "You are not authorized to perform this action."
redirect_to action: :index
end
def show_404
render template: "errors/404", status: 404
end
end
【问题讨论】:
-
我猜你有一些像
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized这样的声明,你能补充更多关于当 Pundit::NotAuthorizedError 引发时将调用的操作 -
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized我的应用程序控制器上有这个。 -
我刚刚更新了上面的问题。
-
是的,图片(i.stack.imgur.com/vFQjU.png) 告诉你:你重定向的时间太多了。似乎当您的请求 /users-list 时,某些操作会将您重定向到其他路径,但您仍然未授权,它会再次重定向到其他路径并继续....
标签: ruby-on-rails