Devise: flexible authentication solution for Rails

UPDATE: This post was an introduction to Devise and a couple of things changed since then. There is a more recent post which describes the same steps as below using generators and, for a more complete and always updated explanation, please check the README.

In Rails Summit Latin America 2009, we showed Devise in a lightning talk and today we are officially releasing it! Before we show you some code, we are going to explain what we want to achieve with Devise, starting with the most used authentication solution nowadays: Clearance and Authlogic.

Clearance

Clearance is a full stack authentication solution, implementing all Model, View and Controller layers using Rails Engines. It deals with account confirmation and password recovery. You just need to plug and play! However, you are required to use the model User and it does not allow you have add and/or customize different roles.

Authlogic

When comes to the Model, Authlogic is definitely the most complete solution out there. It handles several cryptography providers and many other goodies which are completely configurable. However, it’s not a full stack solution (it does not say how users should confirm their account or recover their password) and it has a little bit of controversy since it handles the session in a model. So here is the question, where the session could be handled then?

Here comes Warden!

Warden is a general rack authentication framework, developed by Daniel Neighman, which handles the session in a rack middleware. The main benefit from it is that you can share your authentication strategies with several apps, so if you are using Sinatra, Rails and some others middlewares at the same time, they all rely on the same rules!

Devise: strategies for authentication

After we fell in love with Warden and used it in some projects, we decided to create a full stack solution as Clearance, but flexible as Authlogic, on top of Warden. The solution is Devise, a Rails Engine which handles multiple roles, each one of them with different strategies. Devise currently comes with 5 strategies:

  • Authenticatable: responsible for encrypting password and validating authenticity of a user while signing in;
  • Confirmable: responsible for verifying whether an account is already confirmed to sign in, and to send emails with confirmation instructions;
  • Recoverable: takes care of reseting the user password and send reset instructions;
  • Rememberable: generates and clears a token to remember the user from a saved cookie;
  • Validatable: creates all needed validations for email and password. It’s totally optional, so you’re able to to customize validations by yourself.

The nice thing is: imagine that you are building an app which needs to handle invitations. You just need to create a Invitable strategy on Devise and never implement it again!

Show me the code!

In the README, you will find all the information you need to start using Devise in your projects, so here we are going to cover the main aspects of it. Let’s suppose you are creating an user model, which needs to be authenticated and recover his password. The first step is to create the columns using Devise migration helpers:

create_table :users do |t|
  # creates email, encrypted_password and password_salt
  t.authenticatable

  # creates reset_password_token
  t.recoverable
end

Then you need to declare inside your model which strategies you want to use:

class User < ActiveRecord::User
  # Authenticatable is always included
  devise :recoverable, :validatable
end

And create the routes:

ActionController::Routing::Routes.draw do |map|
  # Check for configuration params on README
  map.devise_for :users
end

The route will access your model and create only the routes for the strategies declared. That ensures that your user won't access the confirmations controller inside Devise. Devise also adds a couple of helpers and filters to be used inside your controllers:

  # Inside your protected controller
  before_filter :authenticate_user!

  # Inside your controllers and views
  user_signed_in?
  current_user
  user_session

user_session is a hash scoped only to the user. So if you have two roles, they will have different session hashes and their data won't conflict! This awesome feature come straights from Warden!

Devise also has I18n support and since it's an engine, you can customize your views just by placing a copy of it in your application. A small application build as example is also available on Github!

What's more to come?

We are planning to add several other strategies to Devise, including brute force protection, session timeouts and also other features, as generators. You can spy our TODO list whenever you want.

Our many thanks to

Carlos Antônio which worked on Devise and made it ready for prime time! Jonas Nicklas, which introduced us to Warden and Daniel Neighman for building and maintaining it!

We also want to thank Thoughtbot guys, which wrote several decisions and tips they took while developing Clearance which helped us while building Devise.

