2015-08-13 15 views
2

我试图在权威策略中集中认证而不是在控制器中进行认证。它运行良好,但我在定制重定向和Flash消息方面失去了一些灵活性。Pundit:在一个用户动作中自定义重定向

我该如何将有关哪个认证未传递给Pundit :: NotAuthorizedError救援功能的信息?一个动作可以有两个步骤的认证:1. user.paid? 2. user.is_allowed_to_update?我想为每个案例定制消息和重定向。

exception.query解决方案不起作用,因为它只允许为每个操作自定义闪存和重定向,而不是在一个操作中。

下面的情况更详细的解释

WITHOUT PUNDIT 
Comment_Controller 
def update 
    if user.didnt_pay? 
     flash[:message] = nice_message 
     redirect_to payment_page_path 
    elsif user.is_not_allowed_to_perform_action 
     flash[:message] = less_nice_message 
     redirect_to dashboard_path 
    end 
end 

现在

WITH PUNDIT 
Comment_Controller 
def update 
    authorize @comment 
end 

Comment_policy 
def update? 
    user.paid? && user_is_allowed_to_perform_action 
end 

ApplicationController 
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized 
def user_not_authorized 
    flash[:message] = one_message_for_all_error # THIS IS WHAT I WANT TO CUSTOMIZE 
    redirect_to one_path_for_all_error # THIS IS WHAT I WANT TO CUSTOMIZE 
end 

回答

1

一种定制此错误消息时在Policy设定预期的消息,后来从得到它的可能性控制器。如何做?

exception对象您在控制器

class CommentsController < ApplicationController 

    def user_not_authorized(exception) 
    end 
end 

得到作为参数配备了policy属性,它链接到你的违规政策。因此,可以说,在你的政策,你要设置一个特定的消息时,一些条款没有实现:

class AnimalPolicy < ApplicationPolicy 
    attr_accessor :error_message 

    def new? 
    if !authorization_clause 
     @error_message = "Something terrible happened" 
     false 
    else 
     true 
    end 
    end 
end 

因此,在你的控制器,你就必须设置这个error_message到您的flash或任何你想要它是:

class CommentsController < ApplicationController 

    def user_not_authorized(exception) 
    flash[:error] = exception.policy.try(:error_message) || "Default error message" 

    redirect_to root_path 
    end 
end 

这是一个有点笨拙的解决方案,但它为我工作

+0

我刚刚提到了一个定制评论的情况;添加自定义“重定向”路径的情况经过必要的修改。 – geekazoid

0

在我的解决方案,我提出了两种方法,一是当用户有一个很好的答案另一个当回答是不利的。 ..专家有一个方法(user_not_authorized),它可以管理一个可以复制和适应您的建议

def update 

    if user.didnt_pay? 

     authorize @comment 
     user_congratulation 

    elsif user.is_not_allowed_to_perform_action 

     user_not_authorized 

    end 

end 

ApplicationController中

过去,这rescue_from权威人士:: NotAuthorizedError,具有:user_not_authorized

和之后您将在控制器中创建两个私有方法,名为

user_not_authorized和user_congratulation

private 

    def user_not_authorized 
     flash[:alert] = "less_nice_message" 
     redirect_to dashboard_path 
    end 


    def user_congratulation 
     flash[:alert] = "nice_message" 
     redirect_to payment_page_path 
    end 

    end 

更多信息,请访问此链接https://github.com/elabs/pundit#rescuing-a-denied-authorization-in-rails

虽然这个职位是旧的,我认为合适的回答,因为我还需要一个很好的答案,这是不是这么回事!我希望有帮助

+0

请花些时间正确地设置代码的格式。 –

+0

我做到了**谢谢** – tnbsoftlab

+0

良好的工作,谢谢。 –

相关问题