views:

85

answers:

1

Given that it is well-documented how to use before_filter for a single user classification, I'm having trouble getting action-level protection for multiple user types. Let me explain:

I've got something like this...

class ApplicationController < ActionController::Base
  class << self 
    attr_accessor :standard_actions
  end
  @standard_actions = [:index, :show, :new, :edit, :create, :update, :destroy]

  def require_guardian
    unless current_user and current_user.is_a?(Guardian)
      store_location
      redirect_to home_url
      return false
    end
  end

  def require_admin
    unless current_user and current_user.is_a?(Administrator)
      store_location
      redirect_to register_url
      return false
    end
  end
end

And in the GuardiansController I want to only allow the standard actions for Administrator but all other actions should require Guardian. So I tried this...

class GuardiansController < ApplicationController
  before_filter :require_admin, :only => ApplicationController::standard_actions
  before_filter :require_guardian, :except => ApplicationController::standard_actions
  ...
end

Which ends up doing a recursive redirection. There must be a better way?

A: 

OK, this is another case of not looking carefully and missing something. I inadvertently had setup the route to redirect the user in a recursive way. The above solution works just fine when you set the routes properly:

def require_guardian
  unless current_user and current_user.is_a?(Guardian)
    store_location
    # this route (home_url) sent the user to another controller which ran a before_filter sending them back here again.
    # redirect_to home_url 
    # So I changed it to a neutral route and it works great!
    redirect_to register_url
    return false
  end
end
Midwire