I'm trying to centralize authentification in pundit policies instead of having it in my controllers. It works well but I lost some flexibility in customizing redirection and flash message.
How could I transfer the information about which authentification didn't pass to the Pundit::NotAuthorizedError rescuing function ? One action can have 2 steps of authentification: 1. user.paid? 2. user.is_allowed_to_update? and I want custom message and redirection for each case.
The exception.query
solution is not working cause it only allow to customize flash and redirection for each action and not within one action.
Below is a more detailed explanation of the situation
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
And now
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