1
0
Fork 0
mirror of https://github.com/heartcombo/devise.git synced 2022-11-09 12:18:31 -05:00
heartcombo--devise/README.md

494 lines
20 KiB
Markdown
Raw Normal View History

2013-02-26 13:19:48 -05:00
![Devise Logo](https://raw.github.com/plataformatec/devise/master/devise.png)
2009-09-16 08:17:43 -04:00
2013-04-14 02:35:58 -04:00
By [Plataformatec](http://plataformatec.com.br/).
[![Build Status](https://api.travis-ci.org/plataformatec/devise.png?branch=master)](http://travis-ci.org/plataformatec/devise)
2013-02-26 13:27:58 -05:00
[![Code Climate](https://codeclimate.com/github/plataformatec/devise.png)](https://codeclimate.com/github/plataformatec/devise)
2011-11-06 17:18:46 -05:00
2012-09-18 07:30:04 -04:00
This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/).
2009-10-13 16:01:42 -04:00
Devise is a flexible authentication solution for Rails based on Warden. It:
* Is Rack based;
* Is a complete MVC solution based on Rails engines;
2013-07-23 04:21:01 -04:00
* Allows you to have multiple models signed in at the same time;
2009-10-13 16:01:42 -04:00
* Is based on a modularity concept: use just what you really need.
2013-08-08 16:37:15 -04:00
It's composed of 10 modules:
2009-10-13 16:01:42 -04:00
* [Database Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): 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.
2014-02-10 18:47:51 -05:00
* [Omniauthable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Omniauthable): adds Omniauth (https://github.com/intridea/omniauth) support.
* [Confirmable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
* [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions.
* [Registerable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account.
* [Rememberable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie.
* [Trackable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address.
* [Timeoutable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have no activity in a specified period of time.
* [Validatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations.
* [Lockable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.
2009-09-16 08:17:43 -04:00
2013-06-30 08:18:49 -04:00
Devise is guaranteed to be thread-safe on YARV. Thread-safety support on JRuby is on progress.
2012-01-30 15:45:08 -05:00
## Information
2009-10-13 16:01:42 -04:00
2012-01-30 15:45:08 -05:00
### The Devise wiki
2009-10-20 22:21:06 -04:00
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:
2010-06-28 15:25:03 -04:00
2013-09-13 07:47:27 -04:00
https://github.com/plataformatec/devise/wiki
2012-01-30 15:45:08 -05:00
### Bug reports
2009-12-12 19:52:48 -05:00
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:
2010-05-21 10:42:34 -04:00
2011-10-13 10:59:41 -04:00
https://github.com/plataformatec/devise/wiki/Bug-reports
2010-05-21 10:42:34 -04:00
2013-12-16 14:49:21 -05:00
If you found a security bug, do *NOT* use the GitHub issue tracker. Send an email to opensource@plataformatec.com.br.
2012-01-30 15:45:08 -05:00
### Mailing list
2010-04-05 06:21:02 -04:00
If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker:
2011-10-13 10:59:41 -04:00
https://groups.google.com/group/plataformatec-devise
2012-01-30 15:45:08 -05:00
### RDocs
You can view the Devise documentation in RDoc format here:
http://rubydoc.info/github/plataformatec/devise/master/frames
2013-05-07 12:32:03 -04:00
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.
2012-01-30 15:45:08 -05:00
### 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:
2011-10-13 10:59:41 -04:00
https://github.com/plataformatec/devise/wiki/Example-Applications
2012-01-30 15:45:08 -05:00
### 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:
2011-10-13 10:59:41 -04:00
https://github.com/plataformatec/devise/wiki/Extensions
2012-01-30 15:45:08 -05:00
### Contributing
We hope that you will consider contributing to Devise. Please read this short overview for some information about how to get started:
2011-10-13 10:59:41 -04:00
https://github.com/plataformatec/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 "rake". For the tests to pass, you will need to have a MongoDB server (version 2.0 or newer) running on your system.
2012-01-30 15:45:08 -05:00
## Starting with Rails?
2011-01-31 08:06:35 -05:00
2011-01-31 09:16:58 -05:00
If you are building your first Rails application, we recommend you to *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:
2011-01-31 08:06:35 -05:00
* Michael Hartl's online book: http://railstutorial.org/chapters/modeling-and-viewing-users-two#top
* Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch
2011-07-11 14:30:52 -04:00
Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :)
2011-01-31 08:06:35 -05:00
2012-01-30 15:45:08 -05:00
## Getting started
2009-10-13 16:01:42 -04:00
2013-05-07 12:32:03 -04:00
Devise 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with:
```ruby
gem 'devise'
```
Run the bundle command to install it.
2009-10-19 22:52:31 -04:00
After you install Devise and add it to your Gemfile, you need to run the generator:
2009-10-13 16:01:42 -04:00
2012-01-30 15:45:08 -05:00
```console
rails generate devise:install
```
2009-10-13 16:01:42 -04:00
The generator will install an initializer which describes ALL Devise's configuration options and you MUST take a look at it. When you are done, you are ready to add Devise to any of your models using the generator:
2009-10-13 16:01:42 -04:00
2012-01-30 15:45:08 -05:00
```console
rails generate devise MODEL
```
2009-10-13 16:01:42 -04:00
Replace MODEL by the class name used for the applications 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. Next, you'll usually run `rake db:migrate` as the generator will have created a migration file (if your ORM supports them). This generator also configures your `config/routes.rb` file to point to the Devise controller.
2010-01-13 13:45:24 -05:00
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`:
```ruby
config.action_mailer.default_url_options = { host: 'localhost:3000' }
```
You should restart your application after changing Devise's configuration options. Otherwise you'll run into strange errors like users being unable to login and route helpers being undefined.
2012-01-30 15:45:08 -05:00
### Controller filters and helpers
2009-10-30 05:23:47 -04:00
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:
2009-10-13 16:01:42 -04:00
2012-01-30 15:45:08 -05:00
```ruby
before_filter :authenticate_user!
```
2009-10-13 16:01:42 -04:00
To verify if a user is signed in, use the following helper:
2009-10-13 16:01:42 -04:00
2012-01-30 15:45:08 -05:00
```ruby
user_signed_in?
```
2009-10-13 16:01:42 -04:00
For the current signed-in user, this helper is available:
2009-10-13 16:01:42 -04:00
2012-01-30 15:45:08 -05:00
```ruby
current_user
```
2009-10-13 16:01:42 -04:00
You can access the session for this scope:
2009-10-18 16:31:01 -04:00
2012-01-30 15:45:08 -05:00
```ruby
user_session
```
2009-10-18 16:31:01 -04:00
After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect. For instance, for 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:
2012-01-30 15:45:08 -05:00
```ruby
2013-04-14 02:34:07 -04:00
root to: "home#index"
2012-01-30 15:45:08 -05:00
```
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:
2012-01-30 15:45:08 -05:00
```ruby
before_filter :authenticate_member!
2012-01-30 15:45:08 -05:00
member_signed_in?
2012-01-30 15:45:08 -05:00
current_member
2012-01-30 15:45:08 -05:00
member_session
```
2012-01-30 15:45:08 -05:00
### 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:
2012-01-30 15:45:08 -05:00
```ruby
devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 20
2012-01-30 15:45:08 -05:00
```
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.
2013-04-14 02:39:32 -04:00
### Strong Parameters
2009-10-30 05:23:47 -04:00
2013-04-14 02:39:32 -04:00
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.
2009-10-13 16:01:42 -04:00
2013-11-22 03:55:16 -05:00
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:
2013-04-14 02:34:07 -04:00
* `sign_in` (`Devise::SessionsController#new`) - 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 with a simple before filter in your `ApplicationController`:
2013-04-14 02:34:07 -04:00
```ruby
class ApplicationController < ActionController::Base
2013-04-14 11:49:30 -04:00
before_filter :configure_permitted_parameters, if: :devise_controller?
2013-04-14 02:34:07 -04:00
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
2013-04-14 02:34:07 -04:00
end
end
2012-01-30 15:45:08 -05:00
```
2009-10-13 16:01:42 -04:00
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_parameters_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
```ruby
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
end
```
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 thusly:
```ruby
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(roles: [], :email, :password, :password_confirmation) }
end
```
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
2013-07-23 04:21:01 -04:00
If you have multiple Devise models, you may want to set up different parameter sanitizer per model. In this case, we recommend inheriting from `Devise::ParameterSanitizer` and add your own logic:
2013-05-07 18:18:48 -04:00
```ruby
class User::ParameterSanitizer < Devise::ParameterSanitizer
def sign_in
default_params.permit(:username, :email)
end
end
```
And then configure your controllers to use it:
```ruby
class ApplicationController < ActionController::Base
protected
def devise_parameter_sanitizer
if resource_class == User
2013-05-07 18:18:48 -04:00
User::ParameterSanitizer.new(User, :user, params)
else
super # Use the default one
end
end
end
```
2013-04-14 02:34:07 -04:00
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.
2012-01-30 15:45:08 -05:00
### Configuring views
2010-01-13 13:45:24 -05:00
2010-04-12 07:48:22 -04:00
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.
2009-10-23 09:18:11 -04:00
2012-01-12 00:18:04 -05:00
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:
2009-10-23 09:18:11 -04:00
2012-01-30 15:45:08 -05:00
```console
rails generate devise:views
```
2010-01-13 13:45:24 -05:00
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.
2010-07-15 07:01:31 -04:00
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:
2010-07-15 07:01:31 -04:00
2012-01-30 15:45:08 -05:00
```console
rails generate devise:views users
```
2012-01-30 15:45:08 -05:00
### Configuring controllers
2010-04-12 07:48:22 -04:00
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`:
```ruby
class Admins::SessionsController < Devise::SessionsController
end
```
Note that in the above example, the controller needs to be created in the `app/controller/admins/` directory.
2. Tell the router to use this controller:
```ruby
devise_for :admins, controllers: { sessions: "admins/sessions" }
```
3. Copy the views from `devise/sessions` to `admins/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:
```ruby
class Admins::SessionsController < Devise::SessionsController
def create
# custom sign-in code
end
end
```
Or you can simply add new behaviour to it:
```ruby
class Admins::SessionsController < Devise::SessionsController
def create
super do |resource|
BackgroundWorker.trigger(resource)
end
end
end
```
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 failed. 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.
2012-01-30 15:45:08 -05:00
### Configuring routes
2010-07-18 18:31:51 -04:00
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:
2012-01-30 15:45:08 -05:00
```ruby
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' }
2012-01-30 15:45:08 -05:00
```
2010-07-18 18:31:51 -04:00
2012-03-05 11:01:46 -05:00
Be sure to check `devise_for` documentation for details.
2010-07-18 18:31:51 -04:00
2012-03-05 11:01:46 -05:00
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:
2010-07-18 18:31:51 -04:00
2012-01-30 15:45:08 -05:00
```ruby
devise_scope :user do
get "sign_in", to: "devise/sessions#new"
2012-01-30 15:45:08 -05:00
end
```
2010-08-02 07:22:45 -04:00
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.
2010-07-18 18:31:51 -04:00
2012-01-30 15:45:08 -05:00
### I18n
2009-10-19 23:28:01 -04:00
Devise uses flash messages with I18n with the flash keys :notice and :alert. To customize your app, you can set up your locale file:
2009-10-19 23:28:01 -04:00
2012-01-30 15:45:08 -05:00
```yaml
en:
devise:
sessions:
signed_in: 'Signed in successfully.'
```
2009-10-19 23:28:01 -04:00
You can also create distinct messages based on the resource you've configured using the singular name given in routes:
2009-10-19 23:28:01 -04:00
2012-01-30 15:45:08 -05:00
```yaml
en:
devise:
sessions:
user:
signed_in: 'Welcome user, you are signed in.'
admin:
signed_in: 'Hello admin!'
```
2009-10-19 23:28:01 -04:00
2010-07-15 07:01:31 -04:00
The Devise mailer uses a similar pattern to create subject messages:
2009-10-19 23:28:01 -04:00
2012-01-30 15:45:08 -05:00
```yaml
en:
devise:
mailer:
confirmation_instructions:
subject: 'Hello everybody!'
user_subject: 'Hello User! Please confirm your email'
reset_password_instructions:
subject: 'Reset instructions'
```
2009-10-19 23:28:01 -04:00
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:
2009-10-19 23:28:01 -04:00
2011-10-13 10:59:41 -04:00
https://github.com/plataformatec/devise/wiki/I18n
2012-01-30 15:45:08 -05:00
### Test helpers
2009-11-16 11:58:14 -05:00
2014-01-23 02:44:32 -05:00
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:
2012-01-30 15:45:08 -05:00
```ruby
class ActionController::TestCase
include Devise::TestHelpers
end
```
2012-06-07 07:31:43 -04:00
If you're using RSpec, you can put the following inside a file named `spec/support/devise.rb`:
2012-01-30 15:45:08 -05:00
```ruby
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
2012-01-30 15:45:08 -05:00
end
```
2012-06-07 07:31:43 -04:00
Now you are ready to use the `sign_in` and `sign_out` methods. Such methods have the same signature as in controllers:
```ruby
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 is 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;
2012-06-07 07:31:43 -04:00
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 router, but since functional tests do not pass through the router, it needs to be told explicitly. For example, if you are testing the user scope, simply do:
2012-06-07 07:31:43 -04:00
```ruby
2012-06-07 07:31:43 -04:00
@request.env["devise.mapping"] = Devise.mappings[:user]
get :new
```
2009-12-07 15:37:04 -05:00
2012-01-30 15:45:08 -05:00
### Omniauth
2012-11-10 14:51:20 -05:00
Devise comes with Omniauth support out of the box to authenticate with other providers. To use it, just specify your omniauth configuration in `config/initializers/devise.rb`:
2012-11-10 12:35:32 -05:00
```ruby
config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
2012-11-10 12:35:32 -05:00
```
You can read more about Omniauth support in the wiki:
2010-04-22 14:55:27 -04:00
2011-04-11 04:26:36 -04:00
* https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
2010-08-17 18:38:07 -04:00
2013-04-14 02:34:07 -04:00
### Configuring multiple models
2013-07-23 04:21:01 -04:00
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:
2013-04-14 02:34:07 -04:00
```ruby
# Create a migration with the required fields
create_table :admins do |t|
t.string :email
t.string :encrypted_password
t.timestamps
end
# Inside your Admin model
devise :database_authenticatable, :timeoutable
# Inside your routes
devise_for :admins
# Inside your protected controller
before_filter :authenticate_admin!
2013-04-14 02:34:07 -04:00
# Inside your controllers and views
admin_signed_in?
current_admin
admin_session
```
2013-07-23 04:21:01 -04:00
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 you to use a role-based approach, by either providing a role column or using [CanCan](https://github.com/ryanb/cancan).
2013-04-14 02:34:07 -04:00
### Other ORMs
Devise supports ActiveRecord (default) and Mongoid. To choose other ORM, you just need to require it in the initializer file.
## Additional information
2012-01-30 15:45:08 -05:00
### Heroku
Using Devise on Heroku with Ruby on Rails 3.1 requires setting:
2012-01-30 15:45:08 -05:00
```ruby
config.assets.initialize_on_precompile = false
```
Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html
2012-01-30 15:45:08 -05:00
### Warden
2009-11-10 15:55:13 -05:00
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:
2010-07-15 07:01:31 -04:00
2011-10-13 10:59:41 -04:00
https://github.com/hassox/warden
2012-01-30 15:45:08 -05:00
### Contributors
2010-05-03 08:00:32 -04:00
We have a long list of valued contributors. Check them all at:
https://github.com/plataformatec/devise/graphs/contributors
2009-11-10 15:55:13 -05:00
2012-01-30 15:45:08 -05:00
## License
2014-01-03 07:12:23 -05:00
MIT License. Copyright 2009-2014 Plataformatec. http://plataformatec.com.br
2013-02-26 13:19:48 -05:00
You are not granted rights or licenses to the trademarks of the Plataformatec, including without limitation the Devise name or logo.