Register now and start sharing your code snippets.
-->

How to install and use the restful_authentication Rails plugin

Ruby posted 8 months ago by christian

This is an adaptation of the restful_authentication screencast by Ryan Bates, which has an issue with Rails 2.0.3 that throws the following error:

   1  NameError (uninitialized constant SessionsController):
   2      /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:266:in `load_missing_constant'
   3      /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:453:in `const_missing'
   4      /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:465:in `const_missing'
   5      /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/inflector.rb:257:in `constantize'

Installing the restful_authentication plugin

   1  script/plugin source http://svn.techno-weenie.net/projects/plugins/
   2  script/plugin install restful_authentication

Generating the model and controller

   1  script/generate authenticated user sessions

Now run the migration:

   1  rake db:migrate

Configure routing

Open config/routes.rb and add the following routes:

   1  map.resources :users
   2  map.resource  :session
   3  
   4  map.signup '/signup', :controller => 'users', :action => 'new'
   5  map.login  '/login', :controller => 'sessions', :action => 'new'
   6  map.logout '/logout', :controller => 'sessions', :action => 'destroy'

Include restful_authentication in ApplicationController

First remove these lines from the users and sessions controllers:

   1  # Be sure to include AuthenticationSystem in Application Controller instead
   2    include AuthenticatedSystem

Now include restful_authentication in the application controller:

   1  class ApplicationController < ActionController::Base
   2    include AuthenticatedSystem

Integrate restful_authentication with your views

First let’s create a controller and view by executing the generate script:

   1  script/generate controller home index

Modify index.html.erb as follows:

   1  <h1>Welcome</h1>
   2  
   3  <% if logged_in? %>
   4    <p><strong>You are logged in as <%=h current_user.login %></strong></p>
   5    <p><%= link_to 'Logout', logout_path %></p>
   6  <% else %>
   7    <p><strong>You are currently not logged in.</strong></p>
   8    <p>
   9      <%= link_to 'Login', login_path %> or
  10      <%= link_to 'Sign Up', signup_path %>
  11    </p>
  12  <% end %>

Start Rails and access your application. If needed, add the following to config/routes.rb to make the home controller the default:

   1  map.root :controller => "home"

Login, sign up and logout should work.

Tagged rails, ruby, authentication, restful_authentication