Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Fetching contributors…
Cannot retrieve contributors at this time
298 lines (176 sloc) 12.8 KB


Devise is a flexible authentication solution for Rails based on Warden. It:

  • Is Rack based;

  • Is a complete MVC solution based on Rails engines;

  • Allows you to have multiple roles (or models/scopes) signed in at the same time;

  • Is based on a modularity concept: use just what you really need.

Right now it's composed of 11 modules:

  • Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of an user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.

  • Token Authenticatable: signs in an user based on an authentication token (also known as “single access token”). The token can be given both through query string or HTTP Basic Authentication.

  • Confirmable: sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.

  • Recoverable: resets the user password and sends reset instructions.

  • Registerable: handles signing up users through a registration process.

  • Rememberable: manages generating and clearing a token for remembering the user from a saved cookie.

  • Trackable: tracks sign in count, timestamps and IP address.

  • Timeoutable: expires sessions that have no activity in a specified period of time.

  • Validatable: provides validations of email and password. It's optional and can be customized, so you're able to define your own validations.

  • Lockable: locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.



Devise is based on Warden (, a Rack Authentication Framework. You need to install Warden as a gem. Please ensure you have it installed in order to use Devise (see installation below).


Devise master branch now supports Rails 3 and is NOT backward compatible. You can use the latest Rails 3 beta gem with Devise latest gem:

sudo gem install devise --version=1.1.rc1

After you install Devise and add it to your Gemfile, you need to run the generator:

rails generate devise_install

And you're ready to go. The generator will install an initializer which describes ALL Devise's configuration options, so be sure to take a look at it and at the documentation as well:

The documentation above is for Rails 3. If you want to consult the documentation for Rails 2.3, you need to start `gem server` in your own machine. Finally, another good resource for information, is the wiki:

Rails 2.3

If you want to use the Rails 2.3.x version, you should do:

sudo gem install devise --version=1.0.6

Or checkout from the v1.0 branch:

Basic Usage

This is a walkthrough with all steps you need to setup a devise resource, including model, migration, route files, and optional configuration. You MUST also check out the Generators section below to help you start.

Devise must be set up within the model (or models) you want to use. Devise routes must be created inside your config/routes.rb file.

We're assuming here you want a User model with some Devise modules, as outlined below:

class User < ActiveRecord::Base
  devise :database_authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable

After you choose which modules to use, you need to set up your migrations. Luckily, Devise has some helpers to save you from this boring work:

create_table :users do |t|

Devise doesn't use attr_accessible or attr_protected inside its modules, so be sure to define attributes as accessible or protected in your model.

Configure your routes after setting up your model. Open your config/routes.rb file and add:

devise_for :users

This will use your User model to create a set of needed routes (you can see them by running `rake routes`).

Options for configuring your routes include :class_name (to set the class for that route), :path_prefix, :as and :path_names, where the last two have the same meaning as in common routes. The available :path_names are:

devise_for :users, :as => "usuarios", :path_names => { :sign_in => 'login', :sign_out => 'logout', :sign_up => 'register', :password => 'secret', :confirmation => 'verification', :unlock => 'unblock' }

Be sure to check devise_for documentation for details.

After creating your models and routes, run your migrations, and you are ready to go! But don't stop reading here, we still have a lot to tell you:

Controller filters and helpers

Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_filter:

before_filter :authenticate_user!

To verify if a user is signed in, use the following helper:


For the current signed-in user, this helper is available:


You can access the session for this scope:


After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect. Example: For a :user resource, it will use user_root_path if it exists, otherwise default root_path will be used. This means that you need to set the root inside your routes:

root :to => "home"

You can also overwrite after_sign_in_path_for and after_sign_out_path_for to customize your redirect hooks.

Finally, you need to set up default url options for the mailer in each environment. Here is the configuration for config/environments/development.rb:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Tidying up

Devise allows you to set up as many roles as you want. For example, you may have a User model and also want an Admin model with just authentication, trackable, lockable and timeoutable features and no confirmation or password-recovery features. Just follow these steps:

# Create a migration with the required fields
create_table :admins do |t|

# Inside your Admin model
devise :database_authenticatable, :trackable, :timeoutable, :lockable

# Inside your routes
devise_for :admin

# Inside your protected controller
before_filter :authenticate_admin!

# Inside your controllers and views


Devise has generators to help you get started:

rails generate devise_install

This will generate an initializer, with a description of all configuration values.

You can also generate models:

rails generate devise Model

This will create a model named “Model” configured with default Devise modules and attr_accessible set for default fields. The generator will also create the migration and configure your routes for Devise.

Model configuration

The devise method in your models also accepts some options to configure its modules. For example, you can choose which encryptor to use in database_authenticatable:

devise :database_authenticatable, :confirmable, :recoverable, :encryptor => :bcrypt

Besides :encryptor, you can define :pepper, :stretches, :confirm_within, :remember_for, :timeout_in, :unlock_in and other values. For details, see the initializer file that was created when you invoked the devise_install generator described above.

Configuring views

We built Devise to help you quickly develop an application that uses authentication. However, we don't want to be in your way when you need to customize it.

Since Devise is an engine, all its views are packaged inside the gem. These views will help you get started, but after sometime you may want to change them. If this is the case, you just need to invoke the following generator, and it will copy all views to your application:

rails generate devise_views

However, if you have more than one role in your application (such as “User” and “Admin”), you will notice that Devise uses the same views for all roles. Fortunately, Devise offers an easy way to customize views. All you need to do is set “config.scoped_views = true” inside “config/initializers/devise.rb”.

After doing so, you will be able to have views based on the role like “users/sessions/new” and “admins/sessions/new”. If no view is found within the scope, Devise will use the default view at “devise/sessions/new”.

Configuring controllers

If the customization at the views level is not enough, you can customize each controller by following these steps:

1) Create your custom controller, for example a Admins::SessionsController:

