Devise

使用 Warden 为 Rails 提供灵活的认证解决方案。「Flexible authentication solution for Rails with Warden.」

Github stars Tracking Chart

Devise Logo

Build Status
Code Climate

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: hashes 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 (https://github.com/omniauth/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.

Table of Contents

Information

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:

https://github.com/heartcombo/devise/wiki

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:

https://github.com/heartcombo/devise/wiki/Bug-reports

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

StackOverflow and Mailing List

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

http://stackoverflow.com/questions/tagged/devise

The deprecated mailing list can still be read on

https://groups.google.com/group/plataformatec-devise

RDocs

You can view the Devise documentation in RDoc format here:

http://rubydoc.info/github/heartcombo/devise/master/frames

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:

https://github.com/heartcombo/devise/wiki/Example-Applications

Extensions

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:

https://github.com/heartcombo/devise/wiki/Extensions

Contributing

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

https://github.com/heartcombo/devise/wiki/Contributing

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 bin/test.
Devise works with multiple Ruby and Rails versions, and ActiveRecord and Mongoid ORMs, which means you can run the test suite with some modifiers: DEVISE_ORM and BUNDLE_GEMFILE.

DEVISE_ORM

Since Devise support both Mongoid and ActiveRecord, we rely on this variable to run specific code for each ORM.
The default value of DEVISE_ORM is active_record. To run the tests for mongoid, you can pass mongoid:

DEVISE_ORM=mongoid bin/test

==> Devise.orm = :mongoid

When running the tests for Mongoid, you will need to have a MongoDB server (version 2.0 or newer) running on your system.

Please note that the command output will show the variable value being used.

BUNDLE_GEMFILE

We can use this variable to tell bundler what Gemfile it should use (instead of the one in the current directory).
Inside the gemfiles directory, we have one for each version of Rails we support. When you send us a pull request, it may happen that the test suite breaks on Travis using some of them. If that's the case, you can simulate the same environment using the BUNDLE_GEMFILE variable.
For example, if the tests broke using Ruby 2.4.2 and Rails 4.1, you can do the following:

rbenv shell 2.4.2 # or rvm use 2.4.2
BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bundle install
BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bin/test

You can also combine both of them if the tests broke for Mongoid:

BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bundle install
BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable DEVISE_ORM=mongoid bin/test

Running tests

Devise uses Mini Test as test framework.

  • Running all tests:
bin/test
  • Running tests for an specific file:
bin/test test/models/trackable_test.rb
  • Running a specific test given a regex:
bin/test test/models/trackable_test.rb:16

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 three 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 4.0 works with Rails 4.1 onwards. Add the following line to your Gemfile:

gem 'devise'

Then run bundle install

Next, you need to run the generator:

$ rails generate devise:install

At this point, a number of instructions will appear in the console. Among these instructions, you'll 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 }

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.

In the following command you will 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 the default Devise modules. The generator also configures your config/routes.rb file to point to the Devise controller.

$ rails generate devise MODEL

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 rails db:migrate

You should restart your application after changing Devise's configuration options (this includes stopping spring). 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!

For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.

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:

user_signed_in?

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

current_user

You can access the session for this scope:

user_session

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!

member_signed_in?

current_member

member_session

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 hashing algorithm with:

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

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

The Parameter Sanitizer API has changed for Devise 4

For previous Devise versions see https://github.com/heartcombo/devise/tree/3-stable#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 allow any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and default permitted parameters 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 action in your ApplicationController:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
  end
end

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:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, address_attributes: [:country, :state, :city, :area, :postal_code]])
  end
end

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.permit(:sign_in) do

Overview

Name With Ownerheartcombo/devise
Primary LanguageRuby
Program languageRuby (Language Count: 2)
PlatformLinux, Mac, Windows
License:MIT License
Release Count144
Last Release Namev4.9.4 (Posted on 2024-04-10 09:27:24)
First Release Namev0.7.5 (Posted on )
Created At2009-09-16 12:15:12
Pushed At2024-05-27 17:42:38
Last Commit At
Stargazers Count23.8k
Watchers Count462
Fork Count5.5k
Commits Count3.9k
Has Issues Enabled
Issues Count4210
Issue Open Count150
Pull Requests Count775
Pull Requests Open Count68
Pull Requests Close Count608
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private
To the top