While sessions expand your application-building possibilities,
almost any interactive application that will be around for a while needs
to be able to keep track of users. You might be a little startled to hear
that Rails itself doesn’t include any mechanisms for tracking users,
unlike most current web frameworks. That isn’t so much a failure as an
opportunity for developers to create their own authentication approaches.
When getting started, however, it’s
probably wisest to work with the commonly used restful_authentication
plug-in. (The code for this example is available in
ch14/students007.)
Note that the restful_authentication
plug-in is based on the
older acts_as_authenticated
plug-in.
Many applications use, and much documentation describes, acts_as_authenticated
, which has similar data
structures but doesn’t operate in a RESTful way.
Authentication is a complicated enough project that it’s worth fitting
into a more sophisticated application, like the students and courses
example. The first step toward adding authentication to it is to install
the restful_authentication
plug-in.
From the application directory, enter:
$script/plugin install http://svn.techno-
weenie.net/projects/plugins/restful_authentication
In Heroku, you’ll want to use the Gems & Plugins link under the vendor folder in the editor. In addition to the usual list of files being added, this installer reports some documentation and security issues. Definitely read through this information, though it may make more sense when you’ve used the plug-in for a while.
More recent versions of restful_authentication
have moved to a
different location, git://github.com/technoweenie/restful-authentication.git.
Using that version, which has changed slightly from the one described
here, will require you to install Git on your computer. For more on
Git, see http://git.or.cz/.
The next step is using the plug-in to generate the many classes
needed to actually implement authentication. While the generator can
take many arguments, the two most important at the outset are what you
want to call your user model and what you want to call your session
model. For now, user
and session
make sense:
$ script/generate authenticated user session
The documentation suggests sessions
instead of session
. It’s not entirely clear why, but we
find session
makes for more
readable code, if a tiny bit more work. Others seem to do the same as
well.
Running this script/generate
also brings up some documentation beyond the usual list of files,
including suggestions for routes that would use some of the initially
generated methods. Integrating it into an existing application will take
this work down a slightly different path, but the general idea—having
users sign up, log in, and log out—remains the same.