Restricting Access

We can check if a user is logged in by testing the session variable (i.e. session[:user]). Here we restrict access to specific actions by checking the login status.

Filters

Filters are methods that are called before or after a controller action is executed. Here we focus on Before Filters, which are called before a controller action is performed. The before filter provides an opportunity to check for valid login and redirect the request if the current action is not authorized.

The text covers filters for restricting access on pp. 266 - 281.

Here are examples of declaring a filter in a controller (placed before any of the action methods):

  # run this filter before all requests
  before_filter :authorization

  # run this filter before all requests except for the index action
  before_filter :restrict, :except => :index

  # run this filter only for the new and create actions
  before_filter :prepare, :only => [:new, :create]

Filters are then declared later in the controller (they should follow a proctected or private declaration). Here is an example that prevents access to all actions unless a user (any user) is logged in:

  def authorization
    unless session[:user]
       # not logged in, go to login page
       redirect_to :controller => :session, :action => :login
    end
  end

Alternatively, you may want to restrict access to specific users:

  def restrict
    user_name = session[:user]
    if user_name
      @user = User.find_by_name(user_name)
       unless @user.admin
         # if user is not admin, show the view auth_error.html.erb
         render :action => 'auth_error'
       end
    else
      # not logged in, go to login page
      redirect_to :controller => :session, :action => :login
    end
  end