2010-02-04 58 views
5

我正在寻找一个解决方案,允许我定期检查用户会话是否已过期,如果是,则将其重定向到登录页面。
我使用的是Authlogic gem,所以我在做的是调用一个在current_user上进行测试的函数。
我的USER_SESSION_TIMEOUT为5分钟,所以我每5分钟做一次这个Ajax调用。Ruby on rails - Authlogic:定期检查用户会话是否有效

<%= 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 

我注意到,每次我打电话CURRENT_USER用户对象的时间进行更新,因此该会话被更新到5分钟。
当只打开一个选项卡时没有问题,但如果我每次调用check_session_timed_out时都有2个选项卡,则current_user更新将更新用户,因此会话永不过期。

有什么想法吗? 感谢

回答

5

从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 

在你的情况,你会想用你的行动的名称的方式添加到您的控制器:

def last_request_update_allowed? 
    action_name != "check_session_timed_out" 
end 
+0

MERCI!那很完美 – Mathieu 2010-02-05 00:59:06

6

Authlogic可以做到这一点为你。就在您的模型使用:

用户模型:

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

...和UserSession型号:

self.logout_on_timeout = true 

,简单地工作! = D