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.
Rails doesn't seem to map an exception to :unauthorized.
The default mappings are defined in activerecord/lib/active_record/railtie.rb:
config.action_dispatch.rescue_responses.merge!(
'ActiveRecord::RecordNotFound' => :not_found,
'ActiveRecord::StaleObjectError' => :conflict,
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
)
and actionpack/lib/action_dispatch/middleware/exception_wrapper.rb:
##rescue_responses.merge!(
'ActionController::RoutingError' => :not_found,
'AbstractController::ActionNotFound' => :not_found,
'ActionController::MethodNotAllowed' => :method_not_allowed,
'ActionController::UnknownHttpMethod' => :method_not_allowed,
'ActionController::NotImplemented' => :not_implemented,
'ActionController::UnknownFormat' => :not_acceptable,
'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
'ActionDispatch::ParamsParser::ParseError' => :bad_request,
'ActionController::BadRequest' => :bad_request,
'ActionController::ParameterMissing' => :bad_request
)
You could add a custom exception from within your application's configuration (or a custom Railtie):
Your::Application.configure do
config.action_dispatch.rescue_responses.merge!(
'AuthorizationException' => :unauthorized
)
# ...
end
Or simply use rescue_from.
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, Dude Policy, CanCanCan, Rollify for NotAuthorized) I would actually argue it may be a bad thing to extend ActionController with custom exceptions like ActionController::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
class ApplicationController < ActionController::Base
NotAuthorized = Class.new(StandardError)
# ...or if you really want it to be ActionController
# NotAuthorized = Class.new(ActionController::RoutingError)
rescue_from ActiveRecord::RecordNotFound do |exception|
render_error_page(status: 404, text: 'Not found')
end
rescue_from ApplicationController::NotAuthorized do |exception|
render_error_page(status: 403, text: 'Forbidden')
end
private
def render_error_page(status:, text:, template: 'errors/routing')
respond_to do |format|
format.json { render json: {errors: [message: "#{status} #{text}"]}, status: status }
format.html { render template: template, status: status, layout: false }
format.any { head status }
end
end
end
Therefore in my controllers I can do
class MyStuff < ApplicationController
def index
if current_user.admin?
# ....
else
raise ApplicationController::NotAuthorized
end
end
end
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 modern goto (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.
Related
So I handle exceptions with an error controller to display dynamic content to my users in production. I have it in my route file to do:
# Errors
%w( 404 422 500 ).each do |code|
get code, :to => "errors#show", :code => code
end
The only problem is now that I'm routing on errors such as that I lose information in my controller when I want to notify Airbrake. How can I maintain the exception information and send it to Airbrake on a 500? Right now all I get is the env that was occurring at the time of the exception which is less helpful for debugging purposes.
class ErrorsController < ApplicationController
def show
notify_airbrake(env)
render status_code.to_s, :status => status_code
end
protected
def status_code
params[:code] || 500
end
end
Are you handling an error by redirecting to a URL like http://your.site/500? That will be just an HTTP request like any other, losing the exception context you're after. Instead, you probably want to be using ActionController's Rescue functionality. It would look like this:
class ApplicationController < ActionController::Base
rescue_from StandardError, with: :render_error
private
def render_error(error)
notify_airbrake(error)
render text: 500, status: 500
end
end
You can add multiple rescue_from declarations to handle different kinds of error, like the ActiveRecord::RecordNotFound from the Rails guide's example.
I am using rails-api to build an API with no web interface. When I get errors in development, I'd love to see just the error message and stacktrace in plain text without all of the HTML wrapping. How do I override the global exception handling so it renders the stacktrace in development mode in plain text/JSON, and a generic error message in production?
I would suggest that including the stack trace in production code is probably not a good idea from a security stand point.
Here is how I would do it:
render :json => {message:exception.message, stack_trace: exception.stacktrace}
I hope this helps.
After Sam's clarification I can add:
In your base controller for your API (probably ApplicationController):
class ApplicationController < ActionController::Base
...
rescue_from Exception do |exception|
error = {message:exception.message}
error[:stack_trace] = exception.stacktrace if Rails.env.development?
render :json => error
end
...
end
Caveat: You may not want to rescue from every single exception in this way but this is how you'd do it if you did.
Some improvements over #donleyp answer to get a clean trace in Rails 3.2 and output generic error info in production:
class ApplicationController < ActionController::API
...
rescue_from Exception do |exception|
if Rails.env.development?
error = {message:exception.message}
error[:application_trace] = Rails.backtrace_cleaner.clean(exception.backtrace)
error[:full_trace] = exception.backtrace
render :json => error
else
render :text => "Internal server error.", :status => 500
end
end
...
end
Is there are way to tell Rails to render your custom error pages (for example, the ones you write in your ErrorsController)? I've searched many topics, and the one that seems to kinda work was to add to your ApplicationController something like
if Rails.env.production?
rescue_from Exception, :with => :render_error
rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
rescue_from ActionController::UnknownController, :with => :render_not_found
rescue_from ActionController::UnknownAction, :with => :render_not_found
end
and then you write your methods render_error and render_not_found the way you want. This seems to me like a really unelegant solution. Also, it's bad, because you have to know exactly what are all the errors that could happen. It's a temporary solution.
Also, there is really no easy way to rescue an ActionController::RoutingError that way. I saw that one way was to add something like
get "*not_found", :to => "errors#not_found"
to your routes.rb. But what if you want to raise somewhere an ActionController::RoutingError manually? For example, if a person who is not an administrator tries to go to "adminy" controllers by guessing the URL. In those situations I prefer raising a 404 more than raising an "unauthorized access" error of some kind, because that would actually tell the person that he guessed the URL. If you raise it manually, it will try to render a 500 page, and I want a 404.
So is there a way to tell Rails: "In all cases you would normally render a 404.html or a 500.html, render my custom 404 and 500 pages"? (Of course, I deleted the 404.html and 500.html pages from the public folder.)
Unfortunately there aren't any methods I know of that can be overridden to provide what you want. You could use an around filter. Your code would look something like this:
class ApplicationController < ActionController::Base
around_filter :catch_exceptions
protected
def catch_exceptions
yield
rescue => exception
if exception.is_a?(ActiveRecord::RecordNotFound)
render_page_not_found
else
render_error
end
end
end
You can handle each error as you see fit in that method. Then your #render_page_not_found and #render_error methods would have to be something like
render :template => 'errors/404'
You would then need to have a file at app/views/errors/404.html.[haml|erb]
I have this code somewhere in my controller:
raise PermissionDenied
When this is executed, I want to show a custom error page written in HAML, rather than the default NameError page.
Can anyone help me? Thanks.
The rescue_from method can be used for global exception handling.
Change theapp/controller/application_controller.rb file to add the exception handler.
class ApplicationController < ActionController::Base
rescue_from ::PermissionDenied, :with => :render_permission_denied
def render_permission_denied(e)
#error = e # Optional, accessible in the error template
log_error(e) # Optional
render :template => 'error_pages/permission_denied', :status => :forbidden
end
end
Now add a haml file called permission_denied.html.haml in app/views/error_pages directory.
%h1 Permission Denied!
%p #{#error.message}
Refer to the rails documentation for more details.
I need to implement a custom error page in my rails application that allows me to use erb.
I've been following this tutorial (http://blog.tommilewski.net/2009/05/custom-error-pages-in-rails/) and I cannot get it to work locally (or remotely). I am running Rails 2.3.5
Here's the gist of the approach.
1) in the 'application_controller', I over ride the "render_optional_error_file(status_code)" method, and set the visibility to "protected", like this.
protected
def render_optional_error_file(status_code)
known_codes = ["404", "422", "500"]
status = interpret_status(status_code)
if known_codes.include?(status_code)
render :template => "/errors/#{status[0,3]}.html.erb", :status => status, :layout => 'errors.html.erb'
else
render :template => "/errors/unknown.html.erb", :status => status, :layout => 'errors.html.erb'
end
end
def local_request?
true
end
I also created a folder within views called errors and created the following views: 404.html.erb, 422.html.erb, 500.html.erb,unknown.html.erb and I created a new layout "errors.html.erb"
I can't seem to get it to work. I've been trying to trigger the 404 page by navigating to http://localhost:3000/foobar -- but, instead of getting the new 404.html.erb, I seem to be getting the standard apache 500 error. This happens when I try both mongrel_rails start and mongrel_rails start -e production.
I would suggest using exceptions to render such error pages, so you can use inheritance to group your error messages...
First, declare some (I usually do it in application_controller.rb)
class Error404 < StandardError; end
class PostNotFound < Error404; end
Then add code to ApplicationController to handle them
class ApplicationController < ActionController::Base
# ActionController::RoutingError works in Rails 2.x only.
# rescue_from ActionController::RoutingError, :with => :render_404
rescue_from Error404, :with => :render_404
rescue_from PostNotFound, :with => :render_post_not_found
def render_404
respond_to do |type|
type.html { render :template => "errors/error_404", :status => 404, :layout => 'error' }
type.all { render :nothing => true, :status => 404 }
end
true
end
def render_post_not_found
respond_to do |type|
type.html { render :template => "errors/shop_not_found", :status => 404, :layout => 'error' }
type.all { render :nothing => true, :status => 404 }
end
true
end
end
This renders errors/error_404 with the errors layout. Should get you started :)
And in your target_controller:
raise PostNotFound unless #post
Edit
Note for Rails 3
for a longer explanation on why ActionController::RoutingError doesn't work for rails 3:
Rails 3.0 Exception Handling.
Rails ticket 4444
"If your application relies on engines that extend your app with their
own routes, things will break because those routes will never get
fired!"
Firstly - have you deleted the file: 'public/500.html' If that file exists, it will override anything else that you try to do.
Secondly, using an explicit "rescue_from" in the controller (as explained in the other comment) - is a good option if you need to fine-tune the response to different kinds of errors.
You most likely get the 500 error because of an application error.
Have you checked the log files?
Update:
Are you certain that you are running 2.3.5 and not an older version that happens to be installed?
Mongrel should say which version you are running when it starts, otherwise it should say in the config/environment.rb file.
There are some errors in the code that might create the 500 error. I've changed that and also corrected a few other things I think you meant :)
def render_optional_error_file(status_code)
known_codes = ["404", "422", "500"]
status = interpret_status(status_code)
if known_codes.include?(status) # Here it should be status, not status_code (which is a symbol)
render :template => "errors/#{status[0,3]}", :status => status, :layout => 'errors' # No need to mention ".html.erb", you can do it, but it is not necessary since rails will guess the correct format.
else
render :template => "errors/unknown", :status => status, :layout => 'errors'
end
end
def local_request?
# This must return false instead of true so that the public viewer is called
# instead of the developer version.
false
end
Purpose of completeness for newer rails versions:
http://www.frick-web.com/en/blog/nifty_errorpages-gem
that is a little rails engine for handling your error pages. Maybe you will need it for newer projects. it is a good option to handle errors in my opinion.