- Notifications
You must be signed in to change notification settings - Fork5.5k
Flexible authentication solution for Rails with Warden.
License
heartcombo/devise
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
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
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 doNOT use the GitHub issue tracker. Send an email toheartcombo@googlegroups.com.
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
You can view the Devise documentation in RDoc format here:
http://rubydoc.info/github/heartcombo/devise/main/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.
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
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
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 runbundle install
andbin/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
andBUNDLE_GEMFILE
.
Since Devise supports both Mongoid and ActiveRecord, we rely on this variable to run specific code for each ORM.The default value ofDEVISE_ORM
isactive_record
. To run the tests for Mongoid, you can passmongoid
:
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.
We can use this variable to tell bundler what Gemfile it should use (instead of the one in the current directory).Inside thegemfiles 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 using some of them. If that's the case, you can simulate the same environment using theBUNDLE_GEMFILE
variable.For example, if the tests broke using Ruby 3.0.0 and Rails 6.0, you can do the following:
rbenv shell 3.0.0# or rvm use 3.0.0BUNDLE_GEMFILE=gemfiles/Gemfile-rails-6-0 bundle installBUNDLE_GEMFILE=gemfiles/Gemfile-rails-6-0 bin/test
You can also combine both of them if the tests broke for Mongoid:
BUNDLE_GEMFILE=gemfiles/Gemfile-rails-6-0 bundle installBUNDLE_GEMFILE=gemfiles/Gemfile-rails-6-0 DEVISE_ORM=mongoid bin/test
Devise usesMini 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
If you are building your first Rails application, we recommend youdo 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. Here's a few resources that should help you get started:
- Michael Hartl's online book:https://www.railstutorial.org/book/modeling_users
- Ryan Bates' Railscasts:http://railscasts.com/episodes/250-authentication-from-scratch andhttp://railscasts.com/episodes/250-authentication-from-scratch-revised
- Codecademy's Ruby on Rails: Authentication and Authorization:https://www.codecademy.com/learn/rails-auth
Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. 😃
Devise 4.0 works with Rails 6.0 onwards. Run:
bundle add devise
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 forconfig/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 isimperative 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 replaceMODEL
with the class name used for the application’s users (it’s frequentlyUser
but could also beAdmin
). This will create a model (if one does not exist) and configure it with the default Devise modules. The generator also configures yourconfig/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 runrails 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.
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 thatprotect_from_forgery
is no longer prepended to thebefore_action
chain, so if you have setauthenticate_user
beforeprotect_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 useprotect_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, theuser_root_path
will be used if it exists; otherwise, the defaultroot_path
will be used. This means that you need to set the root inside your routes:
rootto:'home#index'
You can also overrideafter_sign_in_path_for
andafter_sign_out_path_for
to customize your redirect hooks.
Notice that if your Devise model is calledMember
instead ofUser
, for example, then the helpers available are:
before_action:authenticate_member!member_signed_in?current_membermember_session
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
.
The Parameter Sanitizer API has changed for Devise 4
For previous Devise versions seehttps://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 (likeemail
)sign_up
(Devise::RegistrationsController#create
) - Permits authentication keys pluspassword
andpassword_confirmation
account_update
(Devise::RegistrationsController#update
) - Permits authentication keys pluspassword
,password_confirmation
andcurrent_password
In case you want to permit additional parameters (the lazy way™), you can do so using a simple before action in yourApplicationController
:
classApplicationController <ActionController::Basebefore_action:configure_permitted_parameters,if::devise_controller?protecteddefconfigure_permitted_parametersdevise_parameter_sanitizer.permit(:sign_up,keys:[:username])endend
The above works for any additional fields where the parameters are simple scalar types. If you have nested attributes (say you're usingaccepts_nested_attributes_for
), then you will need to tell devise about those nestings and types:
classApplicationController <ActionController::Basebefore_action:configure_permitted_parameters,if::devise_controller?protecteddefconfigure_permitted_parametersdevise_parameter_sanitizer.permit(:sign_up,keys:[:first_name,:last_name,address_attributes:[:country,:state,:city,:area,:postal_code]])endend
Devise allows you to completely change Devise defaults or invoke custom behavior by passing a block:
To permit simple scalar values for username and email, use this
defconfigure_permitted_parametersdevise_parameter_sanitizer.permit(:sign_in)do |user_params|user_params.permit(:username,:email)endend
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:
defconfigure_permitted_parametersdevise_parameter_sanitizer.permit(:sign_up)do |user_params|user_params.permit({roles:[]},:email,:password,:password_confirmation)endend
For the list of permitted scalars, and how to declare permitted keys in nested hashes and arrays, see
https://github.com/rails/strong_parameters#nested-parameters
If you have multiple Devise models, you may want to set up a different parameter sanitizer per model. In this case, we recommend inheriting fromDevise::ParameterSanitizer
and adding your own logic:
classUser::ParameterSanitizer <Devise::ParameterSanitizerdefinitialize(*)superpermit(:sign_up,keys:[:username,:email])endend
And then configure your controllers to use it:
classApplicationController <ActionController::Baseprotecteddefdevise_parameter_sanitizerifresource_class ==UserUser::ParameterSanitizer.new(User,:user,params)elsesuper# Use the default oneendendend
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.
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 asUser
andAdmin
), 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 setconfig.scoped_views = true
inside theconfig/initializers/devise.rb
file.
After doing so, you will be able to have views based on the role likeusers/sessions/new
andadmins/sessions/new
. If no view is found within the scope, Devise will use the default view atdevise/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 theregisterable
andconfirmable
module,you can pass a list of views to the generator with the-v
flag.
rails generate devise:views -v registrations confirmations
If the customization at the views level is not enough, you can customize each controller by following these steps:
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 inapp/controllers/users/
.And the sessions controller will look like this:classUsers::SessionsController <Devise::SessionsController# GET /resource/sign_in# def new# super# end ...end
Use the
-c
flag to specify one or more controllers, for example:rails generate devise:controllers users -c sessions
Tell the router to use this controller:
devise_for:users,controllers:{sessions:'users/sessions'}
Recommended but not required: copy (or move) the views from
devise/sessions
tousers/sessions
. Rails will continue using the views fromdevise/sessions
due to inheritance if you skip this step, but having the views matching the controller(s) keeps things consistent.Finally, change or extend the desired controller actions.
You can completely override a controller action:
classUsers::SessionsController <Devise::SessionsControllerdefcreate# custom sign-in codeendend
Or you can simply add new behavior to it:
classUsers::SessionsController <Devise::SessionsControllerdefcreatesuperdo |resource|BackgroundWorker.trigger(resource)endendend
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 callflash[:notice]
andflash[: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.
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 checkdevise_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 create your routes normally and wrap them in adevise_scope
block in the router:
devise_scope:userdoget'sign_in',to:'devise/sessions#new'end
This way, you tell Devise to use the scope:user
when "/sign_in" is accessed. Noticedevise_scope
is also aliased asas
in your router.
Please note: You will still need to adddevise_for
in your routes in order to use helper methods such ascurrent_user
.
devise_for:users,skip::all
Devise integrates with Hotwire/Turbo by treating such requests as navigational, and configuring certain responses for errors and redirects to match the expected behavior. New apps are generated with the following response configuration by default, and existing apps may opt-in by adding the config to their Devise initializers:
Devise.setupdo |config|# ...# When using Devise with Hotwire/Turbo, the http status for error responses# and some redirects must match the following. The default in Devise for existing# apps is `200 OK` and `302 Found` respectively, but new apps are generated with# these new defaults that match Hotwire/Turbo behavior.# Note: These might become the new default in future versions of Devise.config.responder.error_status=:unprocessable_entityconfig.responder.redirect_status=:see_otherend
Important: these custom responses require theresponders
gem version to be3.1.0
or higher, please make sure you update it if you're going to use this configuration. Checkthis upgrade guide for more info.
Note: the above statuses configuration may become the default for Devise in a future release.
There are a couple other changes you might need to make in your app to work with Hotwire/Turbo, if you're migrating from rails-ujs:
- The
data-confirm
option that adds a confirmation modal to buttons/forms before submission needs to change todata-turbo-confirm
, so that Turbo handles those appropriately. - The
data-method
option that sets the request method for link submissions needs to change todata-turbo-method
. This is not necessary forbutton_to
orform
s since Turbo can handle those.
If you're setting up Devise to sign out via:delete
, and you're using links (instead of buttons wrapped in a form) to sign out with themethod: :delete
option, they will need to be updated as described above. (Devise does not provide sign out links/buttons in its shared views.)
Make sure to inspect your views looking for those, and change appropriately.
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:
en:devise:sessions: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:
en:devise:sessions:user:signed_in:'Welcome user, you are signed in.'admin:signed_in:'Hello admin!'
The Devise mailer uses a similar pattern to create subject messages:
en:devise:mailer:confirmation_instructions:subject:'Hello everybody!'user_subject:'Hello User! Please confirm your email'reset_password_instructions: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:
https://github.com/heartcombo/devise/wiki/I18n
Caution: Devise Controllers inherit from ApplicationController. If your app uses multiple locales, you should be sure to set I18n.locale in ApplicationController.
Devise includes some test helpers for controller and integration tests.In order to use them, you need to include the respective module in your testcases/specs.
Controller tests require that you includeDevise::Test::IntegrationHelpers
onyour test case or its parentActionController::TestCase
superclass.For Rails versions prior to 5, includeDevise::Test::ControllerHelpers
instead, since the superclassfor controller tests was changed to ActionDispatch::IntegrationTest(for more details, see theIntegration tests section).
classPostsControllerTest <ActionController::TestCaseincludeDevise::Test::IntegrationHelpers# Rails >= 5end
classPostsControllerTest <ActionController::TestCaseincludeDevise::Test::ControllerHelpers# Rails < 5end
If you're using RSpec, you can put the following inside a file namedspec/support/devise.rb
or in yourspec/spec_helper.rb
(orspec/rails_helper.rb
if you are usingrspec-rails
):
RSpec.configuredo |config|config.includeDevise::Test::ControllerHelpers,type::controllerconfig.includeDevise::Test::ControllerHelpers,type::viewend
Just be sure that this inclusion is madeafter therequire 'rspec/rails'
directive.
Now you are ready to use thesign_in
andsign_out
methods on your controllertests:
sign_in@usersign_in@user,scope::admin
If you are testing Devise internal controllers or a controller that inheritsfrom Devise's, you need to tell Devise which mapping should be used before arequest. This is necessary because Devise gets this information from the router,but since controller tests do not pass through the router, it needs to be statedexplicitly. For example, if you are testing the user scope, simply use:
test'GET new'do# Mimic the router behavior of setting the Devise scope through the env.@request.env['devise.mapping']=Devise.mappings[:user]# Use the sign_in helper to sign in a fixture `User` record.sign_inusers(:alice)get:new# assert somethingend
Integration test helpers are available by including theDevise::Test::IntegrationHelpers
module.
classPostsTests <ActionDispatch::IntegrationTestincludeDevise::Test::IntegrationHelpersend
Now you can use the followingsign_in
andsign_out
methods in your integrationtests:
sign_inusers(:bob)sign_inusers(:bob),scope::adminsign_out:user
RSpec users can include theIntegrationHelpers
module on their:feature
specs.
RSpec.configuredo |config|config.includeDevise::Test::IntegrationHelpers,type::featureend
Unlike controller tests, integration tests do not need to supply thedevise.mapping
env
value, as the mapping can be inferred by the routes thatare executed in your tests.
You can read more about testing your Rails controllers with RSpec in the wiki:
Devise comes with OmniAuth support out of the box to authenticate with other providers. To use it, simply specify your OmniAuth configuration inconfig/initializers/devise.rb
:
config.omniauth:github,'APP_ID','APP_SECRET',scope:'user,public_repo'
You can read more about OmniAuth support in the wiki:
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 fieldscreate_table:adminsdo |t|t.string:emailt.string:encrypted_passwordt.timestampsnull:falseend# Inside your Admin modeldevise:database_authenticatable,:timeoutable# Inside your routesdevise_for:admins# Inside your protected controllerbefore_action:authenticate_admin!# Inside your controllers and viewsadmin_signed_in?current_adminadmin_session
Alternatively, you can simply run the Devise generator.
Keep in mind that those models will have completely different routes. Theydo not andcannot 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.
If you are using Active Job to deliver Action Mailer messages in thebackground through a queuing back-end, you can send Devise emails through yourexisting queue by overriding thesend_devise_notification
method in your model.
defsend_devise_notification(notification, *args)devise_mailer.send(notification,self, *args).deliver_laterend
If you enable theRecoverable 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:
- 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.
- 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 INFO by default. Consider changing your production logger level to WARN if you wish to prevent tokens from being leaked into your logs. Inconfig/environments/production.rb
:
config.log_level=:warn
Devise supports ActiveRecord (default) and Mongoid. To select another ORM, simply require it in the initializer file.
Rails 5+ has a built-inAPI Mode which optimizes Rails for use as an API (only). Devise issomewhat able to handle applications that are built in this mode without additional modifications in the sense that it should not raise exceptions and the like. But some issues may still arise duringdevelopment
/testing
, as we still don't know the full extent of this compatibility. (For more information, seeissue #4947)
API-only applications don't support browser-based authentication via cookies, which is devise's default. Yet, devise can still provide authentication out of the box in those cases with thehttp_authenticatable
strategy, which uses HTTP Basic Auth and authenticates the user on each request. (For more info, see this wiki article forHow To: Use HTTP Basic Authentication)
The devise default for HTTP Auth is disabled, so it will need to be enabled in the devise initializer for the database strategy:
config.http_authenticatable=[:database]
This restriction does not limit you from implementing custom warden strategies, either in your application or via gem-based extensions for devise.A common authentication strategy for APIs is token-based authentication. For more information on extending devise to support this type of authentication and others, see the wiki article forSimple Token Authentication Examples and alternatives or this blog post onCustom authentication methods with Devise.
API Mode changes the order of the middleware stack, and this can cause problems forDevise::Test::IntegrationHelpers
. This problem usually surfaces as anundefined method `[]=' for nil:NilClass
error when using integration test helpers, such as#sign_in
. The solution is simply to reorder the middlewares by adding the following to test.rb:
Rails.application.config.middleware.insert_beforeWarden::Manager,ActionDispatch::CookiesRails.application.config.middleware.insert_beforeWarden::Manager,ActionDispatch::Session::CookieStore
For a deeper understanding of this, reviewthis issue.
Additionally be mindful that without views supported, some email-based flows from Confirmable, Recoverable and Lockable are not supported directly at this time.
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:
https://github.com/wardencommunity/warden
We have a long list of valued contributors. Check them all at:
https://github.com/heartcombo/devise/graphs/contributors
MIT License. Copyright 2020-2024 Rafael França, Leonardo Tegon, Carlos Antônio da Silva. Copyright 2009-2019 Plataformatec.
The Devise logo is licensed underCreative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
About
Flexible authentication solution for Rails with Warden.