Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way of making rails sessions persist between browser restarts

What is the easiest way of implementing cookies such that the session persists between browser restarts?

like image 865
meow Avatar asked Dec 29 '22 01:12

meow


2 Answers

The best thing to do is use what's called a remember me cookie. Since a session cookie will not persist between browser restarts, you need to use some other kind of cookie that indicates to your application that the user is who they say they are. Most commonly the remember me functionality is implemented by having the user select that they would like the application to remember them. What happens then is that you need to create a cookie that will act as a password for that user. Typically you want to do the following:

  • Select an attribute related to the user that the user is not able to access or view. For example, the time their account was created, or some randomly generated string you store for them.
  • Hash this attribute so the cookie value is not recognizable.

Here is an example:

identifier = current_user.id
value = Digest::SHA1.hexdigest(current_user.created_at)[6,10]

cookies['remember_me_id'] = {:value => identifier, :expires => 30.days.from_now}
cookies['remember_me_key'] = {:value => value, :expires => 30.days.from_now}

Finally, when you are checking if a user is logged in, you'll need to check if they are logged in using a remember cookie as well. For example:

def current_user
  current_user ||= login_from_session || login_from_cookie
end

def login_from_session
  current_user = User.find(session[:id]) unless session[:id].nil?
end

def login_from_cookie
  user = User.find(cookies['remember_me_id'])
  if cookies['remember_me_key'] == Digest::SHA1.hexdigest(user.created_at)[6,10]
    current_user = user
  else
    nil
  end
end

This should get you started on your way to implementing cookies that will persist outside of a browser restart.

like image 142
Pan Thomakos Avatar answered Jan 13 '23 12:01

Pan Thomakos


If you want your cookie to last forever, you can do:

cookies.permanent[:foo] = "bar"

See the cookies documentation at http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html

like image 36
cam Avatar answered Jan 13 '23 11:01

cam