lib/pundit/resource_controller.rb in pundit-resources-1.0.0 vs lib/pundit/resource_controller.rb in pundit-resources-1.0.1
- old
+ new
@@ -2,11 +2,14 @@
module ResourceController
extend ActiveSupport::Concern
included do
include ActionController::Rescue
+ include AbstractController::Callbacks
+ after_action :enforce_policy_use
+
JSONAPI.configure do |config|
error = Pundit::NotAuthorizedError
unless config.exception_class_whitelist.include? error
config.exception_class_whitelist << error
end
@@ -15,10 +18,16 @@
rescue_from Pundit::NotAuthorizedError, with: :reject_forbidden_request
end
protected
+ def enforce_policy_use
+ return if @policy_used || response.status.in?(400...600)
+ raise Pundit::AuthorizationNotPerformedError,
+ "#{params[:controller]}##{params[:action]}"
+ end
+
def reject_forbidden_request(error)
type = error.record.class.name.underscore.humanize(capitalize: false)
error = JSONAPI::Error.new(
code: JSONAPI::FORBIDDEN,
status: :forbidden,
@@ -28,12 +37,9 @@
render json: { errors: [error] }, status: 403
end
def context
- { current_user: current_user }
- end
-
- def current_user
+ { current_user: current_user, policy_used: -> { @policy_used = true } }
end
end
end