What is the easiest way of implementing cookies such that the session persists between browser restarts?
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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With