Thursday, 28 April 2011

Gateway filtering in RubyCAS

Gateway login pages are ones where a user doesn't need to be logged-in... but if they already *are* logged in, then we want to know. Example: the help or contact-us pages are available to non-logged-in users.

Often we want to write these pages using the existing templates so that if they aren't logged in, the templates are fairly simple, but if they *are* logged in, then you display the usual logged-in navigation links.

So you need a filter that will auto-authenticate a user *if* they are already logged in, but doesn't *require* it. The standard CAS-login filters will actually redirect non-logged in users to the login page - and we don't want that happening. So we need to write a little filter-magick using the CAS GatewayFilter.

class WelcomeController < ApplicationController
  # don't *require* login for the public pages (inc actual login page)
  skip_before_filter CASClient::Frameworks::Rails::Filter, :only => [:home, :contact_us, :terms, :cas_login]
  # instead use gateway-login filter
  before_filter :cas_gateway_login, :only => [:home, :contact_us, :terms, :cas_login]

  # ... lots of actions and stuff here

  #####################################################################################
  private
    
    # This before_filter method is used to both call the GatewayFilter and
    # also to then call the setup_cas_user method.  Note that the latter
    # will already have been called on an action, but as we declare the
    # GatewayFilter *after* this, it must be declared again.  So we use this
    # method to make sure that we do both of these in the requisite
    # before_filter.
    def cas_gateway_login
      return false unless CASClient::Frameworks::Rails::GatewayFilter
      setup_cas_user # setup @cas_current_user etc for use by other methods
    end
end # controller

After this, you can use the logged_in? method to determine whether or not to display extra navigation features.

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

No comments: