3

当权威人士不允许用户查看带有授权规则的页面时,我收到以下错误:

在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。另请注意,重定向和渲染都不会终止操作的执行,因此如果您想在重定向后退出操作,则需要执行“redirect_to(...) and return”之类的操作。

这是application_controller.rb

class ApplicationController < ActionController::Base    
  # Includes Authorization mechanism
    include Pundit

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  # Globally rescue Authorization Errors in controller.
  # Returning 403 Forbidden if permission is denied
  rescue_from Pundit::NotAuthorizedError, with: :permission_denied

  # Enforces access right checks for individuals resources
  # after_filter :verify_authorized, :except => :index

  # Enforces access right checks for collections
  # after_filter :verify_policy_scoped, :only => :index

  private

  def permission_denied
    flash[:error] = "You don't have the proper permissions to view this page. If you think you are supposed to then please contact us at permissions@inrtracker.com"
    # this is giving a redirect loop error
    redirect_to(request.referrer || root_path)
  end
end

stat_policy.rb

class StatPolicy
  attr_reader :current_user, :model

  def initialize(current_user, model)
    @current_user = current_user
    @stat = model
  end

  def index?
    @current_user.admin?
  end
end

stats_controller.rb:

class StatsController < ApplicationController
  after_action :authorize_stat

  def index
    @stats = Stat.all
    @stat = Stat.new
    render layout: "stat_layout"
  end

  private
    def authorize_stat
      authorize @stat
    end

    # Use callbacks to share common setup or constraints between actions.
    def set_stat
      @stat = Stat.find(params[:id])
    end

end
4

3 回答 3

7

有一个奇怪的操作顺序发生在after_action. 如果您设置response_bodynil,它应该可以解决您的问题。

  def permission_denied
    flash[:error] = "You don't have the proper permissions to view this page. If you think you are supposed to then please contact us at permissions@inrtracker.com"
    self.response_body = nil # This should resolve the redirect root.
    redirect_to(request.referrer || root_path)
  end
于 2014-09-19T22:54:54.913 回答
2

接受的答案对我不起作用。我的问题最终是 Turbolinks 导致所有链接都被双重提交。我不知道我的 Turbolinks 问题的最初原因,但我禁用了 Turbolinks,现在一切正常。

于 2016-05-31T10:34:37.143 回答
0

根据 Garrett 的解决方案,该问题是由 Turbolinks 结合 Rails 渲染流程引起的。我建议不要删除非常有用的 Turbolinks,而是放置一个:

data-turbolinks="false"

在指向导致问题的页面的链接上。就我而言,它只是发生在带有表单的页面上,例如“新”操作。

于 2017-07-31T13:14:30.420 回答