Restful Authentication with rails 2
20 Responses January 19th, 2008 | Ekerete.
I recently had to build an authentication system into a project and seeing as the restful authentication plugin was getting such buzz, I decided to try it out.
The problem was, most of the information I found on the internet was dated and I had to make a couple of changes to get it to work on Rails 2.0. This site and this forum post were really helpful. This post documents the steps I took (or rather, the steps I’ll take next time I use it) to get the plugin working. It assumes you already have a rails application running and want to add authentication to it.
- Install the plug-in
Open up a console window and navigate to the root of your application.
Use script/plugin to install the plugin.ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication/ - Run the generator
The generator sets up your controllers, model, views and observer as well as modify the routes.rb file (sets up session and users as resources). The session controller is used for signing in and out of the system while the user controller takes care of the rest.If you do not need a user activation system built into the system, type the line below:
ruby script/generate authenticated user sessionsIf you need a user account activation system, use the line below. The rest of this post will assume the system includes user activation (the system is a lot simpler without user activation enabled).
ruby script/generate authenticated user sessions --include-activation - Run the migration
The system also generated a migration file. Run the migration with:rake db:migrate - Modify the routes file
Open up config/routes.rb and add to the named route section:map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'While the routes file is still open, add more named routes (giving the user actions nice, friendly urls)
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy' - Add an observer (required for user activation emails)
Add an observer to config/enviroment.rb (within the Rails::Initializer.run block) :config.active_record.observers = :user_observerAt this point, the basic system should be working. Start up your development server and go to http://localhost:3000/signup. You should see the sign up form.
Also try http://localhost:3000/login to confirm it’s fine. - Set up ActionMailer (required for user activation emails)
The rails config/environment.rb file includes a Rails::Initializer.run block and prior to Rails 2, configuration code went in there.
With Rails 2, there’s now a directory (config/initializers) where seperate, discreet bits of configuration are placed in files of their own.
These are automatically loaded after plugins are loaded when Rails starts up.Create a new file called mail.rb in the config/initializers directory (you can actually call the file anything you like). SMTP setting will go into this file.
Rails 2 also changed the variable for ActionMailer settings from server_settings to smtp_settings
Place the following into the mail.rb file:ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "mail.example-domain.com",
:port => 25,
:domain => "www.example-domain.com",
:authentication => :login,
:user_name => "user@example-domain.com",
:password => "secret"
}:address and :port - Determines the address and port of the SMTP server you’ll be using. These default to localhost and 25 , respectively.
:domain - The domain the mailer should use when identifying itself to the server (usually the top-level domain name of the machine sending the email).
:authentication - One of :plain, :login or :cram_md5. Should be omitted if the server does not require authentication. Also omit :username and :password options if you omit this parameter.
:username and :password - Mail account login credentials. Required if :authentication is set. - Modify the activation email parameters
Open the production and development configuration files, config/environments/production.rb and config/environments/development.rb respectively.In the development config file:
SITE_URL = "localhost:3000"and in the production:
SITE_URL = "example-domain.com"You need to restart the server for these settings to take effect.Open app/models/user_mailer.rb. Change:
@body[:url] = "http://YOURSITE/activate/#{user.activation_code}"to:
@body[:url] = "http://#{SITE_URL}/activate/#{user.activation_code}"Change:
@body[:url] = "http://YOURSITE/"to:
@body[:url] = "http://#{SITE_URL}/"Change the setup_email block settings (ADMINEMAIL and YOURSITE) to your desired settings.
Open the email template files (app/views/user_mailer/activation.html.erb and app/views/user_mailer/signup_notification.html.erb) and modify as desired.
And that’s it. The system should now be working.
Note: You need to include flash[:notice] and flash[:error] in your templates or layout to view the status messages e.g. just before the <%= yield %> line in app/views/application.html.erb, type:
<p style="color: green"><%= flash[:notice] %></p>
<p style="color: #990000"><%= flash[:alert] %></p>




