I am writing an application that uses plain old Ruby objects (POROs) to abstract authorization logic out of controllers.
Currently, I have a custom exception class called NotAuthorized
that I rescue_from
at the controller level, but I was curious to know: Does Rails 4 already come with an exception to indicate that an action was not authorized? Am I reinventing the wheel by implementing this exception?
Clarification: The raise AuthorizationException
is not happening anywhere inside of a controller, it is happening inside of a completely decoupled PORO outside of the controller. The object has no knowledge of HTTP, routes or controllers.
I'm guessing the reason Rails didn't introduce this exception is because Authorisation and Authentication is not Rails native behavior (not considering basicauth of course).
Usually these are responsibilities of other libraries Devise for NotAuthenticated; Pundit, CanCanCan, Rollify for NotAuthorized) I would actually argue it may be a bad thing to extend
ActionController
with custom exceptions likeActionController::NotAuthorized
(because like I said it's not it's responsibility)So Way how I usually tackled this problem is that I've introduced custom exceptions on
ApplicationController
Therefore in my controllers I can do
This clearly defines that the layer your expecting this exception to be raised and caught is your application layer, not 3rd party lib.
The thing is that libraries can change (and yes this means Rails too) defining exception on a 3rd party lib classes and rescuing them in your application layer is really dangerous as if the meaning of exception class changes it brakes your
rescue_from
You can read lot of articles where people are Waring about Rails
raise
-rescue_from
being the moderngoto
(now considering anti-pattern amongst some experts) and in certain extend it is true, but only if you are rescuing Exceptions that you don't have full control off !!That means 3rd party exceptions (including Devise and Rails to certain point). If you define the exceptions classes in your application, you are not relaying on 3rd party lib => you have full control => you can
rescue_from
without this being an anti-pattern.Rails doesn't seem to map an exception to
:unauthorized
.The default mappings are defined in activerecord/lib/active_record/railtie.rb:
and actionpack/lib/action_dispatch/middleware/exception_wrapper.rb:
You could add a custom exception from within your application's configuration (or a custom Railtie):
Or simply use
rescue_from
.