Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails - Authlogic : periodically check if user session is valid

I'm looking for a solution allowing me to check periodically if the user session has expired and if so redirect him to the login page.
I'm using Authlogic gem, so what I'm doing is call a function that make a test on current_user.
My USER_SESSION_TIMEOUT is 5minutes so I make this ajax call every 5:10 minutes.

<%= periodically_call_remote :url => {:controller => 'user_session', :action => 'check_session_timed_out'}, :frequency =>  (USER_SESSION_TIMEOUT + 10.seconds) %>

def check_session_timed_out
   if !current_user
      flash[:login_notice] = "Your session timed out due to a period of inactivity. Please sign in again."
      render :update do |page|
          page.redirect_to "/user_sessions/new"   
      end
   else
       render :nothing => true
   end
end

I noticed that every time I call current_user the user object is updated and so the session is renewed to 5 minutes.
There is no problem when only one tab is opened but if I have 2 tabs each time I call check_session_timed_out current_user renew update the user and so the session never expires.

any idea? Thanks

like image 504
Mathieu Avatar asked Feb 04 '10 22:02

Mathieu


2 Answers

Authlogic can do this for you. Just use in your models:

On User model:

acts_as_authentic do |c|
  c.logged_in_timeout(5.minutes)
end

... and on UserSession model:

self.logout_on_timeout = true

And simply work! =D

like image 103
nanda Avatar answered Oct 21 '22 03:10

nanda


From the AuthLogic source itself:

# For example, what if you had a javascript function that polled the server
# updating how much time is left in their session before it times out. Obviously
# you would want to ignore this request, because then the user would never
# time out. So you can do something like this in your controller:

def last_request_update_allowed?
 action_name != "update_session_time_left"
end

In your case, you would want to add the method to your controller using the name of your action:

def last_request_update_allowed?
  action_name != "check_session_timed_out"
end
like image 43
Jeff Dallien Avatar answered Oct 21 '22 04:10

Jeff Dallien