문제

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:

  1. Prevent flow if current_user is not admin.
  2. Allow regular flow if 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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top