Dienstag, 30. September 2008

Sessions and, or Cookies

Rails 2.0 + uses a cookie on the client bowser to store session data. Sesion data is used to protect against misuse and data theft.

If the client browser has cookies disabled the application with throw an exception for any and all PUT, UPDATE and DESTROY requests.

To safeguard this you should diable any code that results in
PUT, UPDATE and DESTROY requests if cookies are disabled in the browser client.

Just add a protected method in the application controller.

helper_method :cookies_on?
protected

def cookies_on?
..request.cookies["_appname_session"].to_s.include?('_appname_session')
end


The "_appname_session" defalts to the name for your application and is defined in the app/config/environment.rb

config.action_controller.session = {
:session_key => '_appname_session',
:secret => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}


In your controllers and views you can now write:

<% if cookies_on? %>
# show the form with the submit button
<% else %>
# show the form without the submit button and display a message telling the user that this site protects the identiy of users with coded cookies and they cannot sumbit the form without cookies enabled in the browser.
<% end %>


As the session cookie won't be avilable until the user has loaded at least two pages of your application, until then your application will be in a state of "cookies disabled".

This is all a bit of a pain, especially in the light of mobile browsers, most of which do not support cookies. However in the light of data protection, there is a real need to come up with practices to deal with this. And rails does a great job - so lets not get pissed off with rails, but more with the twits that seem to think the web is some sort of data free for all.

BTW: Setting your own cookie is as easy as
cookies [:my_name_of_cookie]="hello this string will now be in a cookie in the users browser"

The next time the user views somthing you can read the cookie:
value=cookies[:my_name_of_cookie]
puts value ->
"hello this string will now be in a cookie in the users browser"

Keine Kommentare: