Sessions in Rack

The value of state is a pretty frequent topic in our office. State can make code more complex as there are more areas prone to unrelated changes, but state has a time and place. As always, context is important.

It is possible to write a web app that does not need state to be stored and reads a new board object from a post request each time a move is made through a click. This sends data across via a post request. It is also possible to store this data in a Session.

Session::Cookie

A session is able to store the same information that would ordinarily be sent via a post request in a Session Cookie. This is known as session based cookie management and Rack has different ways to implement cookies. A session is stored as text and is normally under 4 kilobytes stored on the user’s computer by a web server.

Here is an example of a Session Cookie:

use Rack::Session::Cookie, :key => 'rack.session',
:domain => 'foo.com',
:path => '/',
:expire_after => 2592000, (seconds)
:secret => 'change_me',
:old_secret => 'also_change_me'

As you can see a session is a Ruby hash that is stores information about that particular user session. This makes it possible for redirects to know the stored parameters of a hash.

If you do not provide a secret the following warning pops up:

SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
This poses a security threat. It is strongly recommended that you
provide a secret to prevent exploits that may be possible from crafted cookies. This will not be supported in future versions of Rack, and future versions will even invalidate your existing user cookies.

This warning pops up because it might be possible for someone to forge the secret if it has not been explicitly set and they could hack your app.

Session::Pool

It is also possible to use Rack::Session::Pool which only saves IDs in the cookie and stores the information in the form of an instance variable. You can store objects in a session pool too which makes them useful when you need to access different objects across routes. However, the data is also lost when you restart the app, so that is something to bear in mind.

There is discussion as to when not to use sessions and the problems they can cause for security and latency, but for a simple Tic Tac Toe game, they seem to be quite useful!

Related Sites:

http://blog.ianmiller.nyc/2014/09/29/working-with-rack-sessions/

http://www.rubydoc.info/github/rack/rack/Rack/Session/Cookie

http://wonko.com/post/why-you-probably-shouldnt-use-cookies-to-store-session-data