Agile Web Development

Build it. Launch it. Love it.

Restful-authentication

This widely-used plugin provides a foundation for securely managing user
authentication:

  • Login / logout
  • Secure password handling
  • Account activation by validating email
  • Account approval / disabling by admin
  • Rudimentary hooks for authorization and access control.

Several features were updated in May, 2008.

!! important: if you upgrade your site, existing user account !! !! passwords will stop working unless you use —old-passwords !!

Issue Tracker

Please submit any bugs or annoyances on the lighthouse tracker at

For anything simple enough, please github message both maintainers: Rick Olson
(technoweenie) and Flip Kromer
(mrflip).


Documentation

This page has notes on

See the wiki
(or the notes/ directory) if you want to learn more about:

  • Extensions, Addons and Alternatives such as HAML templates
  • Security Design Patterns with snazzy diagram
  • [[Authentication]] — Lets a visitor identify herself (and lay claim to her corresponding Roles and measure of Trust)
  • Trust Metrics — Confidence we can rely on the outcomes of this visitor’s actions.
  • [[Authorization]] and Policy — Based on trust and identity, what actions may this visitor perform?
  • [[Access Control]] — How the Authorization policy is actually enforced in your code (A: hopefully without turning it into a spaghetti of if thens)
  • [[Rails Plugins]] for Authentication, Trust, Authorization and Access Control
  • [[Tradeoffs]] — for the paranoid or the curious, a rundown of tradeoffs made in the code
  • [[CHANGELOG]] — Summary of changes to internals
  • [[TODO]] — Ideas for how you can help

These best version of the release notes are in the notes/ directory in the
source code
— look there for the latest version. The wiki versions are taken (manually)
from there.



h2. Exciting new features

Stories

There are now Cucumber features that allow expressive, enjoyable tests for the
authentication code. The flexible code for resource testing in stories was
extended from Ben Mabey’s.

Modularize to match security design patterns:

  • Authentication (currently: password, browser cookie token, HTTP basic)
  • Trust metric (email validation)
  • Authorization (stateful roles)
  • Leave a flexible framework that will play nicely with other access control / policy definition / trust metric plugins

Other

  • Added a few helper methods for linking to user pages
  • Uniform handling of logout, remember_token
  • Stricter email, login field validation
  • Minor security fixes — see CHANGELOG

Non-backwards compatible Changes

Here are a few changes in the May 2008 release that increase “Defense in Depth”
but may require changes to existing accounts

  • If you have an existing site, none of these changes are compelling enough to
    warrant migrating your userbase.
  • If you are generating for a new site, all of these changes are low-impact.
    You should apply them.

Passwords

The new password encryption (using a site key salt and stretching) will break
existing user accounts’ passwords. We recommend you use the —old-passwords
option or write a migration tool and submit it as a patch. See the
[[Tradeoffs]] note for more information.

Validations

By default, email and usernames are validated against a somewhat strict pattern; your users’ values may be now illegal. Adjust to suit.



h2. Installation

This is a basic restful authentication generator for rails, taken from
acts as authenticated. Currently it requires Rails 1.2.6 or above.

IMPORTANT FOR RAILS > 2.1 USERS To avoid a NameError exception (lighthouse tracker ticket), check out the code to have an underscore and not dash in its name:

  • either use git clone git://github.com/technoweenie/restful-authentication.git restful_authentication
  • or rename the plugin’s directory to be restful_authentication after fetching it.

To use the generator:

