Flexible authentication solution for Rails with Warden. Now with added support for changing email content_type yay!


Platform: Rubygems

Language: Ruby

License: MIT


View on registry:


Install: gem install glennr-devise

Devise Logo

By Plataformatec.

Build Status Code Climate Security

This README is also available in a friendly navigable format.

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 models signed in at the same time;
  • Is based on a modularity concept: use only what you really need.

It's composed of 10 modules:

  • Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
  • Omniauthable: adds OmniAuth ( support.
  • 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, also allowing them to edit and destroy their account.
  • 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 not been active 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 guaranteed to be thread-safe on YARV. Thread-safety support on JRuby is in progress.


The Devise wiki

The Devise Wiki has lots of additional information about Devise including many "how-to" articles and answers to the most frequently asked questions. Please browse the Wiki after finishing this README:

Bug reports

If you discover a problem with Devise, we would like to know about it. However, we ask that you please review these guidelines before submitting a bug report:

If you have discovered a security related bug, please do NOT use the GitHub issue tracker. Send an email to

Mailing list

If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker:


You can view the Devise documentation in RDoc format here:

If you need to use Devise with previous versions of Rails, you can always run "gem server" from the command line after you install the gem to access the old documentation.

Example applications

There are a few example applications available on GitHub that demonstrate various features of Devise with different versions of Rails. You can view them here:


Our community has created a number of extensions that add functionality above and beyond what is included with Devise. You can view a list of available extensions and add your own here:


We hope that you will consider contributing to Devise. Please read this short overview for some information about how to get started:

You will usually want to write tests for your changes. To run the test suite, go into Devise's top-level directory and run "bundle install" and "rake". For the tests to pass, you will need to have a MongoDB server (version 2.0 or newer) running on your system.

Starting with Rails?

If you are building your first Rails application, we recommend you do not use Devise. Devise requires a good understanding of the Rails Framework. In such cases, we advise you to start a simple authentication system from scratch. Today we have two resources that should help you get started:

Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :smiley:

Getting started

Devise 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with:

gem 'devise'

Run the bundle command to install it.

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

rails generate devise:install

The generator will install an initializer which describes ALL of Devise's configuration options. It is imperative that you take a look at it. When you are done, you are ready to add Devise to any of your models using the generator:

rails generate devise MODEL

Replace MODEL with the class name used for the application’s users (it’s frequently User but could also be Admin). This will create a model (if one does not exist) and configure it with default Devise modules. The generator also configures your config/routes.rb file to point to the Devise controller.

Next, check the MODEL for any additional configuration options you might want to add, such as confirmable or lockable. If you add an option, be sure to inspect the migration file (created by the generator if your ORM supports them) and uncomment the appropriate section. For example, if you add the confirmable option in the model, you'll need to uncomment the Confirmable section in the migration. Then run rake db:migrate

Next, you need to set up the default URL options for the Devise mailer in each environment. Here is a possible configuration for config/environments/development.rb:

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

You should restart your application after changing Devise's configuration options. Otherwise, you will run into strange errors, for example, users being unable to login and route helpers being undefined.

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_action (assuming your devise model is 'User'):

before_action :authenticate_user!

If your devise model is something other than User, replace "_user" with "_yourmodel". The same logic applies to the instructions below.

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 to. For instance, when using a :user resource, the user_root_path will be used if it exists; otherwise, the default root_path will be used. This means that you need to set the root inside your routes:

root to: "home#index"

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

Notice that if your Devise model is called Member instead of User, for example, then the helpers available are:

before_action :authenticate_member!

Configuring Models

The Devise method in your models also accepts some options to configure its modules. For example, you can choose the cost of the encryption algorithm with:

devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 20

Besides :stretches, you can define :pepper, :encryptor, :confirm_within, :remember_for, :timeout_in, :unlock_in among other options. For more details, see the initializer file that was created when you invoked the "devise:install" generator described above. This file is usually located at /config/initializers/devise.rb.

Strong Parameters

When you customize your own views, you may end up adding new attributes to forms. Rails 4 moved the parameter sanitization from the model to the controller, causing Devise to handle this concern at the controller as well.

There are just three actions in Devise that allows any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and the permitted parameters by default are:

  • sign_in (Devise::SessionsController#create) - Permits only the authentication keys (like email)
  • sign_up (Devise::RegistrationsController#create) - Permits authentication keys plus password and password_confirmation
  • account_update (Devise::RegistrationsController#update) - Permits authentication keys plus password, password_confirmation and current_password

In case you want to permit additional parameters (the lazy way™), you can do so using a simple before filter in your ApplicationController:

class ApplicationController < ActionController::Base
 before_action :configure_permitted_parameters, if: :devise_controller?
 def configure_permitted_parameters
 devise_parameter_sanitizer.for(:sign_up) << :username

The above works for any additional fields where the parameters are simple scalar types. If you have nested attributes (say you're using accepts_nested_attributes_for), then you will need to tell devise about those nestings and types. Devise allows you to completely change Devise defaults or invoke custom behaviour by passing a block:

To permit simple scalar values for username and email, use this

def configure_permitted_parameters
 devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }

If you have some checkboxes that express the roles a user may take on registration, the browser will send those selected checkboxes as an array. An array is not one of Strong Parameters' permitted scalars, so we need to configure Devise in the following way:

def configure_permitted_parameters
 devise_parameter_sanitizer.for(:sign_up) { |u| u.permit({ roles: [] }, :email, :password, :password_confirmation) }

For the list of permitted scalars, and how to declare permitted keys in nested hashes and arrays, see

If you have multiple Devise models, you may want to set up a different parameter sanitizer per model. In this case, we recommend inheriting from Devise::ParameterSanitizer and adding your own logic:

class User::ParameterSanitizer < Devise::ParameterSanitizer
 def sign_in
 default_params.permit(:username, :email)

And then configure your controllers to use it:

class ApplicationController < ActionController::Base
 def devise_parameter_sanitizer
 if resource_class == User, :user, params)
 super # Use the default one

The example above overrides the permitted parameters for the user to be both :username and :email. The non-lazy way to configure parameters would be by defining the before filter above in a custom controller. We detail how to configure and customize controllers in some sections below.

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 some time 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

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

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. You can also use the generator to generate scoped views:

rails generate devise:views users

If you would like to generate only a few sets of views, like the ones for the registerable and confirmable module, you can pass a list of modules to the generator with the -v flag.

rails generate devise:views -v registrations confirmations

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 controllers using the generator which requires a scope:

    rails generate devise:controllers [scope]

    If you specify users as the scope, controllers will be created in app/controllers/users/. And the sessions controller will look like this:

    class Users::SessionsController < Devise::SessionsController
     # GET /resource/sign_in
     # def new
     # super
     # end
  2. Tell the router to use this controller:

    devise_for :users, controllers: { sessions: "users/sessions" }
  3. Copy the views from devise/sessions to users/sessions. Since the controller was changed, it won't use the default views located in devise/sessions.

  4. Finally, change or extend the desired controller actions.

    You can completely override a controller action:

    class Users::SessionsController < Devise::SessionsController
     def create
     # custom sign-in code

    Or you can simply add new behaviour to it:

    class Users::SessionsController < Devise::SessionsController
     def create
     super do |resource|

    This is useful for triggering background jobs or logging events during certain actions.

Remember that Devise uses flash messages to let users know if sign in was successful or unsuccessful. Devise expects your application to call flash[:notice] and flash[:alert] as appropriate. Do not print the entire flash hash, print only specific keys. In some circumstances, Devise adds a :timedout key to the flash hash, which is not meant for display. Remove this key from the hash if you intend to print the entire hash.

Configuring routes

Devise also ships with default routes. If you need to customize them, you should probably be able to do it through the devise_for method. It accepts several options like :class_name, :path_prefix and so on, including the possibility to change path names for I18n:

devise_for :users, path: "auth", path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unblock', registration: 'register', sign_up: 'cmon_let_me_in' }

Be sure to check devise_for documentation for details.

If you have the need for more deep customization, for instance to also allow "/sign_in" besides "/users/sign_in", all you need to do is to create your routes normally and wrap them in a devise_scope block in the router:

devise_scope :user do
 get "sign_in", to: "devise/sessions#new"

This way, you tell Devise to use the scope :user when "/sign_in" is accessed. Notice devise_scope is also aliased as as in your router.


Devise uses flash messages with I18n, in conjunction with the flash keys :notice and :alert. 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 a similar pattern to create subject messages:

 subject: 'Hello everybody!'
 user_subject: 'Hello User! Please confirm your email'
 subject: 'Reset instructions'

Take a look at our locale file to check all available messages. You may also be interested in one of the many translations that are available on our wiki:

Caution: Devise Controllers inherit from ApplicationController. If your app uses multiple locales, you should be sure to set I18n.locale in ApplicationController.

Test helpers

Devise includes some test helpers for functional specs. In order to use them, you need to include Devise in your functional tests by adding the following to the bottom of your test/test_helper.rb file:

class ActionController::TestCase
 include Devise::TestHelpers

If you're using RSpec, you can put the following inside a file named spec/support/devise.rb or in your spec/spec_helper.rb (or spec/rails_helper.rb if you are using rspec-rails):

RSpec.configure do |config|
 config.include Devise::TestHelpers, type: :controller

Now you are ready to use the sign_in and sign_out methods. 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)

There are two things that are important to keep in mind:

  1. These helpers are not going to work for integration tests driven by Capybara or Webrat. They are meant to be used with functional tests only. Instead, fill in the form or explicitly set the user in session;

  2. If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from the router, but since functional tests do not pass through the router, it needs to be stated explicitly. For example, if you are testing the user scope, simply use:

    @request.env["devise.mapping"] = Devise.mappings[:user]
    get :new


Devise comes with OmniAuth support out of the box to authenticate with other providers. To use it, simply specify your OmniAuth configuration in config/initializers/devise.rb:

config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'

You can read more about OmniAuth support in the wiki:

Configuring multiple models

Devise allows you to set up as many Devise models as you want. If you want to have an Admin model with just authentication and timeout features, in addition to the User model above, just run:

# Create a migration with the required fields
create_table :admins do |t|
 t.string :email
 t.string :encrypted_password
 t.timestamps null: false
# Inside your Admin model
devise :database_authenticatable, :timeoutable
# Inside your routes
devise_for :admins
# Inside your protected controller
before_filter :authenticate_admin!
# Inside your controllers and views

Alternatively, you can simply run the Devise generator.

Keep in mind that those models will have completely different routes. They do not and cannot share the same controller for sign in, sign out and so on. In case you want to have different roles sharing the same actions, we recommend that you use a role-based approach, by either providing a role column or using a dedicated gem for authorization.

ActiveJob Integration

If you are using Rails 4.2 and ActiveJob to deliver ActionMailer messages in the background through a queuing back-end, you can send Devise emails through your existing queue by overriding the send_devise_notification method in your model.

def send_devise_notification(notification, *args)
 devise_mailer.send(notification, self, *args).deliver_later

Password reset tokens and Rails logs

If you enable the Recoverable module, note that a stolen password reset token could give an attacker access to your application. Devise takes effort to generate random, secure tokens, and stores only token digests in the database, never plaintext. However the default logging behavior in Rails can cause plaintext tokens to leak into log files:

  1. Action Mailer logs the entire contents of all outgoing emails to the DEBUG level. Password reset tokens delivered to users in email will be leaked.
  2. Active Job logs all arguments to every enqueued job at the INFO level. If you configure Devise to use deliver_later to send password reset emails, password reset tokens will be leaked.

Rails sets the production logger level to DEBUG by default. Consider changing your production logger level to WARN if you wish to prevent tokens from being leaked into your logs. In config/environments/production.rb:

config.log_level = :warn

Other ORMs

Devise supports ActiveRecord (default) and Mongoid. To select another ORM, simply require it in the initializer file.

Additional information


Using Devise on Heroku with Ruby on Rails 3.2 requires setting:

config.assets.initialize_on_precompile = false

Read more about the potential issues at


Devise is based on Warden, which is a general Rack authentication framework created by Daniel Neighman. We encourage you to read more about Warden here:


We have a long list of valued contributors. Check them all at:


MIT License. Copyright 2009-2015 Plataformatec.

You are not granted rights or licenses to the trademarks of Plataformatec, including without limitation the Devise name or logo.

веселые картинки развлекательные гифки интресные факты смешные видео смешные истории из соцсетей

GitHub Repository

plataformatec/devise plataformatec/devise

Flexible authentication solution for Rails with Warden.

Language: Ruby

Created: September 16, 2009 12:15

Last updated: April 01, 2015 02:16

Last pushed: March 31, 2015 17:11

Size: 11.3 MB

Stars: 12,557

Forks: 2,637

Watchers: 427

Open issues: 16

Top Contributors

José Valim Carlos Antonio da Silva Lucas Mazza Vasiliy Ermolovich Rafael Mendonça França David Henry Drew Ulmer yang2007chun Rodrigo Flores Jo Liss Marcelo Silveira Fred Wu Vinicius Baggio Fuentes Ches Martin Josh Kalderimis Rodrigo Rosenfeld Rosas Denis Lifanov Jacques Crocker Jared Morgan Alex Soble


  • - February 14, 2010 22:00
  • 1.0.1 - February 14, 2010 22:00

Related Projects

brainsome_devise 3.3.0
Flexible authentication solution for Rails with Warden
Rubygems - Ruby - MIT - Published 7 months ago - 12,557 stars
cloudfoundry-devise 1.5.2
Flexible authentication solution for Rails with Warden
Rubygems - Ruby - MIT - Published over 3 years ago - 12,557 stars
dcu-devise 1.0.7
Flexible authentication solution for Rails with Warden
Rubygems - Ruby - MIT - Published almost 5 years ago - 12,557 stars
devise_omniauth_fb 1.0.0
Flexible authentication solution for Rails with Warden
Rubygems - Ruby - MIT - Published over 2 years ago - 12,557 stars
graffititracker_devise 1.0.11
Flexible authentication solution for Rails with Warden
Rubygems - Ruby - MIT - Published about 4 years ago - 12,557 stars
веселые картинки развлекательные гифки интресные факты смешные видео смешные истории из соцсетей