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
- Create a new Rails app.
git flow feature start authentication
- 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.
bundle install
rails g devise:install
- Make the three changes specified by generator:
- Set the action_mailer host in development.rb, test.rb, and production.rb.(The production host should obviously point to your production host.)
- Uncomment and amend the root route in routes.rb.This is also a good time to delete public/index.html.
- Add flash messages to the application layout. I prefer haml so I delete application.html.erb and add the following application.html.haml.
- This is a good time to commit with
git add -A
andgit commit -m "Installed devise."
- Amend devise.rb.
rails g devise user
- 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.
- Amend ####_devise_create_users.rb.The most important points are to add the user column and index and remove unique from the email index.
rake db:migrate
rake db:test:clone
- 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. - Another good point to commit and take a break.
git add -A
andgit 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.