Rails会话超时并重定向到登录页面

时间:2013-06-18 15:50:56

标签: ruby-on-rails session-timeout

我想在会话到期后执行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来使其工作。任何人都可以给我一些想法或一些我可以遵循的好教程。万分感谢。

3 个答案:

答案 0 :(得分:0)

您希望在每个请求上运行before_filter,而不仅仅是登录。

before_filter :session_expires, :only => [:login]替换为before_filter :session_expires

答案 1 :(得分:0)

我建议您查看本指南 - 为什么不应该自己进行身份验证

The definitive guide to form-based website authentication

有一个很好的Ruby / Rails解决方案 - Devise gem https://github.com/plataformatec/devise

如果您需要对某些外部api进行身份验证,请在此处使用looke https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP
http://4trabes.com/2012/10/31/remote-authentication-with-devise/

答案 2 :(得分: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