parm530
3/16/2018 - 1:41 PM

Rails Sessions

Using sessions, cookies, ...

What is a session?

  • Temporary store of data (user_id, preferred language)
  • Kept in the browser, usually for more then one request

Where to store a session?

  • Use a sessions_controller
  • Store a user's session:
#sessions_controller.rb
def create
  session[:current_user_id] = @user.id
end

#can be read in another controller, for example users_controller.rb
def index
  current_user = User.find_by_id(session[:current_user_id])
end

Basic Flow

  • When you send a request (and the link contains parameters) to your website, you are able to extract those sent parameters in the Rails param hash param[:user_id]

  • Rails then saves the params in a session cookie!

    • Rails stores the session under a single key, a single cookie, example: session_my_app
    • This session is located in config/initializers/session_store.rb in the following LOC: Rails.application.config.session_store :cookie_store, key: '_session_my_app'
  • Rails encrypts (for security reasons) and signs (to prevent users from tampering it) the session cookie

    • All rails app have a secret_key(found in config/secrets.yml):
    production:
      secret_key_base = <% ENV["SECRET_KEY_BASE"] %>
    
    • This key is used for encryption and signing cookies
    • When your app boots, Rails puts this key into a secret generator: Rails.application.key_generator
    • This creates some "secrets" and use those "secrets" to create an encryptor object: used to encrypt and decrypt cookies, the result (after decryption: json results of the params hash)
    • json because of the configuration in config/initializers/cookies_serializer.rb: Rails.application.config.action_dispatch.cookies_serializer = :json
  • Rails then sends the encrypted cookie back to the browser, browser stores the cookie.

    • In the case where you visit the app again, the browser has the session saved and can send the cookie to the server, where Rails will verify and decrypt it to be able to recognize who you are.
  • Rails can change the data in the cookie, this will overwrite the cookie and still be able to send the cookie back and forth between server and browser.


What are cookies?

  • When you request a webpage, the server can set a cookie when it responds back
  • Cookies expire faster (each time a new request is made)
  • Until the cookie expires, the browser will send the cookies back to the server
  • Pretty much similair to sessions, however ...

Differences

  • Cookies can only store about 4KB of data
  • Cookies are sent along with every request you make (bigger cookies means slower website response)