mose
mose

Reputation: 40

Rails temporary session cookies & db reset

I'm working through the Michael Hartl's Rails tutorial, and there's a section where he has you seed the development database with fake users. The first step in this process is running rails db:migrate:reset and then you run db:seed.

When I ran these commands, I happened to be logged in to the app in the browser. I therefore still had a temporary session cookie (set via session[:user_id] = user.id) stored in my browser. The ID of my user was 3.

As a consequence of this, I found that upon seeding the database, I could refresh the browser and be logged in as the new user whose ID is now 3.

Related to this: logging out of the application deletes the session cookie (via session.delete(:user_id)). But I found that if you were to (1) copy the cookie when you are logged in, (2) log out and close the browser, and (3) reuse the copied cookie (either in the same browser, or another machine/browser), you would still be automatically authenticated and logged in, without needing user/pass. Is there a standard way to prevent a particular cookie from being used again after logout?

Both of these cases work because the first conditional in this current_user method passes and assigns the ID # to user_id:

# Returns the current logged-in user (if any).
def current_user
  if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
  elsif (user_id = cookies.signed[:user_id])
    user = User.find_by(id: user_id)
    if user && user.authenticated?(cookies[:remember_token])
      log_in user
      @current_user = user
    end
  end
end

Perhaps both of these scenarios are very rare cases. In the first case, I imagine reseting the database of a production application is very undesirable, as would be any reassignment of record IDs. Still, I'm wondering how concerning this situation is and what measures are typically implemented to avoid it. Many thanks!

Upvotes: 1

Views: 1312

Answers (1)

Tom Aranda
Tom Aranda

Reputation: 6036

According to this answer, if you are using file based sessions, you can clear all of your Rails sessions using:

bundle exec rake tmp:sessions:clear

If you are using database sessions you can run this to clear all sessions:

bundle exec rake db:sessions:clear

You could also invalidate sessions be changing the secret_key_base in config/secrets.yml.

This should clear all of the sessions for all of the users. It will log every user out and invalidate their sessions, but it is the most secure way of ensuring old cookies cannot access user data after you migrate your database.

Upvotes: 1

Related Questions