May 23, 2010

Rails: Restful Authentication Quick Start

I almost always use Restful Authentication for my Rails applications. (For those of you who don't know what Restful Authentication is, it's a widely used Rails plugin for managing user authentication. In short, it's a plugin/gem that easily allows you to have users logins/etc on your application without the hassle of coding and debugging the entire thing yourself. The source code can be found on technoweenie's GitHub here.)

What's annoying to me is that I always forget how to set it up, and I hate going through loooong Restful Auth tutorial sites to find the specific commands/code snippets that I need. So here's what you need to set it up, short and sweet!

Installing the plugin

If this doesn't work, just download straight from the GitHub (link above) and include it in your vendor/plugins folder

ruby script/plugin install restful_authentication


Generate all necessary files. Skip the --include-activation part if you doesn't want users to have to "activate" their accounts via email.

ruby script/generate authenticated user sessions --include-activation

My generator fills in all the necessary routes automatically, but here they are just in case.

map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'

How to use

Include this line in your ApplicationController:

include AuthenticatedSystem

Include this filter in any controller where you want users to log in before they see content. You can selectively filter certain methods with the only keyword.

before_filter :login_required

Up to this point, the application should work for simple user authentication without activation by email (let me know if I'm missing anything!). I'll be writing more on activation as soon as I remember how I did it before.