开发者

How to handle the expiration of login cookies if a user is inactive for more than a set time using Ruby on Rails?

I am trying to manage the login session of users that navigate in my RoR3 application.

I set a cookie when they sign in and I would like that their authentication expires after a few minutes of inactivity, for example 1开发者_C百科5 minutes.

How to achieve that?


This doesn't directly answer your question, but I strongly suggest using something like Devise for authentication instead of rolling your own.

Devise provides a timeoutable configuration flag, as well as a timeout value covering how long user sessions can be inactive before being logged out.


You could setup a property in your session. Something like

session[:expire_time] = 15.minutes.since

Then, in your applicationController you can check if your user has been away enough time to be logged out, if not then you renew his expiration time, something like:

 class ApplicationController < ActionController::Base
   before_filter :check_expire

   def check_expire
     if session[:expire_time] and session[:expire_time] < Time.now
       #your code to logout the user
     else
       session[:expire_time] = 15.minutes.since
     end
     return true
  end
end


You can also set the expiration time of the cookie that sets their session. In your configuration :

env["rack.session.options"][:expire_after] = 15.minutes

This works perfectly for the use case you described, because it will be reset every time the server responds, but it gives you a little less control.

Here's a good article about it :

http://augustl.com/blog/2010/dynamic_session_expiration_time_in_rails_3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