2013-06-18 82 views
1

我想在會話過期後做rails會話超時並重定向到登錄頁面。Rails會話超時並重定向到登錄頁面

這是我的應用程序控制器,似乎不工作。

class ApplicationController < ActionController::Base 

    protect_from_forgery with: :exception 
    before_filter :session_expires, :only => [:login] 

    def session_expires 
     a = session[:expires_at] 
     b = Time.now 
     minutes = (a - b)/1.minute 
     if b > a 
     reset_session 
     flash[:error] = 'Session Expire !' 
     render "sessions/new" 
     end 
    end 


end 

我不確定,我需要使用Jquery或Ajax來使它工作。任何人都可以給我一些想法或我可以遵循的一些很好的教程。萬分感謝。

+0

謝謝你!這很好用 –

回答

0

您想對每個請求運行before_filter,而不僅僅是登錄。

before_filter :session_expires, :only => [:login]替換爲before_filter :session_expires

+0

No其實,我想在登錄前運行這個會話執行。我想要做的是用戶登錄後,我將分配我的會話過期時間,例如(從現在開始分鐘),然後在一分鐘後頁面自動註銷並重定向到登錄頁面。請任何幫助。 –

+0

這個答案是好的,如果你不明白你可能應該看看鐵路指南http://guides.rubyonrails.org/getting_started.html –

0

我建議你把這個指南一看 - 爲什麼你不應該做驗證自己

The definitive guide to form-based website authentication

有可用的Ruby/Rails的最佳解決方案 - 設計寶石https://github.com/plataformatec/devise

如果您需要對某些外部API進行身份驗證,請在這裏進行身份驗證
https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP
http://4trabes.com/2012/10/31/remote-authentication-with-devise/

+0

謝謝你的回覆。我的問題是我不能像設計一樣使用gem,因爲我的應用程序的所有數據都來自數據庫api。所以我不需要創建活動記錄模型。那就是爲什麼我從頭開始進行所有認證。 –

+0

看到我改進的答案 –

0

我得到以下簡單的解決方案。

我在application.rb中添加了一個簡單的方法。它運作良好。

class ApplicationController < ActionController::Base 
    before_filter :session_expires 

    MAX_SESSION_TIME = 60 * 60 

    helper_method :current_user? 

    protected 

    def current_user? 
     if session[:user_id].nil? 
     false 
     else 
     true 
     end 
    end 

    def authorize 
     unless current_user? 
     flash[:error] = "Please Login to access this page !"; 
     redirect_to root_url 
     false 
     end 
    end 

    def session_expires 
     if !session[:expire_at].nil? and session[:expire_at] < Time.now 
     reset_session 
     end 
     session[:expire_at] = MAX_SESSION_TIME.seconds.from_now 
     return true 
    end 


    protect_from_forgery 
end 
相關問題