Returning Users With Cookies

Fri Apr 03 00:00:00 -0700 2009

It’s a common challenge: once a user has logged in, or registered, or finished resetting a password, where do you send him? Ideally you send him to where he wants to be, but is that the same place as where he entered the login or registration pipeline? Has it changed since then?

The common solution packaged with restful_authentication is to set and maintain session[:return_to]. This requires setting save points by either tracking where the user was trying to go (request.url) or where the user just came from (request.referer). This works pretty well, but I’m trying something different — cookies. It just feels … simpler.

The code looks like this:

class ApplicationController < ActionController::Base
  before_filter :set_save_point
  
  def set_save_point
    if request.get?
      cookies[:last_page] = {
        :value => request.url,
        :expires => 30.minutes.from_now
      }
    end
  end

  def landing_page(default = nil)
    cookies[:last_page] || default
  end

  def return_or_continue_to(default = nil)
    redirect_to landing_page(default)
  end
end

Then for any action where you take sidetracks (logging in, registering, resetting password, etc.) you simply skip the set_save_point filter. Like so:

class SessionsController < ApplicationController
  skip_before_filter :set_save_point
end

class UsersController < ApplicationController
  skip_before_filter :set_save_point, :only => [:new, :create]
end

Beautiful. Simple. Set and forget. No database access. Is it better than session[:return_to]? I’m still deciding …