The best thing to do is use what is called Remember Me. Since the session cookie will not persist between browser restarts, you need to use some other cookie that tells your application that the user is who they say. Most often, the “remember me” function is implemented by the user selecting what they would like the application to remember them. Then what happens is that you need to create a cookie that will act as the password for this user. Usually you want to do the following:
- Select an attribute associated with the user that the user cannot access or view. For example, the time when their account was created, or some randomly generated line that you store for them.
- Hash this attribute, so the cookie value is not recognized.
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 check if the user is logged in, you will need to check if they are logged in using the cookie with the save. For instance:
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 help you get started with implementing cookies that will persist outside of restarting the browser.
source share