2010-02-04 106 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