This change add warnings for these configurations:
* strip_whitespace_keys - It is already explicit on config template, now
it will be the same of the template.
* email_regexp - In the new version this regexp will be more
permissive.
* reconfirmable - It is already explicit on config template, now
it will be the same of the template.
* skip_session_storage - It is already explicit on config template, now
it will be the same of the template.
* sign_out_via - It is already explicit on config template, now
it will be the same of the template.
These ones is important to change, since the configuration says current
explicit value are the default. It can lead to misunderstanging if users
remove the explicit configuration.
It also updates the template explicit values:
* Warns the `config.mailer_sender` is nil by default
* Update `config.password_length` to use the current default
* Make the e-mail configuration explicit
Now the config `extend_remember_period` is used to:
`true` - Every time the user authentication is validated, the
cookie expiration is updated.
`false` - Does not updates the cookie expiration.
Closes#3994
[A change in Rails 5](3979403781) left me hunting for hours on why I could no longer log in to my application. To save others the trouble, I thought it would be nice to note it in the README.
Rails 5 deprecates inheriting directly from `ActiveRecord::Migration` in
favor of inheriting from `ActiveRecord::Migration[5.0]` where `5.0` is
the `major.minor` version of Rails that the migration was originally
written to support.
h/t to b0ce189c69.
This was deprecated on rails/rails#23980.
We now generate scope and provider specific routes, like `user_facebook_omniauth_callback`
or `user_github_omniauth_callback`.
We could deprecate the `omniauth_authorize_path` in favor of the generated routes, but
the `shared/links.html.erb` depends on it to generate all omniauth links at once.
Closes#3983.
* Expand the explanation of why it fail.
* Raise a subclass of `Thor::Error` so the Thor doesn't output the exception
backtrace as it isn't useful for developers facing this error.
I'd like to remove the Hakiri badge from devise's README.
Since we do check in Gemfile and Gemfile.lock for development
and testing purposes (contrary to the popular belief that gems
don't need those files), Hakiri thinks Devise is a Rails app,
instead of a library/gem.
Depending on the Rails version that is locked in Gemfile.lock,
Hakiri will show several CVEs for Rails. But our Travis pipeline
builds against several Rails' branches, all of them updated.
And it is up to the developers using Devise to update
Rails in their apps.
Those warnings (Rails CVEs) don't make sense for devise.
Throughout the documentations, we are using 'encrypt' incorrectly.
Encrypt means that someone will eventually decrypt the message,
which is obviously not the case for Devise.
I'm changing the docs to use 'hashing' instead.
However, I left the database field as `encrypted_password` for now.
I'll update the db field in an upcoming PR.
Time objects aren't properly coerced back when using the JSON cookie serialization,
so we need to do it ourselves.
To avoid any new JSON serialization issues, we now store the `generated_at` as
an String with the timestamp seconds + miliseconds in the cookie but still the
previous JSON encoded format.
Thanks to @boblail at https://github.com/plataformatec/devise/pull/3917 for the
initial patch.
Devise::ParameterSanitizer has a new syntax for permitting additional
attributes to a model. This commit updates the generated controllers to
reflect that.
We no longer need to support the `BaseSanitizer` implementation for apps without
the Strong Parameters API, and this section is lacking a minimal set of
docs to document the expected behavior besides the `README` section.
This solves the issue where a package might do:
```
user = User.new
user.email = 'test@test.com'
token = user.generate_reset_token
user.save
send_reset_email(token)
```
Since the save clears the reset token, the user will receive a stale token that no longer works.
Closes#3774
The current implementation is opinionated about the resource should have
an "email" column on it if it is to be recoverable, which isn't
necessarily the case. For example, developers may decide to pull emails
out into their own model or have some other way of communicating
password resets to their users (e.g. text message)
I'm not sure there's an easy test to put together for this case, as
minitest doesn't make it very easy to stub the "email_changed?" to raise
an error. Happy to look into building another model in the
"test/rails_app" if you want to have this properly tested though? Or for
a nice way to get calls to "email_changed?" to raise; minitest isn't
a test framework I'm overly familiar with :).
As a side note, it would be nice if the Validatable module also took
this into account, I may raise another PR for that.
This comes off the back of comments on this commit:
e641b4b7b9
* Replace "the instance variable name in controller" with "the helper methods
names in controller".
Devise dose not define instance variable for controllers but define helper
methods for controllers.
* Replace "the name in routes" with "the scope name in routes".
`singular` is used as an argument of `devise_scope`.
* Add sample codes of routing and controller.
If a new user is created with a reset password token, the previous behavior
would automatically clear the token even when it was desired for setting
the password for the first time.
Our Simple Form generator shouldn't be responsible for generating the `mailer`
view directory, so we should skip it and let the Erb generator do the job.
Closes#3254.
The existing comment seems to be either outdated or obscure. I interpret it as meaning that configure_warden! is invoked by an 'initializer' block in class Devise::Engine, i.e. in lib/devise/rails.rb. However, as far as I can tell the only time the method is invoked is when ActionDispatch::Routing::RouteSet#finalize! is called, and this is aliased by devise to finalize_with_devise!.
Allow basic authentication to be case insensitive as per the HTTP 1.1 spec RFC 2068 Section 11
> It uses an extensible, case-insensitive token to identify the authentication scheme, followed by a comma-separated list of attribute-value pairs which carry the parameters necessary for achieving authentication via that scheme.
We have a particular client in production that has basic auth hard-coded as `basic` rather than `Basic` and devise is rejecting perfectly fine credentials. Making this small change has allowed us to authenticate this client with no issues.
I'm not hugely familiar with ruby internals vis a vis sclass semantics,
but this *probably* serves as a workaround for the MRI thread-safety
bug mentioned in #3505.
Beyond that, and even if this doesn't fix the thread-safety issue, per
[this blog post][1], `define_method` is recommended over `class_eval`
for performance (and, fwiw, readability) reasons anyway.
[1]: http://tenderlovemaking.com/2013/03/03/dynamic_method_definitions.html
This logic is generic and reusable -- hash a secret; and take an
unhashed secret and compare it to a hashed secret. This breaks this out
to make it reusable in other places. Specifically, we use this in our
own token auth at Bonobos that we plan to split out as a Devise
extension. This will make that possible without copy & pasting this
code.
Now that Rails 3.1 is not supported anymore, we don't need to implement
to_xml, since it does the right thing by calling serializable_hash.
This removes the class_eval need that existed to simplify the
implementation of both to_xml and serializable_hash.
Devise.available_router_name currently returns either
Devise.router_name or :main_app. As such, any redirecting is done
within either of those contexts. Which leads to undesirable redirects
for scopes that reside in an isolate_namespace mounted engine.
This commit makes it possible for FailureApp’s redirect behavior to be
performed in the context of the router_name given to devise_for.
Test case added to cover undesirable behavior. Without change to
lib/devise/failure_app.rb, test case throws exception.
In order to be more clear about the expectations of for authenticating, we use
`password.present?` so there is no confusion about the role of the `valid_password?`
method.
More info: https://github.com/plataformatec/devise/issues/3519
Introspecting the scope of an object can make it difficult to use
wrapper patterns. See issue plataformatec/devise#3307 for an example.
Allow objects to specify their scope explicitly by implementing
`devise_scope`.
Rails 5 will [not have `hide_action` any longer](https://github.com/rails/rails/pull/18371/files), as the Rails convention is to not expose private or protected methods as actions, thus obviating the need for `hide_action`.
Presumably, there is code inheriting from `DeviseController` that is
calling these helpers, so they cannot be private, so protected seems to
be the only way to get Devise working with Rails 5.
Due to bug in Ruby 2.2.0; The bug has been acknowledged and fixed in trunk.
When password comes in FormEncoded the result of `gsub` breaks when
peppered with `nil`.
This only adds pepper if defined on the model and works around this
bug.
See: 622f3f14b6
This reverts commit 43d0715238.
save() returns false only when validations failed. In this case, validations are
not performed. Therefore save() may never return a falsy value.
If save() fails, the appropriate exception is raised.
With certain ORMs, such as NoBrainer, save() never returns true/false, but
always raise an exception. This commit lift the incompatiblity.
This should still keep the devise lookup in the case that a customed scope is not passed as option, but if instead the custom scope is passed, then the find_message method will use it.
This is kind of useful, if i don't want overwrite the devise locale, and use different locale files, but keeping still the fallback of my devise locale.
It is obvious that this initializer should be executed before Rails build_middleware_stack as Omniauth is build on middleware.
Also it is obvious that we need that initializer to be executed after all config/initializers/* files (that is where devise.rb usually is).
The warden method in the Devise::TestHelpers module adds a Warden proxy
object to the request environment hash under the 'warden' key. Including
this module in your test case registers that method as a callback, which
runs before every test:
https://github.com/plataformatec/devise/blob/v3.4.1/lib/devise/test_helpers.rb#L12
The request object itself is created in a callback added by Rails:
https://github.com/rails/rails/blob/v4.2.0/actionpack/lib/action_controller/test_case.rb#L687
So before each test runs, the Rails callback creates the request object,
and then the Devise callback adds a Warden proxy object to it.
I was using the rspec-retry gem (https://github.com/y310/rspec-retry),
and noticed that my controller specs would always fail whenever they
were retried with this error:
NoMethodError: undefined method `authenticate!' for nil:NilClass
When rspec-retry re-runs a failed test, it runs the setup callbacks
again. The Rails callback creates a new request object, but because of
the memoization that was here before, the Devise callback wouldn't add a
Warden proxy to it, which was causing the error.
With this change, the Warden setup code will still only run once as long
as the request object stays the same, but if it changes a new Warden
proxy will be added to the new request object.
There's no real need to pass 2 variables to the view to figure that out,
we can simply display the message relying on whether or not the
`@minimum_password_length` variable is present.
- use the new build env on Travis (sudo: false) (docs coming soon)
faster vms, more cpu, more ram, faster vm boot time
- remove the custom caching for now as the new setup has a far better network
- add rails-head to the gemfile list as it wasn't there
caching is generally not recommended for libs like Devise as you want to test against the latest gem versions. Caching will use the min requirements available on the system instead of retrieving the latest.
On that note, it is also recommended to remove the Gemfile.lock from the repo. For now I have just 'rm'd it before 'bundle install'
Allow to ensure valid upon confirming.
We might want to consider confirmation status in validations. For example, maybe we want to require certain fields upon confirmation, but not at registration.
BCrypt has a limit of 72 characters for the password. Anything beyond 72
characters is truncated. This commit updates the validation to limit
passwords to less than 72 characters, keeping within the limitation.
As I've described [here](http://keepachangelog.com), it's quite useful to associate release version numbers with dates to get situated in a change log.
Hope you find this useful.
PS: While doing this I did notice that a release marked as yanked in the CHANGELOG was not showing up as yanked on RubyGems, hence #3289.
As we are already slicing the Hash, we must be sure that this method will send
a "safe" object down to the other finder methods that will use the Hash entries
to do the querying.
Depending on the test order, there might a moment when a test reloads the I18n
backend and another tries to store a translation, but since the backend wasn't
re-initialized the custom translations would be overriden when i18n loads the
translations from the en.yml file.
... is enabled.
The old code may cause conflicts when developing an engine (i.e. invalid
route name) and according to @josevalim the reason for it to remain is
unknown.
Until 4.2.0, any test suite based on the `TestCase` classes provided by Rails would
always run into alphabetical, but now they run in random order. For now, we ensure
that our tests always run in alphabetical order.
Related commit on rails/rails
6ffb29d24e
This was broken in Rails 4.2.0+ because the `@scope` object is no longer a Hash
but an internal structure that supports a better override/rollback flow for cases
like this. If we would only support Rails 4.2, this method could be something
like this:
```ruby
def with_devise_exclusive_scope(new_path, new_as, options)
overrides = { as: new_as, path: new_path, module: nil }
overrides.merge!(options.slice(:constraints, :defaults, :options))
@scope = @scope.new(overrides)
yield
ensure
@scope = @scope.parent
end
```
I was seeing the following in my console:
```
/home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/devise-3.2.4/app/controllers/devise_controller.rb:9: warning: `*' interpreted as argument prefix
/home/vagrant/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/devise-3.2.4/app/controllers/devise_controller.rb:10: warning: `*' interpreted as argument prefix
```
This change silences this warning.
This leaks into Devise mappings overriding the existing :admin one, so
depending on the test seed it fails like this:
$ TESTOPTS="--seed=9972" rake
==> Devise.orm = :active_record
Run options: --seed=9972
...
1) Failure:
MappingTest#test_allows_path_to_be_given [./test/mapping_test.rb:31]:
Expected: "admin_area"
Actual: "admin"
Using a different name should avoid any test randomization issues.
Previously the test was raising an ArgumentError by mistake:
ArgumentError: wrong number of arguments (0 for 1)
actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:328:in `eval_block'`
The #eval_block method expects a proc/lambda argument that can be
instance_exec'ed, not a real block. In the Rails implementation the block
is passed to #draw, which calls #eval_block internally passing the block
along, but as a Proc argument and not as a block.
Also the error we were raising from #devise_for was a RuntimeError,
changed to the expected ArgumentError. Adding an assertion on top of the
expected message should ensure we won't have this issue again.
This was introduced in 29da146c07, related
to #2802.
Also refactor tests to remove the custom failure app class only used
once in favor of an inline class for the specific test, makes it easier
to follow what's going on.
after_confirmation_path_for checks whether the user already signed in
by calling signed_in? after confirmation succeeded.
Since it was called without scope specification, the user treated as
signed in inappropriately when the user signed in as another resource
(such as 'admin').
Changes the behavior of `Devise.warden` such that calling it multiple
times with different blocks will result in a call to each block on
`Devise.configure_warden!` rather than "last block wins". This is
especially used for plugins that wish to extend warden functionality
without clobbering base app configuration or vice versa.
Only execute the `SessionsController#destroy` if there is a signed in
user, otherwise it will raise
`ActionController::InvalidAuthenticityToken`.
Fixes#2934.
Pushing the `Time` object inside the session has inconsistencies
across different serializers and we should use a more primitive type
so we don't need any specific parsing logic for the JSON serializer.
* this will avoid people (like me) loosing an hour trying to understand
why doing it "a little bit safer" with 20 stretches suddenly takes
60 seconds to do sign_up or sign_in. An example of such discussion is:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/399627
The default specified in the docs does not match up with the default
specified in the config.
See
cc8636cfed/lib/devise.rb (L127)
Changing the docs to read 6..128 with the config setting to 8..128 is
feared to cause confusion, so removing the default clause instead.
The updates are:
* Indicate that it is possible to pass a block to `super` to add custom
behaviour to some Devise controller actions without completely
overriding them.
* Move mailer configuration out of the section "Controller filters and
helpers".
* Consistently use Ruby 1.9's hash syntax, highlight code and capitalize
"Devise".
* Wording improvements
Right now if you try to use a route that you have defined in your `omniauth_callbacks` but you have not declared that resource to be `omniauthable` you will get a weird route missing error which causes the user to look in the routes for the fix:
```ruby
devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}
```
This PR checks to see if the mapping of `:user` has the module `omniauthable` included in it when `omniauth_callbacks` is specified in the route. If it does not, an instructional error is raised:
```
Mapping omniauth_callbacks on a resource that is not omniauthable
Please add `devise :omniauthable` to the `User` model
```
Since we don't have authentication token, we don't have to check if
password is "X".
:authentication_token don't have to be in the blacklist for
serialization too.
This is used as a complement to `stored_location_for`.
Example:
Before authorizing with Omniauth;
store_location_for(:user, dashboard_path)
redirect_to user_omniauth_authorize_path(:facebook)
In our Omniauth callback
sign_in(user)
redirect_to stored_location_for(:user) || root_path
If you want to add a new behavior to your devise
controllers but you don't want to override devise's
default workflow, just pass a block around resource.
This would give you for example, the ability to
trigger background jobs after user signs in.
This method is part of the protected API and is used by custom
encryption engines (like `devise-encryptable`) to hook the custom
encryption logic in the models.
Fixes#2730
+ @@last_attempt_warning
+ last_attempt? method;
* send :last_attempt key if it is the last attempt
+ test for last attempt
* update test to make two asserts
* update message
For #2627
When allow_unconfirmed_access_for > 0, users may
be already signed in at the time they confirm
their account. Consequently, the default
confirmation should be compatible with this
possibility. Additionally, they should not be
redirected to the sign in form after confirmation
in this case. So I've changed
ConfirmationsController#after_confirmation_path_for
to send the user to the root path when signed in,
or the sign in form otherwise.
The :confirmed default message in devise.en.yml
used to say "You are now signed in." This is no
longer the default behavior in v3.1.0.
This commit renames that message to
:confirmed_and_signed_in and changes the :confirmed
message to be appropriate for the default post-
confirmation location (which is now the new session
page). The new :confirmed message reads:
"Your account was successfully confirmed. Please
sign in."
- Move the default permitted parameters into ParameterSanitizer::PermittedParameters
- Add devise_permitted_parameters helper
- devise_permitted_parameters.add to add permitted parameters
- devise_permitted_parameters.remove to remove Devise's defaults
- devise_permitted_parameters.for to access the parameters for a given action
- Update 'Strong Parameters' section of README
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
I added an extra note in the section on creating a custom (namespaced) controller.
This controller needs to be created in a directory in order for it to work. Otherwise (for example when creating the controller in `app/controllers`) a `uninitialized constant Admins` error is thrown.
Also, fixed the Markdown formatting for the numbered lists in the README.
We could always generate a confirmation token but not sending a
confirmation email by invoking the skip_confirmation_notification!
method when creating the account.
But there were no way to do that when we were turning on reconfirmable
and updating email.
At times, validations may be skipped and no email address may be
provided. Such an instance comes when testing uniqueness validations of
specific attributes in a Devise model with confirmable, especially when
using Shoulda matchers.
Devise::RegistrationsController#create set self.resource to the return value of build_resource--which is nil, because build_resource sets self.resource to an actual resource object. This caused attempting to save the resource (two lines down) to fail with "undefined method `save' on nil:NilClass."
* Rename #get_constraints_given_method to #constraints_for to make the
method clear.
* The method name now is required.
* Use symbols instead of strings.
* Make #constraints_for a protected method.
This updates Devise's StrongParameter support to feature:
- A Null base sanitizer to support existing Rails 3.x installations that
don't want to use StrongParameters yet
- A new, simpler API for ParameterSanitizer: #permit, #permit!, and #forbid
- Overrideable callbacks on a controller-basis, e.g. #create_sessions_params
for passing the current scope's parameters through StrongParameters and
a helper method, whitelisted_params, for rolling your own implementations
of #create_x_params in your own controllers.
- Lots of tests!
This brings support for Rails 4 StrongParameters changes.
- Parameter sanitizing is setup for Devise controllers via
resource_params except Omniauth Callbacks which doesn't use
resource_params.
- Change #build_resource to not call resource_params for get requests.
Parameter sanitizing is only needed when params are posted to the
server so there's no need to try to construct resource params on get
requests (new, edit).
There are a couple of gotchas in the existing documentation
about the `send_devise_notification` hook.
1. The `after_commit` callback can be called multiple times
so you should clear the array otherwise any additional
invocations will trigger extra copies of the email.
2. The `after_commit` callback is only called when a record
is created or updated so you need to check for `new_record?`
or `changed?` before adding it to `pending_notifications`
otherwise it's okay to send it immediately.
The `new_record? || changed?` condition is necessary because
the latter isn't always true for new records, e.g:
>> User.new.changed?
=> false
[ci skip]
This was the previous functionality since we didn't set anything in the
application configuration. Now when using protected attributes gem, it
sets whitelist to true, forcing us to always declare the accessible
attributes, and this is not the case for the Admin model.
Previously inheriting from Devise::Mailer would not render default views
from devise when the inheriting mailer didn't have the view. Now it'll
correctly pick the default one from Devise::Mailer.
The id attribute is not Integer in Mongo, so it fails with something like:
NoMethodError: undefined method `+' for "5106fc06ee6da1ee44000002":Moped::BSON::ObjectId'`
With #next, it will work with both Integer and String ids, for both AR
and Mongo, returning a different id to test for filtered conditions.
It is advisable to use link_to for mostly GET operations. Actions like DESTROY when presented as a link can cause severe vulnerabilities.
Hence using a button is advisable.
This avoids calling strip and downcase on globally configured keys that may
not exist on all devise models. Fixes#2204, a regression introduced by
PR #2135. Also included a note about the intentional use of respond_to.
For a point release upgrade, Devise should not throw an exception when trying
to downcase or strip globally configured keys. This would be a breaking
change in functionality and this test demonstrates the issue.
In DatabaseAuthenticatable#update_with_password, password is now deleted if
the current_password is invalid. dm-validations will not check the
confirmation in that case, so this test was failing in dm-devise.
Attribute unlock token is not present in the simple_form template,
therefore not being displayed by #error_notification.
This fix explicitily call #full_error on :unlock_token.
fixes#2143
Attribute confirmation token is not present in the simple_form template,
therefore not being displayed by #error_notification.
This fix explicitily call #full_error on :confirmation_token.
This has no actual changes to Devise itself, just fixes the failing
tests when running against Mongoid 3 instead of Mongoid 2.
Mocha has been locked at 0.10.0 since 0.12.0 raises an error when trying
to set an expectation on a frozen object.
Tests were updated to work with both AR and Mongoid, some cases the XML
serialization was slightly different but both were outputting correct
and valid XML, and the id/_id field mismatch is now handled.
An active field was missing from the test models for Mongoid, and the
invalid :null => true options in field were removed.
This is another failing test for #1994, a unit test for Lockable. Lockable's
#uanauthenticated_message should not return :locked if paranoid mode is on
and instead should return the generic :invalid response.
The _process_unauthenticated method in test_helper was returning
the response as the body. When setting rendering the text, it was
calling to_s on the response which would render something like
this: #<ActionDispatch::Response:0x007fb9e1efea00>. This change
renders the body of the response instead of the response itself
- Favor using update_attribute instead of constructor parameters in user
factory for tests
- Test for accurate error message when confirmation token is expired
- Don't check twice whether the confirmation period is expired
With this patch, functionality is added to expire the confirmation
tokens that are being sent by email.
For example, if a token is valid for 3 days only, it cannot be used for
confirmation on the 4th day.
In light of recent discussions around mass assignment security and
the alternate solution of using the controller to filter params, not the model,
a hook/helper is needed to be able to override how the params are filtered
before they are used to build the resource.
Code cleanup for returning headers instead of an empty string
when destroying sessions.
Lines 464 and 471 on test/integration/autenticatable_test.rb
were adjusted to assert on :no_content
find_for_authentication should be called during only during
an authentication process.
This reverts commit a4c9d5826d, reversing
changes made to f94b71038e.
This is also better for translations, because we can translate paragraph-wise.
signed_up_but_inactive and signed_up_but_locked are likely not needed,
but I wasn't sure how to best remove them.
failed attempts count gets reset. When the user tries to login with an incorrect password next,
the message shown is for invalid password instead of locked account since this check
depended mainly on failed attempts count.
This allows alternate ORMs to run compatibility setup code before
Authenticatable is included.
The particular issue for dm-devise is that DataMapper does not have a
before_validation method, which is called when Authenticatable is included
(as of plataformatec/devise@bd27bf76). dm-devise adds before_validation in
it's devise_modules_hook!
There is a delegator to get failure app, introduced in 4629bee and tuned
in 24b26026. The latter commit introduced a bit of logic, however, no
tests are included into commit. Needless to say this resulted in a
broken code.
The point is that `env["warden.options"][:scope]` returns a string.
However, `Devise.mappings` is a hash with symbol keys.
Adding tests and converting scope to symbol here.
It was impossible to accomplish this by providing a
custom #after_sign_out_path_for in ApplicationController because the
session gets destroyed before it is called. Furthermore,
resource_return_to is now used by default if it exists, so users won't
have to provide a custom #after_sign_out_path_for in that case.
Documentation states that authentication_keys should accept a hash with
values indicating whether or not each key is required. This was added in
b2066cc2 but tests only covered request_keys, and 29afe2d2 later broke
it with a << array operator.
- attr_accessible not set for test user model, making Serializable tests
inaccurate
- Mongoid does not `include_root_in_json` by default, so enable this for
consistency with AR tests
- Mark tests pending for Mongoid < 2.1 that fail there due to known bugs
- Add `:mongoid` key for i18n model labels
- Remove outdated shim of `update_attribute` that caused mass assignment
security to be applied (ugh, that took awhile to find)
Per josevalim, by setting {:format => false} in @scope[:options],
Rails will pick it up, without the need to alter each devise_*()
method individually.
* Introduced `DeviseController#set_flash_message!` for conditional flash
messages setting to reduce complexity.
*`rails g devise:install` will fail if the app does not have a ORM configured
(by @arjunsharma)
* Support to Rails 5 versioned migrations added.
* deprecations
* omniauth routes are no longer defined with a wildcard `:provider` parameter,
and provider specific routes are defined instead, so route helpers like `user_omniauth_authorize_path(:github)` are deprecated in favor of `user_github_authorize_path`.
You can still use `omniauth_authorize_path(:user, :github)` if you need to
call the helpers dynamically.
### 4.0.0.rc1 - 2016-01-02
* Support added to Rails 5 (by @twalpole).
* Devise no longer supports Rails 3.2 and 4.0.
* Devise no longer supports Ruby 1.9 and 2.0.
* deprecations
* The `devise_parameter_sanitize` API has changed:
The `for` method was deprecated in favor of `permit`:
* sessions/new and registrations/new also respond to xml and json now
* bug fix
* Fix a regression that occurred if reset_password_sent_at is not present (by github.com/stevehodgkiss)
== 1.3.0
* enhancements
* All controllers can now handle different mime types than html using Responders (by github.com/sikachu)
* Added reset_password_within as configuration option to send the token for recovery (by github.com/jdguyot)
* Bump password length to 128 characters (by github.com/k33l0r)
* Add :only as option to devise_for (by github.com/timoschilling)
* Allow to override path after sending password instructions (by github.com/irohiroki)
* require_no_authentication has its own flash message (by github.com/jackdempsey)
* bug fix
* Fix a bug where configuration options were being included too late
* Ensure Devise::TestHelpers can be used to tests Devise internal controllers (by github.com/jwilger)
* valid_password? should not choke on empty passwords (by github.com/mikel)
* Calling devise more than once does not include previously added modules anymore
* downcase_keys before validation
* backward incompatible changes
* authentication_keys are no longer considered when creating the e-mail validations, the previous behavior was buggy. You must double check if you were relying on such behavior.
== 1.2.1
* enhancements
* Improve update path messages
== 1.2.0
* bug fix
* Properly ignore path prefix on omniauthable
* Faster uniqueness queries
* Rename active? to active_for_authentication? to avoid conflicts
== 1.2.rc2
* enhancements
* Make friendly_token 20 chars long
* Use secure_compare
* bug fix
* Fix an issue causing infinite redirects in production
* rails g destroy works properly with devise generators (by github.com/andmej)
* before_failure callbacks should work on test helpers (by github.com/twinge)
* rememberable cookie now is httponly by default (by github.com/JamesFerguson)
* Ensure after_* hooks are called on RegistrationsController
* When using database_authenticatable Devise will now only create an email field when appropriate (if using default authentication_keys or custom authentication_keys with email included)
* Ensure stateless token does not trigger timeout (by github.com/pixelauthority)
* Implement handle_unverified_request for Rails 3.0.4 compatibility and improve FailureApp reliance on symbols
* Consider namespaces while generating routes
* Custom failure apps no longer ignored in test mode (by github.com/jaghion)
* Do not depend on ActiveModel::Dirty
* Manual sign_in now triggers remember token
* Be sure to halt strategies on failures
* Consider SCRIPT_NAME on Omniauth paths
* Reset failed attempts when lock is expired
* Ensure there is no Mongoid injection
* deprecations
* Deprecated anybody_signed_in? in favor of signed_in? (by github.com/gavinhughes)
* Removed --haml and --slim view templates
* Devise::OmniAuth helpers were deprecated and removed in favor of Omniauth.config.test_mode
== 1.2.rc
* deprecations
* cookie_domain is deprecated in favor of cookie_options
* after_update_path_for can no longer be defined in ApplicationController
* enhancements
* Added OmniAuth support
* Added ORM adapter to abstract ORM iteraction
* sign_out_via is available in the router to configure the method used for sign out (by github.com/martinrehfeld)
* Improved Ajax requests handling in failure app (by github.com/spastorino)
* Added request_keys to easily use request specific values (like subdomain) in authentication
* Increased the size of friendly_token to 60 characters (reduces the chances of a successful brute attack)
* Ensure the friendly token does not include "_" or "-" since some e-mails may not autolink it properly (by github.com/rymai)
* Extracted encryptors into :encryptable for better bcrypt support
* :rememberable is now able to use salt as token if no remember_token is provided
* Store the salt in session and expire the session if the user changes his password
* Allow :stateless_token to be set to true avoiding users to be stored in session through token authentication
* cookie_options uses session_options values by default
* Sign up now check if the user is active or not and redirect him accordingly setting the inactive_signed_up message
* Use ActiveModel#to_key instead of #id
* sign_out_all_scopes now destroys the whole session
* Added case_insensitive_keys that automatically downcases the given keys, by default downcases only e-mail (by github.com/adahl)
* default behavior changes
* sign_out_all_scopes defaults to true as security measure
* http authenticatable is disabled by default
* Devise does not intercept 401 returned from applications
* bugfix
* after_sign_in_path_for always receives a resource
* Do not execute Warden::Callbacks on Devise::TestHelpers (by github.com/sgronblo)
* Allow password recovery and account unlocking to change used keys (by github.com/RStankov)
* FailureApp now properly handles nil request.format
* Fix a bug causing FailureApp to return with HTTP Auth Headers for IE7
* Ensure namespaces has proper scoped views
* Ensure Devise does not set empty flash messages (by github.com/sxross)
== 1.1.6
* Use a more secure e-mail regexp
* Implement Rails 3.0.4 handle unverified request
* Use secure_compare to compare passwords
== 1.1.5
* bugfix
* Ensure to convert keys on indifferent hash
* defaults
* Set config.http_authenticatable to false to avoid confusion
== 1.1.4
* bugfix
* Avoid session fixation attacks
== 1.1.3
* bugfix
* Add reply-to to e-mail headers by default
* Updated the views generator to respect the rails :template_engine option (by github.com/fredwu)
* Check the type of HTTP Authentication before using Basic headers
* Avoid invalid_salt errors by checking salt presence (by github.com/thibaudgg)
* Forget user deletes the right cookie before logout, not remembering the user anymore (by github.com/emtrane)
* Fix for failed first-ever logins on PostgreSQL where column default is nil (by github.com/bensie)
* :default options is now honored in migrations
== 1.1.2
* bugfix
* Compatibility with latest Rails routes schema
== 1.1.1
* bugfix
* Fix a small bug where generated locale file was empty on devise:install
== 1.1.0
* enhancements
* Rememberable module allows user to be remembered across browsers and is enabled by default (by github.com/trevorturk)
* Rememberable module allows you to activate the period the remember me token is extended (by github.com/trevorturk)
* devise_for can now be used together with scope method in routes but with a few limitations (check the documentation)
* Support `as` or `devise_scope` in the router to specify controller access scope
* HTTP Basic Auth can now be disabled/enabled for xhr(ajax) requests using http_authenticatable_on_xhr option (by github.com/pellja)
* bug fix
* Fix a bug in Devise::TestHelpers where current_user was returning a Response object for non active accounts
* Devise should respect script_name and path_info contracts
* Fix a bug when accessing a path with (.:format) (by github.com/klacointe)
* Do not add unlock routes unless unlock strategy is email or both
* Email should be case insensitive
* Store classes as string in session, to avoid serialization and stale data issues
* deprecations
* use_default_scope is deprecated and has no effect. Use :as or :devise_scope in the router instead
== 1.1.rc2
* enhancements
* Allow to set cookie domain for the remember token. (by github.com/mantas)
* Added navigational formats to specify when it should return a 302 and when a 401.
* Added authenticate(scope) support in routes (by github.com/wildchild)
* Added after_update_path_for to registrations controller (by github.com/thedelchop)
* Allow the mailer object to be replaced through config.mailer = "MyOwnMailer"
* bug fix
* Fix a bug where session was timing out on sign out
* deprecations
* bcrypt is now the default encryptor
* devise.mailer.confirmations_instructions now should be devise.mailer.confirmations_instructions.subject
* devise.mailer.user.confirmations_instructions now should be devise.mailer.confirmations_instructions.user_subject
* Generators now use Rails 3 syntax (devise:install) instead of devise_install
== 1.1.rc1
* enhancements
* Rails 3 compatibility
* All controllers and views are namespaced, for example: Devise::SessionsController and "devise/sessions"
* Devise.orm is deprecated. This reduces the required API to hook your ORM with devise
* Use metal for failure app
* HTML e-mails now have proper formatting
* Allow to give :skip and :controllers in routes
* Move trackable logic to the model
* E-mails now use any template available in the filesystem. Easy to create multipart e-mails
* E-mails asks headers_for in the model to set the proper headers
* Allow to specify haml in devise_views
* Compatibility with Mongoid
* Make config.devise available on config/application.rb
* TokenAuthenticatable now works with HTTP Basic Auth
* Allow :unlock_strategy to be :none and add :lock_strategy which can be :failed_attempts or none. Setting those values to :none means that you want to handle lock and unlocking by yourself
* No need to append ?unauthenticated=true in URLs anymore since Flash was moved to a middleware in Rails 3
* :activatable is included by default in your models
* bug fix
* Fix a bug with STI
* deprecations
* Rails 3 compatible only
* Removed support for MongoMapper
* Scoped views are no longer "sessions/users/new". Now use "users/sessions/new"
* Devise.orm is deprecated, just require "devise/orm/YOUR_ORM" instead
* Devise.default_url_options is deprecated, just modify ApplicationController.default_url_options
* All messages under devise.sessions, except :signed_in and :signed_out, should be moved to devise.failure
* :as and :scope in routes is deprecated. Use :path and :singular instead
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses, without explicit permission
* Other unethical or unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by sending an email to [conduct@plataformatec.com.br](conduct@plataformatec.com.br) or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
1) Do not post questions in the issues tracker. If you have any questions about Devise, search the [Wiki](https://github.com/plataformatec/devise/wiki) or use the [Mailing List](https://groups.google.com/group/plataformatec-devise) or [Stack Overflow](http://stackoverflow.com/questions/tagged/devise).
2) If you find a security bug, **DO NOT** submit an issue here. Please send an e-mail to [opensource@plataformatec.com.br](mailto:opensource@plataformatec.com.br) instead.
3) Do a small search on the issues tracker before submitting your issue to see if it was already reported / fixed.
4) When reporting an issue, include Rails, Devise and Warden versions. If you are getting exceptions, please include the full backtrace.
5) Notice that all of your interactions in the project are expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md)
That's it! The more information you give, the easier it becomes for us to track it down and fix it.
Ideally, you should provide an application that reproduces the error or a test case to Devise's suite.
This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/).
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](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): 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.
* [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 not been active 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.
## 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/plataformatec/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:
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:
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 three resources that should help you get started:
* Michael Hartl's online book: https://www.railstutorial.org/book/modeling_users
* Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch
* Codecademy's Ruby on Rails: Authentication and Authorization: http://www.codecademy.com/en/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. :smiley:
## Getting started
Devise 4.0 works with Rails 4.2 onwards. You can add it to your Gemfile with:
```ruby
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:
```console
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:
```console
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 the 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`:
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'):
```ruby
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:
```ruby
user_signed_in?
```
For the current signed-in user, this helper is available:
```ruby
current_user
```
You can access the session for this scope:
```ruby
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:
```ruby
rootto:"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:
```ruby
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:
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

*For previous Devise versions see https://github.com/plataformatec/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 filter in your `ApplicationController`:
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
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:
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:
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:
```console
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:
```console
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.
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:
```ruby
class Users::SessionsController < Devise::SessionsController
def create
# custom sign-in code
end
end
```
Or you can simply add new behaviour to it:
```ruby
class Users::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 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:
Be sure to check `devise_for` [documentation](http://www.rubydoc.info/github/plataformatec/devise/master/ActionDispatch/Routing/Mapper%3Adevise_for) 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 a `devise_scope` block in the router:
```ruby
devise_scope :user do
get "sign_in", to: "devise/sessions#new"
end
```
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.
### I18n
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:
```yaml
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:
```yaml
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:
```yaml
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/plataformatec/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.
### 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 (make sure you place it out of scope of `ActiveSupport::TestCase` which is the default class inside of `test/test_helper.rb`):
```ruby
class ActionController::TestCase
include Devise::TestHelpers
end
```
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):
Just be sure that this inclusion is made *after* the `require 'rspec/rails'` directive.
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 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. It is undesirable even to include `Devise::TestHelpers` during integration tests. 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:
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`:
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:
```ruby
# Create a migration with the required fields
create_table :admins do |t|
t.string :email
t.string :encrypted_password
t.timestamps null: false
end
# Inside your Admin model
devise :database_authenticatable, :timeoutable
# Inside your routes
devise_for :admins
# Inside your protected controller
before_action :authenticate_admin!
# Inside your controllers and views
admin_signed_in?
current_admin
admin_session
```
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.
If you enable the [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/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`:
```ruby
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
### Heroku
Using Devise on Heroku with Ruby on Rails 3.2 requires setting:
```ruby
config.assets.initialize_on_precompile = false
```
Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html
### Warden
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/hassox/warden
### Contributors
We have a long list of valued contributors. Check them all at:
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.
It's composed of 12 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.
* Token Authenticatable: signs in a 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, 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 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.
* Encryptable: adds support of other authentication mechanisms besides the built-in Bcrypt (the default).
== 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:
http://wiki.github.com/plataformatec/devise
=== 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 found a security bug, do *NOT* use the GitHub issue tracker. Send email or a private GitHub message to the maintainers listed at the bottom of the README.
=== Mailing list
If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker:
If you need to use Devise with Rails 2.3, 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:
You will usually want to write tests for your changes. To run the test suite, `cd` 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 1.6 or newer) running on your system.
== Installation
You can use the latest Rails 3 gem with the latest Devise gem:
gem install devise
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 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:
rails generate devise MODEL
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 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, continue reading this file to understand exactly what the generator produces and how to use it.
Support for Rails 2.3.x can be found by installing Devise 1.0.x from the v1.0 branch.
== Starting with Rails?
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:
* 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
Once you have solidified you understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :)
== Getting started
This is a walkthrough with all steps you need to setup a devise resource, including model, migration, route files, and optional configuration.
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:
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|
t.database_authenticatable
t.confirmable
t.recoverable
t.rememberable
t.trackable
t.timestamps
end
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`). If you invoked the devise generator, you noticed that this is exactly what the generator produces for us: model, routes and migrations.
Don't forget to run rake db:migrate 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:
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. 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#index"
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:
Notice that if your devise model is not called "user" but "member", then the helpers you should use are:
before_filter :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 which encryptor to use in database_authenticatable:
Besides :stretches, you can define :pepper, :encryptor, :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 multiple models
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:
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
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". You can also use the generator to generate scoped views:
rails generate devise:views users
=== 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
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.
=== 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:
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"
end
This way you tell devise to use the scope :user when "/sign_in" is accessed. Notice +devise_scope+ is also aliased as +as+ and you can also give a block to +devise_for+, resulting in the same behavior:
devise_for :users do
get "sign_in", :to => "devise/sessions#new"
end
Feel free to choose the one you prefer!
=== I18n
Devise uses flash messages with I18n 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:
http://github.com/plataformatec/devise/wiki/I18n
=== 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 file:
class ActionController::TestCase
include Devise::TestHelpers
end
If you're using RSpec and want the helpers automatically included within all +describe+ blocks, add a file called spec/support/devise.rb with the following contents:
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 (http://wiki.github.com/plataformatec/devise).
=== Omniauth
Devise comes with Omniauth support out of the box to authenticate from other providers. You can read more about Omniauth support in the wiki:
Devise supports ActiveRecord (default) and Mongoid. To choose other ORM, you just need to require it in the initializer file.
=== Migrating from other solutions
Devise implements encryption strategies for Clearance, Authlogic and Restful-Authentication. To make use of these strategies, you need set the desired encryptor in the encryptor initializer config option and add :encryptable to your model. You might also need to rename your encrypted password and salt columns to match Devise's fields (encrypted_password and password_salt).
== Additional information
=== Warden
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:
http://github.com/hassox/warden
=== Contributors
We have a long list of valued contributors. Check them all at:
# Additional translations at http://github.com/plataformatec/devise/wiki/I18n
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
en:
devise:
confirmations:
confirmed:"Your email address has been successfully confirmed."
send_instructions:"You will receive an email with instructions for how to confirm your email address in a few minutes."
send_paranoid_instructions:"If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
failure:
already_authenticated:"You are already signed in."
inactive:"Your account is not activated yet."
invalid:"Invalid %{authentication_keys} or password."
locked:"Your account is locked."
last_attempt:"You have one more attempt before your account is locked."
not_found_in_database:"Invalid %{authentication_keys} or password."
timeout:"Your session expired. Please sign in again to continue."
unauthenticated:"You need to sign in or sign up before continuing."
unconfirmed:"You have to confirm your email address before continuing."
mailer:
confirmation_instructions:
subject:"Confirmation instructions"
reset_password_instructions:
subject:"Reset password instructions"
unlock_instructions:
subject:"Unlock instructions"
password_change:
subject:"Password Changed"
omniauth_callbacks:
failure:"Could not authenticate you from %{kind} because \"%{reason}\"."
success:"Successfully authenticated from %{kind} account."
passwords:
no_token:"You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
send_instructions:"You will receive an email with instructions on how to reset your password in a few minutes."
send_paranoid_instructions:"If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
updated:"Your password has been changed successfully. You are now signed in."
updated_not_active:"Your password has been changed successfully."
registrations:
destroyed:"Bye! Your account has been successfully cancelled. We hope to see you again soon."
signed_up:"Welcome! You have signed up successfully."
signed_up_but_inactive:"You have signed up successfully. However, we could not sign you in because your account is not yet activated."
signed_up_but_locked:"You have signed up successfully. However, we could not sign you in because your account is locked."
signed_up_but_unconfirmed:"A message with a confirmation link has been sent to your email address. Please follow the link to activate your account."
update_needs_confirmation:"You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address."
updated:"Your account has been updated successfully."
sessions:
signed_in:"Signed in successfully."
signed_out:"Signed out successfully."
already_signed_out:"Signed out successfully."
unlocks:
send_instructions:"You will receive an email with instructions for how to unlock your account in a few minutes."
send_paranoid_instructions:"If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
unlocked:"Your account has been unlocked successfully. Please sign in to continue."
# Parse authentication keys considering if they should be enforced or not.
defparse_authentication_key_values(hash,keys)
keys.eachdo|key,enforce|
value=hash[key].presence
@@ -162,4 +173,4 @@ module Devise
end
end
end
end
end
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.