./script/generate authenticated user sessions \ —include-activation \ —stateful \ —rspec \ —skip-migration \ —skip-routes \ —old-passwords
  • The first parameter specifies the model that gets created in signup (typically
    a user or account model). A model with migration is created, as well as a
    basic controller with the create method. You probably want to say “User” here.
  • The second parameter specifies the session controller name. This is the
    controller that handles the actual login/logout function on the site.
    (probably: “Session”).
  • —include-activation: Generates the code for a ActionMailer and its respective
    Activation Code through email.
  • -stateful: Builds in support for acts_as_state_machine and generates
    activation code. (@
    -stateful@ implies --include-activation). Based on the
    idea at [[http://www.vaporbase.com/postings/stateful_authentication]]. Passing
    --skip-migration will skip the user migration, and --skip-routes will skip
    resource generation - both useful if you’ve already run this generator.
    (Needs the acts_as_state_machine plugin,
    but new installs should probably run with @
    -aasm@ instead.)
  • —rspec: Generate RSpec tests and Stories in place of standard rails tests.
    This requires the
    RSpec and Rspec-on-rails plugins
    (make sure you “./script/generate rspec” after installing RSpec.) The rspec
    and story suite are much more thorough than the rails tests, and changes are
    unlikely to be backported.
  • —old-passwords: Use the older password scheme (see [[#COMPATIBILITY]], above)
  • —skip-migration: Don’t generate a migration file for this model
  • —skip-routes: Don’t generate a resource line in config/routes.rb


h2. After installing

The below assumes a Model named ‘User’ and a Controller named ‘Session’; please
alter to suit. There are additional security minutae in notes/README-Tradeoffs
— only the paranoid or the curious need bother, though.

  • Add these familiar login URLs to your config/routes.rb if you like:

map.signup  ‘/signup’, :controller => ‘users’,   :action => ‘new’
map.login  ‘/login’,  :controller => ‘session’, :action => ‘new’
map.logout ‘/logout’, :controller => ‘session’, :action => ‘destroy’
  • With --include-activation, also add to your config/routes.rb:

map.activate ‘/activate/:activation_code’, :controller => ‘users’, :action => ‘activate’, :activation_code => nil
and add an observer to config/environment.rb:

config.active_record.observers = :user_observer
Pay attention, may be this is not an issue for everybody, but if you should have problems, that the sent activation_code does match with that in the database stored, reload your user object before sending its data through email something like:

class UserObserver < ActiveRecord::Observer
def after_create(user)
user.reload
UserMailer.deliver_signup_notification(user)
end
def after_save(user)
user.reload
UserMailer.deliver_activation(user) if user.recently_activated?
end
end
  • With --stateful, add an observer to config/environment.rb:

config.active_record.observers = :user_observer
and modify the users resource line to read map.resources :users, :member => { :suspend => :put, :unsuspend => :put, :purge => :delete }
  • If you use a public repository for your code (such as github, rubyforge,
    gitorious, etc.) make sure to NOT post your site_keys.rb (add a line like
    ‘/config/initializers/site_keys.rb’ to your .gitignore or do the svn ignore
    dance), but make sure you DO keep it backed up somewhere safe.

Vitals

Home http://weblog.techno-weenie.net
Repository git://github.com/technoweenie/restful-authentication.git
License Rails' (MIT)
Rating (374 votes)
Owner Rick Olson
Created 22 August 2006

Comments

  • Avatar
    Matt Zukowski
    3 November 2006

    Just wanted to say that this is a really well thought out and implemented piece of code.

    Good job.

  • Avatar
    Erik Hetzner
    27 November 2006

    What is "restful" about using cookies for authentication?

  • Avatar
    Chris Dwan
    13 December 2006

    Erik: Looks to me like the auth is done via HTTP headers. Cookies are only (optionally) used for 'remember me' functionality.

  • Christopher York
    16 December 2006

    In both Rails 1.2RC1 and Edge Rails, I get the following:

    No such file or directory - script/../config/../vendor/plugins/restfulauthentication/generators/authenticatedmailer/templates/notifier.rb

    Suggestions?

  • Rudy Lu
    19 December 2006

    I found that in loginrequired of authenticatedsystem.rb, the following line: self.current_user ||= User.authenticate(username,passwd) || :false if username && passwd

    should be changed to

    self.current_user = User.authenticate(username,passwd) || :false if username && passwd

    otherwise, http authorization can't work.

  • R McAfee
    5 January 2007

    Thanks for the tip Rudy Lu!

  • Avatar
    Mercury
    19 January 2007

    I really like you plugin, and I am amazed how clean it is implemented.

    But I'm quite new to this rails thing, and I have one question: If you provide a bug fix/update for your plugin, how are the users able to implement these changes?

    For example, Rudy Lu mentions a bug here in the comments. You could release a new version that fixes the bug, but maybe I have already changed some of the generated files? What is the best practice to import the new code into my app?

  • Avatar
    20 January 2007

    <i>What is "restful" about using cookies for authentication?</i>

    In practice, you don't have much choice. The important thing is to treat it as a binary decision - the service either permits or rejects a user based on their cookie, and that's the only effect it has ... what you don't do is change how the service behaves, because that should be determined purely by the action and (optionally) the message.

  • Avatar
    Andrej Gombar
    27 January 2007

    This is just a comment for newbies out there (like me) that might be trying to use restful authentication in an existing app. When starting your application server (script/server) and you get this kind of error during server startup:

    action_controller/routing.rb:406:in initialize_components&#x27;: undefined methodfirst' for :users:Symbol (NoMethodError)

    It means that your environment is set to use an older version of Rails. If you're running Rails 1.2, then open environment.rb in your project and change the RAILSGEMVERSION line to say " RAILSGEMVERSION = '1.2' "

  • Avatar
    Patrick Leytham
    7 February 2007

    Was attempting to generate the authenticatedmailer, yet the error I recieve is, "Couldn't find 'authenticatedmailer' generator. I checked in my vendor/plugins/restful_authentication/authenticated/templates directory, and obviously the mailer isn't present. Wondering if this file was removed from the svn site? if so, where can I get it?

  • iMei
    12 February 2007

    Couldn't find 'authenticated_mailer' generator. What is wrong here ??

  • Avatar
    GregL
    12 February 2007

    Another newbie tip (from a newbie), look in your project's 'lib' folder and open and read the relevant files, ie. authenticated_system.rb. Much of the plugin's callable/useful methods are here.

  • Avatar
    15 February 2007

    The usercontrollertest functional test fails.

    1) Failure: testshouldactivate_user:64 <nil> expected to not be nil.

    The relevant code is:

    def testshouldactivate_user assert_nil User.authenticate('aaron', 'test') get :activate, :activationcode => users(:aaron).activationcode assertredirectedto '/' assertnotnil flash[:notice] assert_equal users(:aaron), User.authenticate('aaron', 'test') end

    Does anyone know why?

  • Avatar
    18 February 2007

    Another request for clarification on the authenticated_mailer.

  • Fyodor Golos
    21 February 2007

    Looks like Rails 1.2.2 is not happy about this in view: <%= linkto("Log out", sessionpath, :method => :delete) %>

    It gives the following error: sessionurl failed to generate from {:controller=>"sessions", :action=>"show"} - you may have ambiguous routes, or you may need to supply additional parameters for this route. contenturl has the following required parameters: ["sessions", :id] - are they all satisifed?

    Any suggestions as to how this should be addressed? I obviously do not want to expose current_user id in the URL. I will if I have to, but I would rather not.

  • 21 February 2007

    Fyodor 1.2.2 introduced singular resources, if you modify the generated files to match the new convention then it should old work.

    eg routes.rb
    map.resource :session

    sessionscontroller to sessioncontroller

    etc...

  • Fyodor Golos
    21 February 2007

    Answering my own questions... :)

    Rails 1.2.2 added a concept of "singular resources: http://weblog.rubyonrails.org/2007/2/6/rails-1-2-2-sqlite3-gems-singular-resources

    In a nutshell, SessionsController needs to be renamed to SessionController (note singular form), and map.resource(:session) needs tobe used instead of map.resources(:session) (again, note singular form). That should take care of it.

  • Nick Urban
    3 March 2007

    If you are using singular resources, don't forget to change sessionspath to sessionpath wherever it is needed (ie in app/views/session/new.rhtml).

  • BillSaysThis
    10 March 2007

    I think the --include-activation parameter replaces the separate mailer generator. Though I could be wildly incorrect.

  • NeoMike
    13 March 2007

    If you like actsasauthenicated you'll love restful auth.

  • Avatar
    Jim Morris
    7 April 2007

    It seems if you want to use the default activation code and templates you will need to add this to config/routes.rb

    map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'

  • Avatar
    JB
    1 April 2007

    Can't generate the mailer either. Here's what I get:

    ./script/generate authenticated_mailer user Couldn't find 'authenticated_mailer' generator

  • travis
    5 April 2007

    in authenticated.rb there is one instance of redirecttourl

    I had to change to to redirect_to

    I guess they took that method out of rails?

  • 23 April 2007

    The plugin has been modified since this post (thx to BillSays below) the new syntax for generating the mailer is -

    ./script/generate authenticated user --include-activation

  • Avatar
    25 April 2007

    Can someone point me to a tutorial that explains in a little bit more detail on how to use this? I see so many folks down in the comments section offering suggestions to this plugin that I don't understand the heads or tail of it. Can someone atleast aggregate the changes that are required to make this plugin work?

    Thanks

  • Avatar
    10 May 2007

    ¿Is there a download-able version?. I can't get the plugin because I'm behind a firewall. Thanks!

  • Avatar
    14 May 2007

    I have written a small tutorial showing how to build a basic system using restfulauthentication and openid_authentication. The tutorial is written in spanish, but the code should be pretty understandable. Maybe can be useful for you. The url is http://blog.leugim.com.mx/index.php/2007/04/27/usando-ruby-on-rails-parte-1/

  • Avatar
    14 May 2007

    A full working sample application with restfulauthentication + openid_authenication is available at http://www.bencurtis.com/archives/2007/05/openid-sample-application/

  • Avatar
    Keeran
    13 July 2007

    Which revision of the plugin is suitable for Rails 1.2.3? Trunk has failing tests which are apparently due to an update for edge.

  • durant
    19 July 2007

    Suggestion: Newbies, remember to run "rake db:migrate" (or if that's supposed to be automatic, it didn't happen for me)

    Fix: (I'm a newbie, myself, but maybe this fix will earn me some help with my problem below)

    in app/views/users/new.rhtml the label tags: label for="login" label for="email" should be: label for="user_login" label for="user_email" etc. so that when you click on the name, the corresponding textfield is selected. At least, this is how input id's area being named for me when I view the page source.

    Problem: When I go to "http://localhost:3000/users/new" and fill out the form, I get directed to a page:

    Unknown action

    No action responded to index

    I've tried modifying config/routes.rb with the suggestions below to no avail. It looks like the submit form is generating an "index" action and the UsersController doesn't know what to do with it. What's supposed to happen? Is email supposed to be sent and I'm somehow missing an emailer program?

    thanks

    note: I'm using Rails version 1.2.3

  • Avatar
    GregL
    26 July 2007

    To strengthen the ramparts against session fixation and hijacking vulnerabilities call reset_session right after the line :

    if LoggedIn? reset_session blah blah.....

    in the method

    'LoginsessionsController.create'

    It doesn't solve the problem, but it is simple and the hacker will need to be much more motivated: most hackers are lazy crims who want something for nothing.

  • durant
    30 July 2007

    Here is an answer to which version works with rails 1.2.3 (from Jacob Atzen http://www.ruby-forum.com/topic/117043#536293)

    I tried this, ran "rake test" and all tests succeeded.

    cd [into/rails-root]

    svn export -r 2563 http://svn.techno-weenie.net/projects/plugins/restful_authentication/ vendor/plugins/restful_authentication

    This version of the plugin should work with Rails 1.2.3.

    ===

    unfortunately, when I try logging in, I still get an error about index not being found.

  • Avatar
    Greg Lorriman
    1 August 2007

    To add to my previous comment. Immediately after calling

    reset_session

    you'll need to either have copied the session data to put in to the new session, or issue this call again :

    self.current_user = User.authenticate(params[:login], params[:password])

  • Avatar
    2 August 2007

    Thanks for this plugins, I make some change in authenticated_system.rb to prevent
    Session Hijacking :

    def current_user=(new_user)
      session[:remote_ip] = request.remote_ip
      session[:user] = (new_user.nil? || new_user.is_a?(Symbol)) ? nil : new_user.id
      @current_user = new_user
    end
    

    and :

    def current_user
      @current_user ||= (session[:user] &amp;&amp; User.find_by_id(session[:user]) &amp;&amp; (session[:remote_ip] == request.remote_ip)) || :false
    end
    
  • Theyaa
    10 August 2007

    Hello Everyone, I am really new to Rails and when trying to run this plugin after installing it it gives me this error:

    ou have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.errors

    Extracted source (around line #1):

    1: <%= errormessagesfor :user %> 2: <% formfor :user, :url => userspath do |f| -%> 3: <p><label for="login">Login</label><br/> 4: <%= f.text_field :login %></p>

    Anyone have an idea on how to fix this

  • Avatar
    18 August 2007

    Here's my take on a 'smart login' (this is a RESTful approach)... I used a partial navlogin.rhtml in my 'shared' folder and call it in my application.rhtml layout: http://pastie.caboo.se/89494

  • Avatar
    Ryan
    28 August 2007

    I tried moving the UsersController to Admin::UsersController, and I can get to the /admin/users/new screen, but I get an undefined constant UsersController on the create action. I've hunted around in the code but can't figure out why create is still looking for UsersController instead of Admin::UsersController. Any ideas?

    Also, has anyone tried using RestfulAuthentication with RoleRequirement?

  • Avatar
    Vadimir
    1 September 2007

    durant, maybe this note will help:

    If you're on rails 1.2.3 you may need to specify the controller name for the session singular resource:

    map.resource :session, :controller => 'sessions'

    Also, add an observer to config/environment.rb if you chose the --include-activation option config.activerecord.observers = :userobserver # or whatever you named your model

  • Avatar
    Vadimir
    1 September 2007

    @durant

    Previous message obsolete, I finally found the reason (I had the same bug).

    you must put the "map.resources" part in the BEGINNING of the routes.rb!

    (The comments say: # The priority is based upon order of creation: first created -> highest priority.)

    I'm feeling dumb :)

  • Avatar
    4 September 2007

    Using this plugin successfully except . . . it doesn't seem to be persisting sessions to the db. It appears that when I log out, it attempts to destroy the session record in the db, but when I log in I see no attempt to create the session in the db.

    No matter what, the sessions table never gets written to.

  • Avatar
    24 September 2007

    I wanted user records in my app to have various statuses. Here's how I modified restfulauthentication with actsasstatemachine to accomplish this. I'll call it stateful_authentication http://www.vaporbase.com/postings/stateful_authentication

  • Avatar
    5 October 2007

    Rails2.0 requires you to replace redirecttourl with redirect_to.

    In the plugin: restfulauthentication/generators/authenticated/templates/authenticatedsystem.rb

    In existing apps: RAILSROOT/lib/authenticatedsystem.rb

  • Avatar
    Scott Meade
    6 October 2007

    Don't know if this is the right place for this type of question or not. Please delete if not.

    I use this plugin for most projects, so thank you for it. I'm been trying to get my hands around when to create a RESTful resource. Restful Authentication is a good example of this decision. Specifically, would anyone like to share their thoughts on why, for example, this plugin has the activate method for Users instead of an Activation resource (where to activate a user you would post a :create to Activation)? I'm not proposing this plug-in be any different - it works just fine. Just thought it might be a good and very well known example to use on discussion of when to use the constrained set of actions and when not to. Are there any guidelines or is it mostly a judgment call from experience?

  • Avatar
    kadoudal
    7 October 2007

    FAILURE IN TESTS 1) Failure: testshouldfailexpiredcookielogin(SessionsControllerTest) [./test/functional/sessionscontroller_test.rb:67]: <false> is not true.

    15 tests, 31 assertions, 1 failures, 0 errors

    def testshouldfailexpiredcookie_login users(:quentin).remember_me users(:quentin).updateattribute :remembertokenexpiresat, 5.minutes.ago @request.cookies["authtoken"] = cookiefor(:quentin) get :new assert !@controller.send(:logged_in?) end

  • Avatar
    da991319
    29 October 2007

    Thank you for all the comments. I have a little problem (may be because i am new to RoR). Everything is OK with the logging and athentication, etc...

    but what i want is to put an observer onto a table and write the login of the current user, which made the change, into an audit table. i try to put "include authenticatedSystem" into my observer but i got en error.

    Anyone as already got that kind of problem before? thank you

  • Avatar
    raj
    15 November 2007

    This plugin looks good. I am not able to activate the account after the installation. I tried to debug the code using netbeans and It is not able to retrieve the instance of the User.

    self.currentuser = params[:activationcode].blank? ? :false : User.findbyactivationcode(params[:activationcode])

    self.current_user sounds to be nil (Note:- this is a single line in my code.) Please let me know any ideas.

  • Avatar
    Dustin Anderson
    18 November 2007

    Railscasts has an excellent screencast about using restful_authentication. I highly recommend: http://www.railscasts.com/episodes/67

  • Avatar
    Johan van der Kuijl
    28 December 2007

    @raj: add this to your routes.rb

    map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'

  • Avatar
    nathan
    28 December 2007

    hi can anyone tell me where to find some documentation for this that i might understand. i have checked Ryans screencast although they usually make complete sense to me this one passes me by completely. I need to see an example of it in action. all i have is a company model and a product model company has many products product belong to company. i would like company has many users user belongs to company. then a logged in user can edit company and products.. any similar permutation would suffice as an example, i just need to see the code in action. spent numerous hours now trying to find examples but not found anything.

  • Avatar
    Gabriele Tassoni
    30 December 2007

    I'm having problems with rails 1.2.4, whenever I try http://localhost:3000 it throws me an error: undefined method `authenticate_with_http_basic' for #<HomesController:0x2aaaac764f18>, reading around I managed to understand that the mentioned method is a prerogative of rails 2.0, but I cannot upgrade to that version since it's different from the one on the provider's site, however in the README from the plugin is clearly stated that works with rails 1.2 and edge... I'm a bit confused, Have I downloaded the wrong version? is there a version for 1.2?

    Thanks

  • Avatar
    nathan sharkey
    4 January 2008

    hi,

    in response to my own post below, I found a more detailed screencast which i found useful in getting me started.

    http://www.rubyplus.org/episodes/20-Extended-RESTful-Authentication-Rails-2-App.html

    so now i' up and running with it my next question is where is best to post questions about the code itself. I would like to modify it so that a child model is created at the same time as user during signup but i don;t fully understand the create method in users controller.

    cheers Nathan

  • tl
    6 January 2008

    hi, i don't know if its a bug, but i have to change the "redirect_to new_session" to "redirect_to new_session_path" in authenticated_system.rb, because i get an error "undefined local variable or method `new_session'". now all works fine.

  • tl
    6 January 2008

    hi, i don't know if its a bug, but i have to change the "redirect_to new_session" to "redirect_to new_session_path" in authenticated_system.rb, because i get an error "undefined local variable or method `new_session'". now all works fine.

  • Josh
    22 January 2008

    @Gabrielle

    I'm using Rails 1.2.6 but here's what worked for me. In the lib>authenticatedsystem.rb there's an action called loginfrombasicauth that contains the 'authenticatewithhttp_basic' Rails 2.0 method. I changed this to:

    # Rails 1.2.6 version
    def login_from_basic_auth 
        username, passwd = get_auth_data 
        self.current_user = User.authenticate(username, passwd) if username &amp;&amp; passwd 
    end
    

    and had to add the getauthdata method at the end of authenticated_system:

    private

    # Called from #login_from_basic_auth used with Rails 1.2.6 version
    @@http_auth_headers = %w(X-HTTP_AUTHORIZATION HTTP_AUTHORIZATION Authorization)
    # gets BASIC auth info
    def get_auth_data
      auth_key  = @@http_auth_headers.detect { |h| request.env.has_key?(h) }
      auth_data = request.env[auth_key].to_s.split unless auth_key.blank?
      return auth_data &amp;&amp; auth_data[0] == &#x27;Basic&#x27; ? Base64.decode64(auth_data[1]).split(&#x27;:&#x27;)[0..1] : [nil, nil] 
    end
    
  • Avatar
    Emil Tin
    24 January 2008

    Hi, I'm having a problem with the otherwise great restful authentication plugin.

    The 'signup, please activate' email that's send out contain an empty activation code. Also the 'activation succeeded' email is send out at the same time (somewhere in UsersController#create), even though the state of the user is still pending.

    It seems that User#makeactivationcode is called after UserMailer has send out the signup notification email.

  • Avatar
    Emil Tin
    24 January 2008

    I should note that I'm using rails 2.0.1.

  • Avatar
    emil tin
    28 January 2008

    i found the problem. a solution is to send out emails directly from the state change methods, and discard the observer all together. for more, see my post at http://harrylove.org/2007/12/17/activation-emails-with-restful-authentication-and-actsasstate_machine#comment-208

  • Avatar
    30 January 2008

    I am confused by logout route, why it is a HTTP GET? Shouldn't it be an HTTP DELETE

  • Avatar
    nimp
    1 February 2008

    Hi,

    I still have the problem with the empty activation code in the email. Have some one a good solution ? Is any update of restful auth coming soon ?

    Thanks in advance.

  • Avatar
    nimp
    2 February 2008

    The problem is that at the creation of a new user, we never using

    state :pending, :enter => :makeactivationcode

    So activation_code stay always at nil.

    Any idea ?

  • Avatar
    nimp
    2 February 2008

    The solution I found is to simply add this to user.rb

    beforecreate :makeactivation_code

    It work great.

  • Avatar
    bruz
    6 February 2008

    I've been using restful_authentication for several months, and noticed
    there have been some security fixes so I figured it was time to
    upgrade. I ran into an error, and thought it might have been specific
    to the app I'm working on, but I tried creating an app from scratch
    and setting up restful_authentication and get the same error. Here's
    what I tired:

    <code>rails test_app
    cd test_app
    script/plugin install restful_authentication
    script/plugin install http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk
    script/generate authenticated user sessions --include-activation --
    stateful
    # configure database.yml
    rake db:migrate
    script/server
    </code>

    Then when I go to http://localhost/users/new and try to sign up a new
    user, I get the following:

    NameError (undefined local variable or method `record' for
    #<UsersController:0xb7be35ec>):
    /app/controllers/users_controller.rb:21:in `create'

    Has anyone else seen this? I'm running rails 2.0.2, and using the
    latest versions of the plugins as of today (2/6/2008). If I leave out
    the --stateful option, everything works, but of course I'm not using
    all of the acts_as_state_machine improvements to
    restful_authentication.

  • 11 February 2008

    @bruz -

    Just change the 'record' expression on the referenced line to '@user.valid?'. I'm working through getting the stateful setup working with the behavior I want too -- you'll probably find that more changes are needed, but that'll get you going.

  • Avatar
    27 February 2008

    rails 2.0.2, latest version of plugin.

    routes.rb map.resource :session

    no change to any files.

    am getting this error when trying to view login form.

    No route matches "/session/new" with {:method=>:get}

  • Avatar
    euro
    12 February 2008

    hi, I have restful auth and act as state machine working as per Bparanj screencast BUT

    1. Validation is not now working - wonder is it because register is used rather than the core save method in create new user.

    2. Session or sessions?. I have to use both session (singular) and sessions (plural) controlllers. Rails 2 seems to require session (singular) for new and destroy actions BUT sessions (plural) for create action - real mystery for me - I have both controllers in the app at present - must try to solve this.

    Just for info! Rgs Ray

  • Avatar
    chris
    16 February 2008

    @euro: I had the same problem as you outline in (2) - session or sessions? I solved it by having a sessions controller and this in my routes file:

    map.resources :sessions map.resource :session, :controller => 'sessions'

  • Avatar
    chris
    23 February 2008

    My last post lost a line-break. Try this:

    map.resources :sessions

    map.resource :session, :controller => 'sessions'

  • Ralph
    18 March 2008

    Where is the tarball or the pure http access (git anyone)?

    I'm behind a http proxy and svn does not work over it...

  • Avatar
    Ralph
    18 March 2008

    Got a tarball of the trunk.

    It just does not work. This plugin might be useful to generate some files (the tests for example) and quickly see how to do some authentication in rails, but it is not working out of the box.

    First error during the generation of the skeleton (in fixtures), second with this Session(s)Controller oddness, then I see in the code that some presumably important line could be "uncommented at your own risk" for some obscure reason (no link in the comment)... is this a "plug in"?

    Really poor quality software.

  • Gordon McCreight
    21 March 2008

    I was experiencing the same issue as Emil Tin, which he describes this way:

    "Also the 'activation succeeded' email is send out at the same time (somewhere in UsersController#create), even though the state of the user is still pending."

    It's actually sent out by the UserObserver class. The UserObserver.aftersave method sends the "deliveractivation" email if the user is "pending". Since the default state of the user is "pending", it will send the second email right away. The UserObserver.after_save method should check if the user is "active" instead.

  • Avatar
    Doug
    21 March 2008

    Anyone else getting:

    ArgumentError in UsersController#create

    A copy of UserObserver has been removed from the module tree but is still active!

    c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:237:in load_missing_constant&#x27; c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:469:inconst_missing' app/models/user_observer.rb:3:in after_create&#x27; app/controllers/users_controller.rb:21:increate'

  • Avatar
    Doug
    29 March 2008

    The UserObserver seems incorrect for activation. I believe instead of aftersave, beforesave should be used, and the existing record and new record must be checked to see if it's being activate at that time in order to trigger the mailer.

    def before_save(user) if user && user.id old_user = User.find(user.id) if olduser && !olduser.active? && user.active? UserMailer.deliver_activation(user) end end end

  • ai
    30 March 2008

    Documentation for this plugin states that it will work for rails 1.2.6 and above. However, it only works for rails 2.0 and above. Directions below provide work around solutions. Also, this plugin uses observers which can be a pain because it sends out the wrong email notification at the wrong time when used with actasstateful_machine. Follow instructions to modify the plugin to get rid of observers. Hope this helps!

    Directions

    1) Install Plugin (enter following command in terminal) ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication/

    2) Then enter this command: ./script/generate authenticated user sessions \ --include-activation \ --stateful

    3) Create the user table by running this command: rake db:migrate

    4) The above will create the following: Controller sessions_controller users_controller

    Model user_mailer user_observer user

    Views for Session and User_mailer and Users

    It also creates authenticated_system.rb in the lib folder (this is the one the doesn't work in rails 1.x)

    5) In a brand new folder outside of your apps folder, e.g. temp, install a older version of this plugin.

    svn export -r 2563 http://svn.techno-weenie.net/projects/plugins/restful_authentication

    Copy the lib/authenticated_system.rb file from this temp folder into our apps/lib. It will overwrite the version you downloaded previously.

    6) How to get rid of Observers Follow instructions from here written by Emil Tin Comment #6 :

    http://harrylove.org/2007/12/17/activation-emails-with-restful-authentication-and-actsasstate_machine

  • Avatar
    Randall
    2 April 2008

    this plugin installation errors out after copying the several files into the plugin folder. Error msg states: "plugin not found...". Anyone else getting this?

  • Avatar
    Randall
    2 April 2008

    this plugin installation errors out after copying the several files into the plugin folder. Error msg states: "plugin not found...". Anyone else getting this?

  • Avatar
    Randall
    2 April 2008

    this plugin installation errors out after copying the several files into the plugin folder. Error msg states: "plugin not found...". Anyone else getting this?

  • Avatar
    Tiago
    3 April 2008

    Hello, im having some problem here to get it to work. Ive just created a new rails project to test it. When i try: ./script/generate authenticated account sessions i get this error message: Couldn't find 'account' generator

    what did i do wrong?

  • Avatar
    Thomas
    3 April 2008

    Hi,

    maybe a really stupid question, but is there somewhere a documentation for the plugin "restful_authentication". I searched the web but could not find more than some small tutorials or the well known README from the plugin itself.

    Thanks!

  • tom
    4 April 2008

    Hm, with the latest security patch for restful_authentication installed, this spec fails for me:

    it 'does not activate user without key' do get :activate flash[:notice].should be_nil end

    My route for :activate looks like this: map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' so the spec won't hit it. I get

    $ rake ActionController::RoutingError in 'UsersController does not activate user without key' No route matches {:action=>"activate", :controller=>"users"} ./spec/controllers/userscontrollerspec.rb:68:

    Probably what I want in production, but I'd feel better if ALL tests would succeed. I changed the test to this:

    it 'does not activate user without key' do get :activate, :activation_code => "" flash[:notice].should be_nil end

    and am a happy customer. Well, kinda. Took way too long to make this plugin work. Anyway, glad you did the hard part, Rick.

  • tom
    4 April 2008

    Eventually, I also had to skip the verifyauthenticitytoken in both controllers to avoid ActionController::InvalidAuthenticityToken exceptions flying low:

    class SessionsController < ApplicationController skipbeforefilter :verifyauthenticitytoken

    class UsersController < ApplicationController skipbeforefilter :verifyauthenticitytoken

  • Avatar
    Todd Conley
    8 April 2008

    If you're visiting this plugin for the first time, you might consider writing your own from scratch. At least you'll learn something, and it might even save you some time.

  • Avatar
    Sergio
    14 April 2008

    An exception occurs if I delete cookies (clean personal info in firefox) just before submit in the login: ActionController::InvalidAuthenticityToken in SessionsController#create

    Any idea? Thanks.

  • Avatar
    Mark Robinson
    17 April 2008

    I'm having a problem with this. I've developed an application with restful_authentication and it's running fine locally under mongrel but when I deploy it to my host running fast-cgi the routes act differently.

    so the line <% formfor sessionpath do -%> should direct to the create action in the sessions controller (as it does locally) but instead it calls the show action.

    In my routes.rb I have: map.resource :session, :controller => 'sessions'

    which should create the default routes to actions create and show (plus others) the difference being show is GET and create is POST. I've tried specifying the form_for as POST with :method => "POST" but it still directs to show (via GET) in fast-cgi. Any ideas how to debug this?

  • Tim
    14 May 2008

    This link works much better http://svn.techno-weenie.net/projects/plugins/restful -authentication/

  • Avatar
    Wayne
    26 May 2008

    Normally I love restful_authentication, and would recommend it, but the newest version on github is terrible for some reason. Things are changed around, it still is using the old Rails 1.2.x way of doing migrations instead of "sexy migrations", and overall it's not as flexible as I remember it being.

  • Avatar
    1 June 2008

    Hey Tim, just a quick update on the link that you mentioned as working better.

    The url is: http://svn.techno-weenie.net/projects/plugins/restful_authentication/

    Thanks

  • carlivar
    4 June 2008

    There seem to be problems with Rails 2.1.0, but only when I enable the observer as per the docs. When this is in environment.rb:

    config.activerecord.observers = :userobserver

    I get this when starting Rails (or 'rake spec' in this case):

    rake aborted! "Plugins::Restful-authentication::Lib" is not a valid constant name!

    Hunting it down, but could use some help.

  • carlivar
    4 June 2008

    I was able to workaround the previous problem I posted by monkey-patching Rails. I think the problem should exist in most versions of Rails, not just 2.1.0. Rails does not want hyphens in certain names, which this violates.

    Posted workaround in the github wiki for the project:

    http://github.com/technoweenie/restful-authentication/wikis/home

  • GG Crew
    5 June 2008

    Is there a way to access #current_user from inside another model?

    I am attempting to assign a 'created_by_user_id' field as part of a model callback function.

    def before_create
    self.created_by_user_id = current_user
    end

    The code consistently throws the error "undefined local variable or method `current_user'"

    All the functions in the AuthenticatedSystem module are protected, although two of them (#current_user and #logged_in?) are extended into the ActionView module. I've fiddled with the AuthenticatedSystem module, attempting to make various things public (which causes session errors in migrations) and tried including AuthenticatedSystem in other modules. Nothing I've tried has worked.

    All other aspects of Restful_Authentication are working correctly. Using Rails v2.0.2 and a recent version of RA.

  • giorgi
    9 June 2008

    To access #current_user from inside another model, one might want to consider Userstamp plugin ( http://agilewebdevelopment.com/plugins/userstamp )and ( http://github.com/delynn/userstamp/tree ). HTH :)

  • GG Crew
    9 June 2008

    Thanks for the response.

    I've come to a solution that's similar to the Userstamp plugin. In fact, both the Userstamp plugin and my implementation pulled inspiration from the same RoR wiki article: http://wiki.rubyonrails.org/rails/pages/ExtendingActiveRecordExample

    I've been journaling my progress at RailsForum, if anyone is curious: http://railsforum.com/viewtopic.php?pid=64505

  • Avatar
    Todd
    20 June 2008

    Please add "edu" as a top level domain. My university was one of the first six domain names, but it doesn't pass the filter =( -- BTW, I love the plugin!

    REDOMAINTLD = '(?:[A-Z]{2}|com|org|edu|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)'

  • Gah
    20 June 2008

    I'm with Wayne. Some good ideas were introduced into this plugin, but the quality is waaay down. There is cruft everywhere, and I had to patch quite a few things to get it working. Someone needs to audit this, or at least put a disclaimer on it ;)

  • Avatar
    20 June 2008

    activation only works if user object is gonna be reloaded before sending the email. I think, the activation_code is salted before saving. (@user.register!)

    protected def setup_email(user) user.reload @recipients = "#{user.email}" @from = "Marketplace" @subject = "Activation User Account " @sent_on = Time.now @body[:user] = user end

  • Avatar
    18 July 2008

    I'm having some problems when i use this plugin in rails 1.2.x. I have to remove http basic auth from code to get it working...

    dk

  • Avatar
    geolev
    10 August 2008

    I can't install this plugin. I'm running Ruby 1.8.4 and Rails 2.0.2.

    When I install with : $ script/plugin install git://github.com/technoweenie/restful-authentication.git

    Results in : Plugin not found: ["git://github.com/technoweenie/restful-authentication.git"]

    Any idea what I'm doing wrong?

  • Ben
    11 August 2008

    I would like to use this plugin to work in the context of users belonging to accounts. That means I will take off the uniqueness validation for logins and manually check if the login is unique for all users that belong to a certain account. Will that somehow interfere with salt or any other aspect of this plugin?

    BR

  • Ben
    11 August 2008

    I would like to use this plugin to work in the context of users belonging to accounts. That means I will take off the uniqueness validation for logins and manually check if the login is unique for all users that belong to a certain account. Will that somehow interfere with salt or any other aspect of this plugin?

    BR

  • Eric
    29 August 2008

    I was wondering why validation isn't working. It errors out of the app instead of highlighting the offending fields and passing an error. Is it something I did wrong or is it broken?

  • Chris
    2 October 2008

    We had issues with users on Windows copying and pasting in their login names, thus trying to log in as "Bob " instead of "Bob" (Windows adds a trailing space to a double-clicked selection) and failing. I'd suggest changing this line in the User model:

    u = findbylogin(login)

    to:

    u = User.find(:first, :conditions => ["login = ?", login.strip])

    Additionally, if you are using PostgreSQL you'll get caught by its strict case-sensitivity. Trying to log in as "bob" if your user name is "Bob" will fail. In PostgreSQL you'll then need to create a unique index on lower(login) and then use this in the User model instead of what I gave above:

    u = User.find(:first, :conditions => ["lower(login) = ?", login.strip.downcase])

    The latest version of this plugin seems to store the login name as lower case, even if it is entered as uppercase. I believe this isn't what should be happening (changing user data behind their backs). Better to store the login name as it is entered.

  • Avatar
    13 October 2008

    @ carlivar:

    RE: "Plugins::Restful-authentication::Lib" is not a valid constant name!

    If you "mv mv restful-authentication/ restful_authentication/" your problems are solved, albeit this doesn't seem to be the "right" solution...

    If you would like to do this beforehand simply perform the following from within the vendor/plugins directory:

    git clone git://github.com/technoweenie/restful-authentication.git restful_authentication

  • Avatar
    Tom S.
    20 October 2008

    I am trying to generate the authentication components and I get the following: script/generate authenticated user sessions ./script/../config/../vendor/rails/actionpack/lib/action_controller/routing.rb:936:in build&#x27;: undefined method[]' for :session:Symbol (NoMethodError) from ./script/../config/../vendor/rails/actionpack/lib/action_controller/routing.rb:1161:in add_route&#x27; from ./script/../config/../vendor/rails/actionpack/lib/action_controller/routing.rb:1167:inaddnamedroute' from ./script/../config/../vendor/rails/actionpack/lib/action_controller/routing.rb:992:in method_missing&#x27; from ./script/../config/../config/routes.rb:4 from ./script/../config/../vendor/rails/actionpack/lib/action_controller/routing.rb:1128:indraw' from ./script/../config/../config/routes.rb:1 from ./script/../config/../vendor/rails/activerecord/lib/../../activesupport/lib/active_support/dependencies.rb:489:in load&#x27; from ./script/../config/../vendor/rails/activerecord/lib/../../activesupport/lib/active_support/dependencies.rb:489:inload' ... 9 levels... from ./script/../config/../vendor/rails/railties/lib/commands/generate.rb:1:in require&#x27; from ./script/../config/../vendor/rails/railties/lib/commands/generate.rb:1 from script/generate:5:inrequire'

    from script/generate:5

    Any ideas?

  • Avatar
    11 December 2008

    There's a bug in the version I'm using when on signup when using actsasstate_machine and the user mailer. The activation code gets generated twice, and the code that gets sent in the activation email is not the code that gets persisted.

    To fix this problem I simply added this line to the top of the #makeactivationcode method in User

    def makeactivationcode return if activation_code
    ... end

    That fixes the problem

  • Avatar
    Al T.
    9 February 2009

    git://github.com/technoweenie/restful-authentication.git

    doesn't work. Instead use the older and trouble-free svn repo: http://svn.techno-weenie.net/projects/plugins/restful_authentication/

  • Avatar
    Trejkaz
    18 February 2009

    Might want to add "int" to the list of valid top-level domains.

  • Avatar
    deen
    24 April 2009

    Hi, really cool plugins.

    But does anyone knows how to customize error messages? for example 'Login has already been taken' etc? I can't set it in the controller.

    Thanx :)

  • Avatar
    24 May 2009

    I ran across an error: No such file or directory - ..../test/fixtures/users.yml

    I created the test/fixtures directory, then re-ran the command: script/generate authenticated user sessions

    and all was smooth..

    Thanks!

  • Avatar
    Vicky
    26 May 2009

    I think I must be having a huge blackout or something - trying to use this plugin & getting:
    active_record/attribute_methods.rb:251:in `method_missing'
    app/models/user.rb:97:in `make_activation_code'
    app/controllers/users_controller.rb:18:in `create'
    Any ideas?
    I am new to RoR but enjoying so far!

  • Avatar
    Vicky
    26 May 2009

    I am new to RoR and am having trouble trying to get this plugin to work. I am getting a no method error message: undefined method activation_code=&#x27; for #&lt;User:0x46761d8&gt; active_record/attribute_methods.rb:251:inmethod_missing' app/models/user.rb:97:in make_activation_code&#x27; app/controllers/users_controller.rb:18:increate' This may be something fundamental I am missing but would appreciate some help?? Thanks

  • Avatar
    AntonioX
    28 May 2009

    For those having the problem: "plugin not found".

    Use http://github.com/technoweenie/restful-authentication.git Instead of: git://github.com/technoweenie/restful-authentication.git

    The complete line would be: script/plugin install http://github.com/technoweenie/restful-authentication.git

    I am not sure, but as I found in other sites, the problem relates to a SSL certificate. I couldn't find a real solution, but this worked for me.

  • Avatar
    29 May 2009
    script/plugin install http://github.com/technoweenie/restful-authentication.git/
    

    The slash was necessary for me.

Add a comment