Authentication With Devise Using Username - Configuration

Devise is probably the most popular authentication gem for Rails apps but, in the current version (1.1.5), doesn't fully support logging in with a username and password. This Railscast walks through how to add a username to the model and use username as the key to log in with but 1.1.5 will still require email as the key to unlock an account, reset a password or resend confirmation instructions.

Version 1.2rc adds the ability to use username as a key for unlocking and resetting and I have submitted a patch to use username as a key when resending confirmations which will hopefully make it into a 1.2.x release. I have included my fork in the Gemfile below and will re-edit this post as future versions of devise are released.

My patch has now been included in 1.2rc so use the https://github.com/plataformatec/devise.git url in your gemfile.

I'll keep this terse and include my workflow

  1. Create a new Rails app.
  2. git flow feature start authentication
  3. Amend Gemfile:I have included hpricot and ruby_parser gems as they are required by devise for haml views. Note that the devise gem is pointing to my fork. I'll amend this as soon as the patch gets included.
  4. bundle install
  5. rails g devise:install
  6. Make the three changes specified by generator:
    1. Set the action_mailer host in development.rb, test.rb, and production.rb.(The production host should obviously point to your production host.)
    2. Uncomment and amend the root route in routes.rb.This is also a good time to delete public/index.html.
    3. Add flash messages to the application layout. I prefer haml so I delete application.html.erb and add the following application.html.haml.
  7. This is a good time to commit with git add -A and git commit -m "Installed devise."
  8. Amend devise.rb.
  9. rails g devise user
  10. Amend user.rb.Note I can't use the validatable module as that would require emails to be unique so I will have to write my own validation later.
  11. Amend ####_devise_create_users.rb.The most important points are to add the user column and index and remove unique from the email index.
  12. rake db:migrate
  13. rake db:test:clone
  14. Generate the devise views so we can amend them. rails g devise:views -e:haml (skip the -e:haml to generate erb views.) I will drive the view changes with tests later.
  15. Another good point to commit and take a break. git add -A and git commit -m "Configured devise"

 

Changing the views is just a matter of replacing :email with :username but I will do that with some cucumber tests in a future post.

Previous
Previous

Rails, Compass, HTML5 Boilerplate and Heroku

Next
Next

Rails - File, New Project...