Skip to content

Instantly share code, notes, and snippets.

@chandracarney
Last active August 29, 2015 14:10
Show Gist options
  • Save chandracarney/e873bea61e8dbdd4b1b8 to your computer and use it in GitHub Desktop.
Save chandracarney/e873bea61e8dbdd4b1b8 to your computer and use it in GitHub Desktop.
Carts: Sessions and Cookies
1. What's the difference between a cookie and a session?
Session is a concept, cookie is a tool
A cookie is part of the response from the server to the client, it is a string of data. Client receives the encrypted cookie from the server, performs no action, they just store it. When client makes their next request from the server, it sends the encrypted cookie and the server can verify that it created it. If you have tampered with the cookie, the server will not recognize it and it will say something like "your session has expired". Want to store as little information as possible in the cookie. Can use a "replay attack" to generate a new cookie.
CSRF token helps block some bad requests. In the session, data will persist across all requests. We are getting back. The session method uses the cookie to store its data. You can store a little or a lot of data in the cookie. You have to have a cookie in order to have sessions. Could create a policy in the client-side that expires cookies in one week. Most policies happen on the server side: setting a timestamp to expire.
Cookies have a fixed max size. 512 kb of data. It may be a good idea to store a little bit of data in the cookie, not a lot
There are three types of attacks:
1. listening
2. replay
3. editing
When using before_action and before_filter: never use :only, use :except (black list is listing out the bad ones)
(in Application Controller)
def load_cart
@cart = Cart.new(session[:cart])
end
(in other Controllers)
before_action: :load_cart
2. What's serialization and how does it come into play with cookies?
Serialization is the process of turning rich objects into strings. JSON, XML, YML are examples we can use. The client never does anything with the cookie so the server can serialize in the same way that it output it. You can store strings, integers, hashes, arrays. If you store a symbol in your session, it will come back as a string and will not match (don't do this).
3. Can a cookie be shared by more than one user? How/why?
Nope.
4. What would it mean to store a shopping cart in a cookie?
A shopping cart cookie would store all of your cart info, even if you left the page and navigated back
5. What advantages/disadvantages are there between cookie-stored carts and database-stored carts?
Databases may not be practical for most cases. Use REDIS to store things unless it is not in REDIS, then fetch it from the database and load it in REDIS
----------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment