Restful Authentication with rails 2

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 sessions

    If 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_observer
    

    At 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:

    <%= flash[:notice] %>
    <%= flash[:alert] %>
    

Update: Need help with using the plugin in your view or controller? Go here.

No related posts.

This entry was posted in Rails. Bookmark the permalink.

59 Responses to Restful Authentication with rails 2

  1. max says:

    Hi,

    Great tutorial, but I seem to have a problem, when create a new user. The activation code staying empty. Any idea ?

    Thanks

  2. 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.

  3. asdx says:

    I’m getting this:

    undefined method `activation_code=’ for #

    Any ideas?

  4. Ekerete says:

    In the routes file, confirm that in map.activate ‘/activate/:activation_code’ line, :activation_code is a symbol.
    Let me know how it goes.

  5. Kumar says:

    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’

    ==========================================

  6. Kumar says:

    Waiting for help, would appreciate it very much.

  7. Kumar says:

    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

  8. Ekerete says:

    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!

  9. Pingback: links for 2008-03-16 | svenkubiak.de

  10. Pingback: RESTful Authentication mit Rails 2.0 Tutorial | svenkubiak.de

  11. Andy says:

    Great HOWTO Ekerete, thanks very much.

  12. Scott says:

    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

  13. dror chung says:

    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

  14. Ekerete says:

    @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.

  15. Pingback: links for 2008-04-24 at adoption curve dot net

  16. Wow thank you that worked really well for my new project!

  17. Pingback: ssonLogger» ???????? » rails?Restful Authentication

  18. Ryan says:

    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.

  19. Ryan says:

    Nevermind, I got it figured out.

  20. sameera says:

    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

  21. Pingback: Scott Motte » Blog Archive » Email validation/activation with rails

  22. Restful Guy says:

    this is not restful at all

  23. Ekerete says:

    @Restful Guy,
    The plugin is called restful authentication but even if you disregard that, REST is about resources and this solution treats both sessions and users as resources which are uniquely addressable.

    The sessions resource may not be completely stateless but then you can’t do authentication without being able to maintain state so for me that’s an acceptable compromise.

    Out of curiosity, how would you design a completely RESTful authentication system?

  24. Rails says:

    Hi guys,
    There’s no apparent error when I run the whole thing, but it takes about 20-30 secs to be redirected at the main page and I’ve got no message saying everything is ok. I think it’s because of bad smtp server config… Anyways, do you know a way of logging what’s happening with the smtp mail server connection so I can figure out what it is? (on the server console, it doesn’t look like there is this information)

    thanks

  25. Rails says:

    correction, apparently it sent the email but…
    Sent mail to xxx@gmail.com

    Date: Fri, 27 Jun 2008 15:21:12 -0400
    From: test@xxx.com
    To: xxx@gmail.com
    Subject: [localhost:3000]Please activate your new account
    Mime-Version: 1.0
    Content-Type: text/plain; charset=utf-8

    Your account has been created.

    Username: xxx
    Password: xxx

    Visit this url to activate your account:

    http://localhost:3000/activate/21491f0d38f62a4d67e7e126236b1f2cd76a6c7a

    on my gmail account theres nothing, no spam no nothing…
    So why does it say that?…

  26. Pingback: The San Francisco Software Company » LINK: Tutorial on restful authentication

  27. smerd says:

    Quick note for stupid newbs like me. This is need too, right?
    map.resources :usersmap.resource :session

  28. mojca says:

    Thanks a lot for your article.

    But since the plugin has now moved to git, it’s probably better to use

    ruby script/plugin install git://github.com/technoweenie/restful-authentication.git

    ?

  29. Ekerete says:

    @smerd,
    I’m sure you have this working by now but yes that should be in your routes file although you don’t have to add the lines manually.

  30. Pingback: Ramblings » Blog Archive » O_RLY? A Ruby/Rails implementation of snowl (Part I)

  31. Pingback: Restful-Authentication « ???????

  32. Sooshi says:

    2 questions. How do you go about ensuring that there is authentication before the user can see your page?

    question 2: I don’t know exactly where to put the flash for notice and alert because this file doesn’t exist for me:

    app/views/application.html.erb,

    Thanks!

  33. aris says:

    hi -

    this is good tutorial for me, thanks!

    about the mailer that doesnt send correctly,
    i’ve experienced at least in my country (Indonesia) some ISPs have like filtering to prevent/block/ignore mail to be sent through localhost,
    you maybe can try using other ISP?

  34. Joe Sak says:

    This works perfect except I don’t get how to protect my controllers that I want to required a logged in session for.

    How do I do that?

  35. palash says:

    Great tutorial, but having problem, when i am login error coming uninitialized constant SessionController, please help me

  36. palash says:

    great tutorial, but error is coming
    NameError in SessionController#create
    uninitialized constant SessionController

    RAILS_ROOT: ./script/../config/..
    Application Trace | Framework Trace | Full Trace

  37. Kumar,

    You might have an old version of the users table in your database. It’s missing the activation_code and activated_at columns. Create a migration to add these in:

    class FixUsers

  38. Denis Ivanov says:

    Great solution, great write-up! Thanks for the help. My system is implemented and working great.

    Much obliged.

  39. Marko says:

    I got the activation email working and it is creating the activation_code in the database. However, new users can still log in without activating. Isn’t it supposed to check to see if the user has been activated before allowing them to log in?

  40. Cedric Castel says:

    when I go to the signup page, I get a blank screen, and the login page generates a routes error :
    ‘session_url failed to generate from {:action=>”show”, :controller=>”session”} – you may have ambiguous routes, or you may need to supply additional parameters for this route. content_url has the following required parameters: ["session", :id] – are they all satisfied?’

    I don’t get it.
    Thanks for your help.

    My routes.rb contains the following :

    map.resources :session

    map.resources :users

    map.resources :suggestions

    map.resources :domains

    map.resources :subdomains

    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’

    map.connect ‘:controller/:action/:id’
    map.connect ‘:controller/:action/:id.:format’

  41. Ekerete says:

    @Cedric,

    Hopefully you’ve fixed your issue by now. Was away on holiday and had VERY limited access to the internet.

    Changing map.resources :session to map.resource session should fix the error since session is a ‘singleton’ resource (one user can only ever have one session).

    Running ‘rake routes’ from the console helps when debugging this type of issue.

    Hope that helps if you haven’t already fixed it.

  42. Adam D says:

    Thanks for the great tutorial!

    Everything appears to be working for me, except when I signup I get redirected to “users/” and get the standard error “We’re sorry, but something went wrong.”

    I do not get an email, and nothing gets put into the DB. Since the error (500) is so generic, how do I go about troubleshooting?

    Any help would be greatly appreciated.

    Thanks,
    Adam

  43. Ekerete says:

    @Adam,

    You are most likely running the app in production mode.
    In development mode you should get the stack trace.

    Alternatively, your log files (production.log or development.log in your logs folder) should also give an indication of the problem.

  44. Seth says:

    This is a great article. Now I need to figure how to set it up for multi-tier user privileges.

  45. Ekerete says:

    Thanks Seth.
    The Role Requirement plugin or the Rails Authorization plugin may be what you need.

    http://code.google.com/p/rolerequirement/

    http://github.com/DocSavage/rails-authorization-plugin/tree/master/

  46. DaveInFL says:

    Ekerete,

    Thanks for the article. Nice, clean and not too many steps :) I have everything working apart from actually receiving the email :( I am developing on a windows laptop but would still expect to receive the activation email. I have setup the smtp settings as I have them in my Outlook setup (which works just fine) so I’d expect the email to go out. Looking at the log file does not shed any light on the issue and in fact, everything looks just fine.

    If you can provide any help I’d appreciate it very much.

  47. Ekerete says:

    @DaveInFL

    Found a fix yet? Using smtp settings with authentication should work (at least it does with my host). Try turning on email delivery errors in your dev config file to see if it sheds more light.

  48. JJ says:

    Hello Ekerete.

    This is a great article! I have a problem regarding the setup of authentication emails though. It seems to send the email but I do not receive it, also, when I try to sign up with a previously used email address it gives an error that it is already in use. How can I go about fixing this? I use rails 2.0.2. I am not too experienced with this so it’s a bit intimidating.

    Also what I would like to know, does
    “:user_name => “user@example-domain.com”,
    :password => “secret” ”

    and

    “SITE_URL = “example-domain.com” ”

    have to be replaced with real working email address details? Like my personal username and password for my email account. I am only using http://localhost:3000/ for this application so what do I need to replace “example-domain.com” with?

    Sorry for the long question(s), and
    Thank you! :)

  49. JJ says:

    # Rails Says:
    June 27th, 2008

    correction, apparently it sent the email but…
    Sent mail to xxx@gmail.com

    Date: Fri, 27 Jun 2008 15:21:12 -0400
    From: test@xxx.com
    To: xxx@gmail.com
    Subject: [localhost:3000]Please activate your new account
    Mime-Version: 1.0
    Content-Type: text/plain; charset=utf-8

    Your account has been created.

    Username: xxx
    Password: xxx

    Visit this url to activate your account:

    http://localhost:3000/activate/21491f0d38f62a4d67e7e126236b1f2cd76a6c7a

    on my gmail account theres nothing, no spam no nothing…
    So why does it say that?…

    Mine does exactly the same thing now. These messages can be seen in the Ruby Console Window. But I don’t receive any email… ?

  50. Ekerete says:

    @JJ,

    I haven’t installed restful authentication in a while choosing instead to use Bort (http://github.com/fudgestudios/bort/tree/master).

    I just tried setting it up now and I also do not get the email even though the logs tell me it got sent. I suspect it has to do with my SMTP settings but I’m off to work soon and can only check it out and get back to you in the evening.

    Let me know if you find a fix.

  51. Pingback: 31 Fascinating Ruby on Rails Tutorials & Guides | Inquisitive Archive

  52. Pingback: 31 Fascinating Ruby on Rails Tutorials & Guides | rapid-DEV.net

  53. Pingback: Restful Authentication with rails 2 — lakehouse :labs

  54. Pingback: Ruby on Rails覚えるだ restful-authenticationのアクティベーション « Software Cosmology

  55. Could you recommend any specific resources, books, or other blogs on this topic?

  56. Yosh says:

    Great Work, Thank you

  57. Uttara says:

    Hey Thanks!!!

    You saved a Lot of time and Efforts!!

  58. aashish says:

    i am not receiving activation mail. can u help me
    my mail.rb is

    ActionMailer::Base.delivery_method = :smtp
    ActionMailer::Base.smtp_settings = {
    :address => “mail.gmail.com”,
    :port => 587,
    :domain => “localhost:3000″,
    :authentication => :plain,
    :user_name => “xxxxxxxx@gmail.com”,
    :password => “xxxxxxxx”

  59. Richie says:

    Brilliant tutorial, saved a lot of hassle.

    Back in love with Rails again!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>