Finally, thanks to Fábio Akita for giving us the chance to release it at Rails Summit and Gregg Pollack for releasing Devise on Ruby 5!

  • José Valim

    @Mike, it’s odd that changing the env in one controller will change for all tests. If that is the case, instead of working with a block, I would suggest to remove the warden environment in teardown.

    class ActionController::TestCase
      teardown :cleanup_warden_env
    
      def cleanup_warden_env
        @controller.request.env.delete('warden')
      end
    end

    And about the “:user => nil” I would suggest you to, while you stub, check if a value was given, if so, make the method call raise an error:

    if v
      warden.stubs(:authenticate!).with(:scope => k) do
        raise "Not authenticated user"
      end
    else
      warden.stubs(:authenticate!).with(:scope => k)
    end

    I’m not sure that syntax works for mocha, but something similar must be available. What do you think?

  • Mike Wyatt

    @José: thanks for the help!

    I’ve updated the gist (always at http://gist.github.com/219330). now you can do something like

    setup do
      sign_in_as :user => Factory(:user), :admin => nil
      post :create
    end

    to stub the current_(user|admin) & (user|admin)_signed_in? methods

    setup do
      mock_warden_for :user
      get :new
    end

    will stub the authenticate_user! method (sign_in_as uses the mock_warden_for method so everything works already). there are some shorthands, too

    sign_in # => sign_in_as :user => Factory(:user)
    mock_warden # => mock_warden_for :user

    p.s crossing my fingers for the formatting to work

  • Mike Wyatt

    @José: thanks for the help!

    I’ve updated the gist (always at http://gist.github.com/219330). now you can do something like

    setup do
      sign_in_as :user => Factory(:user), :admin => nil
      post :create
    end

    to stub the current_(user|admin) & (user|admin)_signed_in? methods

    setup do
      mock_warden_for :user
      get :new
    end

    will stub the authenticate_user! method (sign_in_as uses the mock_warden_for method so everything works already). there are some shorthands, too

    sign_in # => sign_in_as :user => Factory(:user)
    mock_warden # => mock_warden_for :user

    p.s crossing my fingers for the formatting to work

  • José Valim

    Awesome @Mike! We are going to move it to Devise and make it available as a test helper! Thanks!

  • José Valim

    Awesome @Mike! We are going to move it to Devise and make it available as a test helper! Thanks!

  • Mike Wyatt

    really glad I could help José!

  • Mike Wyatt

    really glad I could help José!

  • Mike Wyatt

    also, I’m pretty sure the teardown method isn’t needed. and there’s probably some things I missed

  • Mike Wyatt

    also, I’m pretty sure the teardown method isn’t needed. and there’s probably some things I missed

  • Pingback: Devise: authentication for lazy programmers | Plataforma Tecnologia Blog

  • spyros

    hi all,
    a short -not too- irrelevant question.

    Does anybody have/had issue with authenticate_or_request_with_http_basic
    after using warden/devise?

    Obviously, I do (rails 2.3.2), and seek a solution.

    thanks in advance!

  • spyros

    hi all,
    a short -not too- irrelevant question.

    Does anybody have/had issue with authenticate_or_request_with_http_basic
    after using warden/devise?

    Obviously, I do (rails 2.3.2), and seek a solution.

    thanks in advance!

  • Pingback: Understanding Devise roles | Plataforma Tecnologia Blog

  • Pingback: Devise - Autenticação flexível para desenvolvedores Rails pragmáticos

  • Trung

    Will this play nice with Datamapper?

    Authlogic requires a lot of hack in order to work with datamapper.

    Thanks.

  • Trung

    Will this play nice with Datamapper?

    Authlogic requires a lot of hack in order to work with datamapper.

    Thanks.

  • José Valim

    @Trung Lately we already support ActiveRecord and MongoMapper. Take a look at lib/devise/orm/mongo_mapper.rb and you just need a similar file to have it working with Datamapper. The only hack you will need will be in cases where Datamapper does not mimics ActiveRecord API.

  • José Valim

    @Trung Lately we already support ActiveRecord and MongoMapper. Take a look at lib/devise/orm/mongo_mapper.rb and you just need a similar file to have it working with Datamapper. The only hack you will need will be in cases where Datamapper does not mimics ActiveRecord API.

  • Pingback: Mmm…food » Authentication with Devise and Warden, part 1: Up and Running