原创作者: hideto   阅读:1762次   评论:0条   更新时间:2011-05-26    
Rails的session默认为当用户关闭浏览器时终止
我们可以在config/environment.rb里设置它:
CGI::Session.expire_after 1.month

这需要一个插件,具体session设置请参考http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions
这不是今天我们讨论的重点

出于安全问题,有时候我们需要通知用户你的session快超时了,如在线银行系统等
让我们看看在Rails里怎样做

1,bank_account_controller.rb
class BankAccountController < ApplicationController
  before_filter :update_activity_time, :except => :session_expiry
  def update_activity_time
    session[:expires_at] = 1.minutes.from_now
  end
  
  def session_expiry
    @time_left = (session[:expires_at] - Time.now).to_i
    unless @time_left > 0
      reset_session
      render '/signin/redirect'
    end
  end
end

该controller里定义了update_activity_time这个before_filter,它设置session的超时时间,这里为了demo我们设置为1分钟

2,bank_account/index.rhtml
<html>
    <head>
        <%= javascript_include_tag :defaults %>
    </head>
    <body>
        <div id='header'></div>
        <%= periodically_call_remote :url => {
                :action => 'session_expiry'},
                :frequency => 1,
                :update => 'header' %>
        <div id='body'>Here's where your application's real functionality goes.</div>
    </body>
</html>

我们使用periodically_call_remote这个helper方法来每间隔1秒远程调用一次session_expiry这个action,并更新header这个div

3,bank_account/session_expiry.rhtml
<span style='color: read; font-weight: bold'>
    Your session will expire in <%= @time_left %> seconds
</span>

这里显示了我们的session还有多久会expire

4,signin/redirect.rjs
page << "window.location = '#{signin_url}';"

我们在session超时的时候自动redirect到signin_url(需要我们在routes.rb里定义)
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics