设置会话到期 - Rails 3

时间:2013-04-11 20:22:35

标签: ruby-on-rails-3 session

我有一个应用程序,我使用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

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

编辑:

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

答案 1 :(得分:0)

我在研究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