Closing a session and redirecting to login in Ruby on Rails

I work with session[:hash_name] in ruby ​​on rails to save session information such as username and more.

I am trying to find a way to end this session without having to log out. Especially in two cases: after a while it should expire and when the user closes the browser.

So far, I have found another parameter called cookies[:hash_name] , which expires after a while. But I'm not sure how to check this parameter in each user request, and then call reset_session. When the reset session I need to redirect the user to the login page.

Any suggestion to solve these two problems is greatly eluded.

+7
source share
3 answers

You can save the session in a cookie, which is the session cookie by default (which means that it disappears when the user closes the browser) and adds the expiration time with :expire_after .

This can be configured in config/initializers/session_store.rb . For example:

 Yourapp::Application.config.session_store :cookie_store, key: 'your_session_id', expire_after: 45.minutes 
+5
source

Well, I’m sure that if you run session.delete(:hash_name) , which destroys the session, however, it is strongly recommended not to try to create your own authentication system, especially if you need time to create the simplest functionality, while a ready-made solution can be installed in 20 minutes. Not only this, but the turnkey solution is probably twice as secure as anything you can prepare yourself, because it has been tested and tested by many developers.

I highly recommend using an authentication program. Using the method, you get methods such as sign_out(current_user) , which, obviously, gives the user a query. Take a look at the github page

All that is required is a gem install devise , add it to your gemfile and run

rails g devise:install User # or whatever model name

And they handle the rest

+1
source

I assume that you are using your own authentication method. So, for Scenario 1 (i.e. Session expiration after several times) you can do something similar to the one below:

 def create_session if session[:hash_key] destroy_session if session[:last_login] < 10.minutes.ago session[:last_login] = Time.now else ... authenticate session[:last_login] = Time.now end end def destroy_session reset_session end 

For scenario2 (for example, when closing the browser) you can call the jquery event handler and do something like below:

 $('window').unload(function(){ //call to destroy session method }); 
0
source

All Articles