Friday, 6 May 2011

admin_login_required filter for rubyCAS

Setting up an admin-only login for rubyCAS is fairly straightforward.

First, you have to add an "is_admin" boolean flag to your *local* user class. Remember that you will probably want to restrict admin-rights differently on different applications - so it's better to put it in the local db for this.

If you are really sure that you want universal admins - then you can look into using the "extra attributes" aspects of rubyCAS - but I won't cover this here today.

Now it's just a matter of adding this helper-method to application_controller.rb (note, this depends on logged_in? and current_user)

    # overload the restful_auth version
    def admin_login_required
      # send them to 404 so we don't leak the page's existence
      # Note: implementation of this method left as exercise for the reader...
      render_four_oh_four and return(false) unless logged_in? && @current_user.is_admin?
      true
    end

Now you can add this as a before_filter to whatever actions you need... but make sure it comes *after* the actual login filters eg:

  class MyController < ApplicationController
    # this is the before_filter provided by rubyCAS client
    before_filter CASClient::Frameworks::Rails::Filter
    # this is a call to our own new before_filter which populates the cas user
    before_filter :setup_cas_user

    before_filter :admin_login_required, :only => :admin_homepage

  
    # actions here
    def admin_homepage
      # load cool admin-only stuff here...
    end
  end

To actually update that flag - you'll need to have local versions of user CRUD pages as per any other CRUD pages - affecting the local user values.

This is one article in a series on Rails single-sign-on with rubyCAS

No comments: