Hi, this blog is no longer maintained, my new blog is here

Ruby On Rails and a Conning Israeli entrepreneur

Periodical AJAX requests and Session Expiry

My current applicaiton requires a session expiry feature, so fat, pretty ordinary, i decided to use the limited sessions plugin, as i always do.
The problem came up when i found out, that sessions aren't being released after the desired time had passed.
What was the problem?

first we will need to understand how rails uses sessions, basically it's something like that

  • session is retrieved from whereever it is. (ActiveRecordStore,CookieStore...)
  • Controller#Action is being preformed
  • Session is saved
now, where is the problem? when using periodical ajax calls, the session is being updated as it is after every action, so the 'updated_at' field, (required by the plugin) is updated, what causes the expiry interval (assuming it's bigger than the periodical AJAX calls's interval) to never be met. so no session expiry.

Solution

In my application.rb, i have a before_filter which updated the session with user_id in order to relate the session to the user, i migrated another field into the session table so i can keep my own track over changes, named it 'last_updated' like that

class AddCustomUpdateDateToSessions < ActiveRecord::Migration
  def self.up
    add_column :sessions, :last_updated, :datetime
  end

  def self.down
    remove_column :sessions, :last_updated
  end
end
and changed the application.rb method to update the new field, instead of the 'updated_at' field, and prevented my AJAX requests to update to the session, no need.
before_filter :update_session
  def update_session
    unless request.xhr?
      if logged_in?
        if session.model.user_id.nil?
          session.model.update_attribute(:user_id, current_user.id)
        end
        session.model.update_attribute(:last_updated, DateTime.now)
      end
    end 
  end
(yeah, i know it can be done better.) i also needed to change all the 'updated_at' references to 'last_updated' field inside the plugin's limited_sessions.rb, in order to completely take control over the session update flag. now it's working and my ajax calls do not cause the expiry interval to expire.

0 comments:


The Web Ask eizesus.com

Subscribe

    follow me on Twitter

    Twiters Around

    About Me

    My photo
    I am a web developer for more than 9 years, managed, cried, coded, designed and made money in this industry. now trying to do it again.

    Labels