class Admins::SessionsController < Devise::SessionsController

2) Tell the router to use this controller:

devise_for :admins, :controllers => { :sessions => "admin/sessions" }

3) And since we changed the controller, it won't use the “devise/sessions” views, so remember to copy “devise/sessions” to “admin/sessions”.

Remember that Devise uses flash messages to let users know if sign in was successful or failed. Devise expects your application to call “flash[:notice]” and “flash[:alert]” as appropriate.


Devise uses flash messages with I18n with the flash keys :success and :failure. To customize your app, you can set up your locale file:

      signed_in: 'Signed in successfully.'

You can also create distinct messages based on the resource you've configured using the singular name given in routes:

        signed_in: 'Welcome user, you are signed in.'
        signed_in: 'Hello admin!'

The Devise mailer uses the same pattern to create subject messages:

      confirmation_instructions: 'Hello everybody!'
        confirmation_instructions: 'Hello User! Please confirm your email'
        reset_password_instructions: 'Reset instructions'

Take a look at our locale file to check all available messages.

Test helpers

Devise includes some tests helpers for functional specs. To use them, you just need to include Devise::TestHelpers in your test class and use the sign_in and sign_out method. Such methods have the same signature as in controllers:

sign_in :user, @user   # sign_in(scope, resource)
sign_in @user          # sign_in(resource)

sign_out :user         # sign_out(scope)
sign_out @user         # sign_out(resource)

You can include the Devise Test Helpers in all of your tests by adding the following to the bottom of your test/test_helper.rb or spec/spec_helper.rb file:

class ActionController::TestCase
  include Devise::TestHelpers

Do not use such helpers for integration tests such as Cucumber or Webrat. Instead, fill in the form or explicitly set the user in session. For more tips, check the wiki (

Migrating from other solutions

Devise implements encryption strategies for Clearance, Authlogic and Restful-Authentication. To make use of these strategies, set the desired encryptor in the encryptor initializer config option. You might also need to rename your encrypted password and salt columns to match Devise's fields (encrypted_password and password_salt).

Other ORMs

Devise supports ActiveRecord (by default) and Mongoid. We offer experimental Datamapper support (with the limitation that the Devise test suite does not run completely with Datamapper). To choose other ORM, you just need to configure it in the initializer file.


Please refer to TODO file.



We have a long list of valued contributors. See the CHANGELOG or do `git shortlog -s -n` in the cloned repository.

Devise extensions

Bugs and Feedback

If you discover any bugs, please create an issue on GitHub.

For support, send an e-mail to the mailing list.

See the wiki for additional documentation and support.


MIT License. Copyright 2009 Plataforma Tecnologia.

Jump to Line
Something went wrong with that request. Please try again.