Home arrow Ruby-on-Rails arrow Page 4 - Login Systems and More with Ruby on Rails
RUBY-ON-RAILS

Login Systems and More with Ruby on Rails


In this third article of a six-part series covering web development and Ruby on Rails, you'll learn how to add some very desirable features to your web application. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 39
April 05, 2007
TABLE OF CONTENTS:
  1. · Login Systems and More with Ruby on Rails
  2. · 15.9 Storing Hashed User Passwords in the Database
  3. · 15.10 Escaping HTML and JavaScript for Display
  4. · 15.11 Setting and Retrieving Session Information

print this article
SEARCH DEVARTICLES

Login Systems and More with Ruby on Rails - 15.11 Setting and Retrieving Session Information
(Page 4 of 4 )

Problem

You want to associate some data with each distinct web client that's using your application. The data needs to persist across HTTP requests.

Solution

You can use cookies (see Recipe 15.12) but it's usually simpler to put the data in a user's session. Every visitor to your Rails site is automatically given a session cookie. Rails keys the value of the cookie to a hash of arbitrary data on the server.

Throughout your entire Rails application, in controllers, views, helpers, and mailers, you can access this hash by calling a method called session. The objects stored in this hash are persisted across requests by the same web browser.

This code in a controller tracks the time of a client's first visit to your web site:

  class IndexController < ApplicationController
    def index
      session[:first_time] ||= Time.now
    end
  end

Within your view, you can write the following code to display the time:*

  <!-- index.rhtml -->
  You first visited this site on <%= session[:first_time] %>.

  That was <%= time_ago_in_words session[:first_time] %> ago.

Discussion

Cookies and sessions are very similar. They both store persistent data about a visitor to your site. They both let you implement stateful operations on top of HTTP, which has no state of its own. The main difference between cookies and sessions is that with cookies, all the data is stored on your visitors' computers in little cookie files. With sessions, all the data is stored on the web server. The client only keeps a small session cookie, which contains a unique ID that's tied to the data on the server. No personal data is ever stored on the visitor's computer.

There are a number of reasons why you might want to use sessions instead of cookies:

  1. A cookie can only store four kilobytes of data.
  2. A cookie can only store a string value.
  3. If you store personal information in a cookie, it can be intercepted unless all of a client's requests are encrypted with SSL. Even then, cross-site scripting attacks may be able to read the client cookie and retrieve the sensitive information.

On the other hand, cookies are useful when:

  1. The information is not sensitive and not very large.
  2. You don't want to store session information about each visitor on your server.
  3. You need speed from your application, and not every page needs to access the session data.

Generally, it's a better idea to use sessions than to store data in cookies.

You can include model objects in your session: this can save a lot of trouble over retrieving the same objects from the database on every request. However, if you are going to do this, it's a good idea to list in your application controller all the models you'll be putting into the session. This reduces the risk that Rails won't be able to deserialize the objects when retrieving them from the session store.

  class ApplicationController < ActionController::Base
    model :user, :ticket, :item, :history
  end

Then you can put ActiveRecord objects into a session:

  class IndexController < ApplicationController
    def index
      session[:user] ||= User.find(params[:id])
    end
  end

If your site doesn't need to store any information in sessions, you can disable the feature by adding the following code to your app/controllers/application.rb file:

  class ApplicationController < ActionController::Base
    session :off
  end

As you may have guessed, you can also use the session method to turn sessions off for a single controller:

  class MyController < ApplicationController
    session :off
  end

You can even bring it down to an action level:

  class MyController < ApplicationController
    session :off, :only => ['index']

    def index
      #This action will not have any sessions available to it
    end
  end

The session interface is intended for data that persists over many actions, possibly over the user's entire visit to the site. If you just need to pass an object (like a status message) to the next action, it's simpler to use the flash construct described in Recipe 15.8:

  flash[:error] = 'Invalid login.'

By default, Rails sessions are stored on the server via the PStore mechanism. This mechanism uses Marshal to serialize session data to temporary files. This approach works well for small sites, but if your site will be getting a lot of visitors or you need to run your Rails application concurrently on multiple servers, you should explore some of the alternatives.

The three main alternatives are ActiveRecordStore, DRbStore, and MemCacheStore. ActiveRecordStore keeps session information in a database table: you can set up the table by running rake create_sessions_table on the command line. Both DRbStore and MemCacheStore create an in-memory hash that's accessible over the network, but they use different libraries.

Ruby comes with a standard library called DRb that allows you to share objects (including hashes) over the network. Ruby also has a binding to the Memcached daemon, which has been used to help scale web sites like Slashdot and LiveJournal. Memcached works like a direct store into RAM, and can be distributed automatically over various computers without any special configuration.

To change the session storing mechanism, edit your config/environment.rb file like this:

  Rails::Initializer.run do |config|
    config.action_controller.session_store = :active_record_store
  end

See Also

  1. Recipe 15.8, "Creating a Login System," has an example using flash
  2. Recipe 15.12, "Setting and Retrieving Cookies"
  3. Recipe 16.10, "Sharing a Hash Between Any Number of Computers"
  4. Recipe 16.16, "Storing Data on Distributed RAM with MemCached" 
  5. http://wiki.rubyonrails.com/rails/pages/ HowtoChangeSessionOptions

Please check back next week for the continuation of this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials