1

我想做 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 才能使其工作。谁能给我一些想法或一些我可以遵循的好教程。万分感谢。

4

3 回答 3

0

I suggest you take a look on this guide - why you shouldn't do authentication on your own

The definitive guide to form-based website authentication

There's an excellent solution for Ruby/Rails available - Devise gem https://github.com/plataformatec/devise

If you need to authenticate against some external api, take a looke here
https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP
http://4trabes.com/2012/10/31/remote-authentication-with-devise/

于 2013-06-18T18:33:01.770 回答
0

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

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

于 2013-06-18T15:56:04.897 回答
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
于 2014-08-12T07:06:52.133 回答