February 1st, 2008
Hi,
Great tutorial, but I seem to have a problem, when create a new user. The activation code staying empty. Any idea ?
Thanks
February 4th, 2008
Hi Max,
The activation code is created in a before_create method in the user model.
If your validation passes, this should be called (to generate the code) prior to being saved. Made any changes?
Let’s know how it goes.
March 1st, 2008
I’m getting this:
undefined method `activation_code=’ for #
Any ideas?
March 1st, 2008
In the routes file, confirm that in map.activate ‘/activate/:activation_code’ line, :activation_code is a symbol.
Let me know how it goes.
March 14th, 2008
Hi, I am getting exactly the same error and even after spending a few hours have no clue about whats wrong with it.
===================ERROR===================
undefined method `activation_code=’ for #
RAILS_ROOT: C:/railapps/user_management
Application Trace | Framework Trace | Full Trace
c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/attribute_methods.rb:200:in `method_missing’
app/models/user.rb:96:in `make_activation_code’
app/controllers/users_controller.rb:17:in `create’
==========================================
March 14th, 2008
Waiting for help, would appreciate it very much.
March 14th, 2008
Hi Ekerete,
I deleted everything and tried this same step by step guide and this time it will work without any error. I am still puzzled with this strange behavior.
Thanks for the great tutorial.
-Kumar
March 14th, 2008
Hi Kumar,
I just went through the same process now to doublecheck (things may have changed since I posted this) and it worked fine.
I did find an error though which I have corrected (The SITE_URL config item should not have the http//: in front of it) but that couldn’t have caused the problem you mentioned.
Glad it’s working for you now!
March 16th, 2008
[…] Restful Authentication with rails 2 (tags: rails ruby authentication) […]
March 16th, 2008
[…] der Großteil dieses Tutorials nicht auf meinem Mist gewachsen ist, sondern auf einem einem Blogeintrag von Ekerete Akpan basiert. Ich hab seinen Beitrag ins deutsche Übersetzt und einige Erweiterungen […]
March 20th, 2008
Great HOWTO Ekerete, thanks very much.
March 28th, 2008
Excellent tutorial. I’d also recommend setting this up with this tutorial (http://www.prestonlee.com/archives/63) in order to use gmail’s smtp to test emails on your localhost.
-Scott
March 29th, 2008
Thank you for the excellent work.
I have not installed smtp server and postfix because postfix in my system is not working . I got login session and signup pages. I have a minor problem now. Upon login, the page remains idle and does not jump to the list page.
Grateful if someone could advise me what is missing. Tks
March 31st, 2008
@dror,
Hopefully your problem should be solved by now.
Anyway, the redirect is controlled by the redirect_back_or_default method in the restful authentication plugin.
If you still have issues, holla.
April 24th, 2008
[…] Restful Authentication with rails 2 | AVNet Labs (tags: rails ruby rubyonrails authentication rest restful tutorial howto) Filed under del.icio.us | […]
April 28th, 2008
Wow thank you that worked really well for my new project!
April 29th, 2008
[…] ?????????? ??:Restful Authentication with rails 2 […]
May 15th, 2008
This is really cool — I have been knocking my head against the wall trying to figure out how to handle authentication with all of the millions of options out there, but (aside from one typo caused by yours truly) I got this working with little trouble - with one exception. The authentication emails don’t seem to be going out. I’ve double checked the info in the mail.rb file several times, but it should be correct.
Any ideas on what I could be missing? The account I want to send from is a subdomain of my main account but I have everything configured the way my smtp settings are in Outlook, so it SHOULD be correct, right?
Argh.
May 16th, 2008
Nevermind, I got it figured out.
May 16th, 2008
Hi,
just wanted to say u saved my day…. I’m using rails 2.0.2 and this was perfectly worked for me.
thankx and keep up the good work
cheers
sameera