【问题标题】:Set Session Expiry - Rails 3设置会话到期 - Rails 3
【发布时间】:2013-04-11 20:22:34
【问题描述】:

我有一个应用程序,我在其中使用http://ruby.railstutorial.org/chapters/a-demo-app?version=3.0#sec:planning_the_applicationhttp://ruby.railstutorial.org/chapters/sign-in-sign-out#sec-signin_failure (Rails 3.2) 提供的教程来创建我的用户和会话模型。

如果用户处于非活动状态 5 分钟左右,我想实现过期。我试过了:

config.timeout_in = 5.minutes in my **application.rb**

config.session_store :cookie_store, key: 'blanked_out', :expire_after => 2.minutes in my **session_store.rb**

这些似乎都不起作用。

有什么建议吗?

会话助手

def sign_in(user)
  cookies.permanent[:remember_token] = user.remember_token
  self.current_user = user
end

def sign_out
  self.current_user = nil
  cookies.delete(:remember_token)
end

def current_user
   @current_user ||= User.find_by_remember_token(cookies[:remember_token])
end

【问题讨论】:

    标签: ruby-on-rails-3 session


    【解决方案1】:

    你试过了吗?

    编辑:

    MAX_SESSION_TIME = {enter time}
    
    before_filter :verify_session
    
    def verify_session
    
       if !session[:expire].nil? and session[:expire] < Time.now
          # Session has expired. Clear or reset session.
          reset_session
       end
    
       # Assign a new expiry time, whether the session has expired or not.
       session[:expire] = MAX_SESSION_TIME.seconds.from_now
       return true
    end
    

    【讨论】:

    • 在您的控制器中,您可以使用该行定义一个方法 expire_session ,然后设置一个 before_filter :expire_session ,其中您不希望包含它的参数除外。
    • 还是不行。尝试使会话过期并强制用户注销似乎没有任何作用
    【解决方案2】:

    我在研究 CookieStore 问题时遇到了以下问题。我认为它回答了你的问题:

    https://www.coffeepowered.net/2013/09/26/rails-session-cookies/

    下面是 Chris Heald 建议使用 CookieStore 添加会话超时的代码(请注意,这将放在您的 application_controller.rb 文件中:

    class ApplicationController
      before_filter :validate_session_timestamp
      after_filter  :persist_session_timestamp
    
      SESSION_TTL = 48.hours
      def validate_session_timestamp
        if user? && session.key?(:ttl) && session[:ttl] < SESSION_TTL.ago
          reset_session
          current_user = nil
          redirect_to login_path
        end
      end
    
      def persist_session_timestamp
       session[:ttl] = Time.now if user?
      end
    end
    

    【讨论】:

    • 您可能想从链接中添加一些详细信息到您的答案中。
    猜你喜欢
    • 1970-01-01
    • 2011-08-17
    • 2012-02-05
    • 1970-01-01
    • 2020-02-09
    • 2018-05-11
    • 1970-01-01
    • 2023-03-27
    • 2013-07-03
    相关资源
    最近更新 更多