Reputation: 22264
I'm trying to protect certain actions from being accessed by users that aren't authorized.
Here a small example from my controller:
class RestaurantsController < ApplicationController
before_filter :require_admin, :only => [:new, :create, :update, :edit, :destroy]
#...yada yada yada...
end
And in my ApplicationController (because I need to protect those same actions in many controllers) I placed the helper method, so I don't repeat myself.
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def require_admin
???
end
helper_method :current_user
end
What should I be returning from my require_admin method in order to:
current_user
is not admin.current_user
is admin.Also, do I need to place require_admin
as a helper_method
?
I know how to handle the is admin?
bit, I just need to know what to return from the helper method being invoked by my filter.
Any suggestions?
Upvotes: 0
Views: 88
Reputation: 4382
I prefer to raise a 404 error if someone is trying to access a page they do not have permission to be viewing.
def require_admin!
raise ActiveRecord::RecordNotFound unless authenticate_user! && current_user.is_admin?
end
The above assumes you have an authenticate_user! method which you will have if you are using devise. If you aren't using devise, I'd create one similar to the require admin I showed above with a unless current_user condition.
Add the is_admin? method to your user/admin class
All controllers inherit from application controller so you should not need to make it a helper method.
Upvotes: 1