Rails Expiration of Sessions due to Inactivity

In some apps (some may argue most) session management is a critical aspect for performance and control of the system. From a sysadmin point of view it doesnt make a lot of sense to let a session stay connected forever since it will hog resources that could be put elsewhere.

So here is a way to expire sessions that become inactive in rails:

before_filter :session_expire


  private
  def session_expire
    if session[:user]
      session_length = 60*10 #10 Minutes for logged in users
      expire_time = session[:expire_time] || Time.now + 10
      if expire_time < Time.now
        reset_session
        flash[:notice] = "You have been logged out due to an extended period of inactivity"

        redirect_to :controller => 'welcome' , :action => 'index'
      else
        session[:expire_time] = Time.now + session_length
      end
    end
  end