【问题标题】:Redirect to specific view if Pundit not authorized for show action如果 Pundit 未授权显示操作,则重定向到特定视图
【发布时间】:2015-11-26 03:47:33
【问题描述】:

我的提案控制器有以下操作:

      def show
        @proposal = Proposal.find(params[:id])
        authorize @proposal
      end

我有以下政策:

class ProposalPolicy
  attr_reader :current_user, :proposal

如何重定向到特定页面。如果尝试转到显示页面时权限被拒绝,请说索引建议或根页面?

当我在没有正确权限的情况下导航到它时,我只会得到一个带有以下内容的 rails 错误页面:

not allowed to show? this<proposal OBJ ispsum lorem>

我只是希望他们收到一个简单的通知并重定向到另一个页面。最好的方法是什么?我猜想在显示视图中使用某种 if 语句,但到目前为止没有任何效果。

  def initialize(current_user, proposal)
    @current_user = current_user
    @proposal = proposal
  end

  def show?
    @proposal.published? or @proposal.proposer == @current_user
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model-view-controller authorization pundit


    【解决方案1】:

    Pundit 对此有一个机制。您将在控制器中创建一个名为 user_not_authorized 的私​​有方法 - 在其中您将能够创建一个 Flash 通知并添加一个位置。

    class ApplicationController < ActionController::Base
      protect_from_forgery
      include Pundit
    
      rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
    
      private
    
      def user_not_authorized
        flash[:alert] = "You are not authorized to perform this action."
        redirect_to(request.referrer || root_path)
      end
    end
    

    更多信息在这里:https://github.com/elabs/pundit#rescuing-a-denied-authorization-in-rails

    【讨论】:

    猜你喜欢
    • 2019-06-09
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多