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

两盒软妹~` 提交于 2019-12-30 09:32:10

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/2203777/ruby-on-rails-authlogic-periodically-check-if-user-session-is-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!