【问题标题】:Rails is routing to Page not found instead of 404 errorRails 路由到 Page not found 而不是 404 错误
【发布时间】: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


【解决方案1】:

您应该在控制器上重写user_not_authorized,当非管理员用户访问未经授权的页面时调用该控制器

def user_not_authorized
  show_404
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2023-03-20
    • 2020-12-05
    • 2019-12-01
    相关资源
    最近更新 更多