Addresses #4599
The docs previously mentioned that authentication hooks are not run when `signed_in?` is called, when in fact they are. This commit fixes the comment and suggests calling `authenticated?` on warden directly as an alternative for when you _don't_ want to run auth hooks.
* Change the way to detect ActiveRecord vs Mongoid
Cause of **mongoid-paperclip** declaring *after_commit* callback while **mongoid** (and MongoDB) does not support it.
* Update test for ActiveRecord presence to handle Mongoid/ActiveRecord project
This fairly straightforward refactor extracts the most obtuse
portions of store_location_for into the following discrete
private methods:
- extract_path_from_location
- remove_domain_from_uri
- add_fragment_back_to_path
This may seem like indirection but it was very unclear what
operation was being performed on the location sent to
store_location_for prior to this change.
I considered documenting the behavior but the code seemed
like a prime candidate for method extraction.
The test uses `as_json` instead of `to_json` because `to_json` does `#dup` on `options` before it reaches `#serializable_hash` and the test would pass without the fix.
* Fix missing validations on Signup
This commit fixes issue
https://github.com/plataformatec/devise/issues/4673
This removes `validate: false` from saving a record when `Trackable` is
in use.
* Add test case
* Add mongoid model
Active Record changed it's public API, so we should check against its
version instead of Rails as it is possible to use Rails 5.1 with Mongoid,
which still has the older Dirty API.
However, this patch does not fixes a scenario where an app has both
Active Record and Mongoid loaded. It should be fixed by either normalizing
the Mongoid/ActiveRecord API or replacing the conditional method
definitions with a shim layer that abstracts this away.
Rails 5.1 has deprecated render :text, and HEAD requests on the
omniauth callbacks passthru method is causing errors because the render
:text is non-existant, and there's no template to fall back to.
Replacing :text with :plain, adds a content-type type of text/plain and
also returns the previous message.
render :plain was supported back in rails 4.1.0
http://api.rubyonrails.org/v4.1.0/classes/ActionView/Helpers/RenderingHelper.html#method-i-render
Otherwise we'd be mistakenly displaying the original email in the
message (which is the same we're sending the message to).
Also tweak the messaging a bit in this case, to show that the email "is
being changed" (the change hasn't taken effect yet).
Related to #4455.
Related to issue #4397
This hotfix adds a string coercion to new_password paramenters when
trying to reset an user's password.
Before that, when a user submitted a password recovery form with the
new_password and new_password_confirmation params as nil, Devise would
sign in the user with a success notice but without actually changing the
password.
This better indicates what the setting is for, and when it's supposed to
be triggered.
We might eventually deprecate the existing password_change on in favor
of password_changed.
This adds a new setting `send_email_change_notification` which will
send an email to the original user email when their email is updated to
a new one.
It doesn't take into account the reconfirmable setting yet, it will be
added next, so that if confirmable is included and reconfirmable is
being used, the email will be triggered when the email change is
requested, not when confirmed (e.g when we store the email in
`unconfirmed_email`, not when it's later copied to `email` when that is
confirmed).
in the test we need to declare a subclass of ``Devise::Mailer`` to give
a block to mail call inside of method which has a corresponding view
template
there are propably better ways to test this, but this is pretty much the
use case for passing a block
ActionMailer's ``mail`` method may receive a block for customizing the mails
format
``devise_mail`` now has the same functionality by just
passing the block to ``mail`` call.
fixesplataformatec/devise#2341
This change is required to better support scenarios where records don't have
an `encrypted_password` column and the password is managed elsewhere (LDAP, for instance).
The move from `email_changed?` to loop through the `authentication_keys` is also
useful to support edge cases where users can authenticate with different attributes
besides their email.
Closes#3624.
Fast finish triggers multiple Slack notification and floods our OSS slack room,
and it is a known bug for a while.
Reference: travis-ci/travis-ci/issues/1696
* Add Devise::FailureApp#{relative_url_root, relative_url_root?}
Also support missing action_controller.relative_url_root configuration.
* Dry assignment of relative_url_root
Also this commit adds support for
Rails.application.config.action_controller.relative_url_root
Previously, a `NoMethodError` exception would be raised from here when the
middleware stack isn't present and Warden wasn't injected as expected
(like in a controller test). To foolproof ourselves, we now raise a more
informative error when `request.env['warden']` is `nil` so developers can
figure this out on their own instead of reaching to the issue tracker for
guidance.
The sign_in method permits the bypass option
that ignore the others options used. This behavior
has lead some users to a misconfusion what the
method really does.
This change deprecate the bypass option in favor
of a method that only does the sign in with bypass.
Closes#3981
The suggested omniauth path noted in the CHANGELOG.md under 4.0.0.rc2
did not work. It was missing an `_omniauth` in the middle of the
method name.
user_github_authorize_path => user_github_omniauth_authorize_path
Call send_on_create_confirmation_instructions in after_commit instead of after_create, I think this is no harm in general and it makes things like async job work.
Fix#4062
Set the new defaults for Devise 4.1
In our configuration template we explicit set some configurations as recommended defaults.
Now we are enforcing these configurations to be the defaults.
It also removes all warning code about this change.
The first value returned by token_generator.generate is
simply the return value of friendly_token so this code should
be equivalent.
The use of token_generator here dates back to when the
confirmation_token was stored as a digest, but that is no
longer true.
This removes an upgrade path that migrated the old serialization format
to the new one introduced. This was introduced in c22d755 (#2300)
3 years ago and should no longer be needed.
As has been seen in a previous pull request, some applications require
routes to be loaded before the code is eagerly loaded, which implies
that all Rails applications using Devise need to have routes reloaded
twice:
https://github.com/plataformatec/devise/pull/3241
This can incur a very significant slowdown for large apps that have a
lot of routes or a lot of controllers, so reloading should be optional.
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.
* Ensure Gemspec is loaded as utf-8. (by @segiddins)
* Fix `ActiveRecord` check on `Confirmable`. (by @tegon)
* Fix `signed_in?` docs without running auth hooks. by (@machty)
### 4.4.0 - 2017-12-29
* enhancements
* Add `frozen_string_literal` pragma comment to all Ruby files. (by @pat)
* Use `set_flash_method!` instead of `set_flash_method` in `Devise::OmniauthCallbacksController#failure`. (by @saichander17)
* Clarify how `store_location_for` modifies URIs. (by @olivierlacan)
* Move `failed_attempts` increment into its own function. by (@mobilutz)
* Add `autocomplete="email"` to email fields. by (@MikeRogers0)
* Add the ability to change the default migrations path introduced in Rails 5.0.3. (by @alexhifer)
* Delete unnecessary condition for helper method. (by @davydovanton)
* Support `id: :uuid` option for migrations. (by @filip373)
* bug fixes
* Fix syntax for MRI 2.5.0. (by @pat)
* Validations were being ignored on singup in the `Trackable#update_tracked_fields!` method. (by @AshleyFoster)
* Do not modify options for `#serializable_hash`. (by @guigs)
* Email confirmations were being sent on sign in/sign out for application using `mongoid` and `mongoid-paperclip` gems. This is because previously we were checking if a model is from Active Record by checking if the method `after_commit` was defined - since `mongoid` doesn' have one - but `mongoid-paperclip` gem does define one, which cause this issue. (by @fjg)
### 4.3.0 - 2017-05-14
* Enhancements
* Dependency support added for Rails 5.1.x.
### 4.2.1 - 2017-03-15
* removals
*`Devise::Mailer#scope_name` and `Devise::Mailer#resource` are now protected
methods instead of public.
* bug fixes
* Attempt to reset password without the password field in the request now results in a `:blank` validation error.
Before this change, Devise would accept the reset password request and log the user in, without validating/changing
the password. (by @victor-am)
* Confirmation links now expire based on UTC time, working properly when using different timezones. (by @jjuliano)
* enhancements
* Notify the original email when it is changed with a new `Devise.send_email_changed_notification` setting.
When using `reconfirmable`, the notification will be sent right away instead of when the unconfirmed email is confirmed.
(original change by @ethirajsrinivasan)
### 4.2.0 - 2016-07-01
* removals
* Remove the deprecated `Devise::ParameterSanitizer` API from Devise 3.
Please use the `#permit` and `#sanitize` methods over `#for`.
* Remove the deprecated OmniAuth URL helpers. Use the fully qualified helpers
(`user_facebook_omniauth_authorize_path`) over the scope based helpers
( `user_omniauth_authorize_path(:facebook)`).
* Remove the `Devise.bcrypt` method, use `Devise::Encryptor.digest` instead.
* Remove the `Devise::Models::Confirmable#confirm!` method, use `confirm` instead.
* Remove the `Devise::Models::Recoverable#reset_password!` method, use `reset_password` instead.
* Remove the `Devise::Models::Recoverable#after_password_reset` method.
* bug fixes
* Fix an `ActionDispatch::IllegalStateError` when testing controllers with Rails 5 rc 2(by @hamadata).
* Use `ActiveSupport.on_load` hooks to include Devise on `ActiveRecord` and `Mongoid`,
avoiding autoloading these constants too soon (by @lucasmazza, @rafaelfranca).
* enhancements
* Display the minimum password length on `registrations/edit` view (by @Yanchek99).
* You can disable Devise's routes reloading on boot by through the `reload_routes = false` config.
This can reduce the time taken to boot the application but it might trigger
some errors if you application (mostly your controllers) requires that
Devise mappings be loaded during boot time (by @sidonath).
* Added `Devise::Test::IntegrationHelpers` to bypass the sign in process using
Warden test API (by @lucasmazza).
* Define `inspect` in `Devise::Models::Authenticatable` to help ensure password hashes
aren't included in exceptions or otherwise accidentally serialized (by @tkrajcar).
* Add missing support of `Rails.application.config.action_controller.relative_url_root` (by @kosdiamantis).
* deprecations
*`Devise::TestHelpers` is deprecated in favor of `Devise::Test::ControllerHelpers`
(by @lucasmazza).
* The `sign_in` test helper has changed to use keyword arguments when passing
a scope. `sign_in :admin, users(:alice)` should be rewritten as
* The option `bypass` of `Devise::Controllers::SignInOut#sign_in` method is
deprecated in favor of `Devise::Controllers::SignInOut#bypass_sign_in`
method (by @ulissesalmeida).
### 4.1.1 - 2016-05-15
* bug fixes
* Fix overwriting the remember_token when a valid one already exists (by @ralinchimev).
### 4.1.0
* bug fixes
* Fix race condition of sending the confirmation instructions e-mail using background jobs.
Using the previous `after_create` callback, the e-mail can be sent before
the record be committed on database, generating a `ActiveRecord::NotFound` error.
Now the confirmation e-mail will be only sent after the database commit,
using the `after_commit` callback.
It may break your test suite on Rails 4 if you are testing the sent e-mails
or enqueued jobs using transactional fixtures enabled or `DatabaseCleaner` with `transaction` strategy.
You can easily fix your test suite using the gem
[test_after_commit](https://github.com/grosser/test_after_commit). For example, put in your Gemfile:
```ruby
gem 'test_after_commit', :group => :test
```
On Rails 5 `after_commit` callbacks are triggered even using transactional
fixtures, then this fix will not break your test suite. If you are using `DatabaseCleaner` with the `deletion` or `truncation` strategies it may not break your tests. (by @allenwq)
* Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` and
`:undefined` strategies. (by @f3ndot)
* features
* Humanize authentication keys in failure flash message (by @byzg)
When you are configuring the translations of `devise.failure.invalid`, the
`authentication_keys` is translated now.
* deprecations
* Remove code supporting old session serialization format (by @fphilipe).
* Now the `email_regexp` default uses a more permissive regex:
`/\A[^@\s]+@[^@\s]+\z/` (by @kimgb)
* Now the `strip_whitespace_keys` default is `[:email]` (by @ulissesalmeida)
* Now the `reconfirmable` default is `true` (by @ulissesalmeida)
* Now the `skip_session_storage` default is `[:http_auth]` (by @ulissesalmeida)
* Now the `sign_out_via` default is `:delete` (by @ulissesalmeida)
* improvements
* Avoids extra computation of friendly token for confirmation token (by @sbc100)
### 4.0.3 - 2016-05-15
* bug fixes
* Fix overwriting the remember_token when a valid one already exists (by @ralinchimev).
### 4.0.2 - 2016-05-02
* bug fixes
* Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none`
and `:undefined` strategies. (by @f3ndot)
### 4.0.1 - 2016-04-25
* bug fixes
* Fix the e-mail confirmation instructions send when a user updates the email
* 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_omniauth_authorize_path`.
You can still use `omniauth_authorize_path(:user, :github)` if you need to
call the helpers dynamically.
### 4.0.0.rc1 - 2016-02-01
* 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`:
* Hide Devise's internal generators from `rails g` command
* bug fix
* Removed tmp and log files from gem
== 2.0.0
* enhancements
* Add support for e-mail reconfirmation on change (by @Mandaryn and @heimidal)
* Redirect users to sign in page after unlock (by @nashby)
* Redirect to the previous URL on timeout
* Inherit from the same Devise parent controller (by @sj26)
* Allow parent_controller to be customizable via Devise.parent_controller, useful for engines
* Allow router_name to be customizable via Devise.router_name, useful for engines
* Allow alternate ORMs to run compatibility setup code before Authenticatable is included (by @jm81)
* deprecation
* Devise now only supports Rails 3.1 forward
* Devise.confirm_within was deprecated in favor Devise.allow_unconfirmed_access_for
* Devise.stateless_token= is deprecated in favor of appending :token_auth to Devise.skip_session_storage
* Usage of Devise.apply_schema is deprecated
* Usage of Devise migration helpers are deprecated
* Usage of Devise.remember_across_browsers was deprecated
* Usage of rememberable with remember_token was removed
* Usage of recoverable without reset_password_sent_at was removed
* Usage of Devise.case_insensitive_keys equals to false was removed
* Move devise/shared/_links.erb to devise/_links.erb
* Deprecated support of nested devise_for blocks
* Deprecated support to devise.registrations.reasons and devise.registrations.inactive_signed_up in favor of devise.registrations.signed_up_but_*
== 1.5.3
* bug fix
* Ensure delegator converts scope to symbol (by @dmitriy-kiriyenko)
* Ensure passing :format => false to devise_for is not permanent
* Ensure path checker does not check invalid routes
== 1.5.2
* enhancements
* Add support for Rails 3.1 new mass assignment conventions (by @kirs)
* Add timeout_in method to Timeoutable, it can be overridden in a model (by @lest)
* bug fix
* OmniAuth error message now shows the proper option (:strategy_class instead of :klass)
== 1.5.1
* bug fix
* Devise should not attempt to load OmniAuth strategies. Strategies should be loaded before hand by the developer or explicitly given to Devise.
== 1.5.0
* enhancements
* Timeoutable also skips tracking if skip_trackable is given
* devise_for now accepts :failure_app as an option
* Models can select the proper mailer via devise_mailer method (by @locomotivecms)
* Migration generator now uses the change method (by @nashby)
* Support to markerb templates on the mailer generator (by @sbounmy)
* Support for Omniauth 1.0 (older versions are no longer supported) (by @TamiasSibiricus)
* bug fix
* Allow idempotent API requests
* Fix bug where logs did not show 401 as status code
* Change paranoid settings to behave as success instead of as failure
* Fix bug where activation messages were shown first than the credentials error message
* Instance variables are expired after sign out
* deprecation
* redirect_location is deprecated, please use after_sign_in_path_for
* after_sign_in_path_for now redirects to session[scope_return_to] if any value is stored in it
== 1.4.9
* bug fix
* url helpers were not being set under some circumstances
== 1.4.8
* enhancements
* Add docs for assets pipeline and Heroku
* bug fix
* confirmation_url was not being set under some circumstances
== 1.4.7
* bug fix
* Fix backward incompatible change from 1.4.6 for those using custom controllers
== 1.4.6
* enhancements
* Allow devise_for :skip => :all
* Allow options to be passed to authenticate_user!
* Allow --skip-routes to devise generator
* Add allow_params_authentication! to make it explicit when params authentication is allowed in a controller
== 1.4.5
* bug fix
* Failure app tries the root path if a session one does not exist
* No need to finalize Devise helpers all the time (by @bradleypriest)
* Reset password shows proper message if user is not active
* `clean_up_passwords` sets the accessors to nil to skip validations
== 1.4.4
* bug fix
* Do not always skip helpers, instead provide :skip_helpers as option to trigger it manually
== 1.4.3
* enhancements
* Improve Rails 3.1 compatibility
* Use serialize_into_session and serialize_from_session in Warden serialize to improve extensibility
* bug fix
* Generator properly generates a change_table migration if a model already exists
* Properly deprecate setup_mail
* Fix encoding issues with email regexp
* Only generate helpers for the used mappings
* Wrap :action constraints in the proper hash
* deprecations
* Loosened the used email regexp to simply assert the existent of "@". If someone relies on a more strict regexp, they may use https://github.com/SixArm/sixarm_ruby_email_address_validation
== 1.4.2
* bug fix
* Provide a more robust behavior to serializers and add :force_except option
== 1.4.1
* enhancements
* Add :defaults and :format support on router
* Add simple form generators
* Better localization for devise_error_messages! (by @zedtux)
* bug fix
* Ensure to_xml is properly white listened
* Ensure handle_unverified_request clean up any cached signed-in user
== 1.4.0
* enhancements
* Added authenticated and unauthenticated to the router to route the used based on his status (by @sj26)
* Improve e-mail regexp (by @rodrigoflores)
* Add strip_whitespace_keys and default to e-mail (by @swrobel)
* Do not run format and uniqueness validations on e-mail if it hasn't changed (by @Thibaut)
* Added update_without_password to update models but not allowing the password to change (by @fschwahn)
* Added config.paranoid, check the generator for more information (by @rodrigoflores)
* bug fix
* password_required? should not affect length validation
* User cannot access sign up and similar pages if he is already signed in through a cookie or token
* Do not convert booleans to strings on finders (by @xavier)
* Run validations even if current_password fails (by @crx)
* Devise now honors routes constraints (by @macmartine)
* Do not return the user resource when requesting instructions (by @rodrigoflores)
== 1.3.4
* bug fix
* Do not add formats if html or "*/*"
== 1.3.3
* bug fix
* Explicitly mark the token as expired if so
== 1.3.2
* bug fix
* Fix another regression related to reset_password_sent_at (by @alexdreher)
== 1.3.1
* enhancements
* Improve failure_app responses (by @indirect)
* 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 @stevehodgkiss)
== 1.3.0
* enhancements
* All controllers can now handle different mime types than html using Responders (by @sikachu)
* Added reset_password_within as configuration option to send the token for recovery (by @jdguyot)
* Bump password length to 128 characters (by @k33l0r)
* Add :only as option to devise_for (by @timoschilling)
* Allow to override path after sending password instructions (by @irohiroki)
* require_no_authentication has its own flash message (by @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 @jwilger)
* valid_password? should not choke on empty passwords (by @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 @andmej)
* before_failure callbacks should work on test helpers (by @twinge)
* rememberable cookie now is httponly by default (by @JamesFerguson)
* Add missing confirmation_keys (by @JohnPlummer)
* 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 @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 @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 @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 @martinrehfeld)
* Improved Ajax requests handling in failure app (by @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 @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 @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 @sgronblo)
* Allow password recovery and account unlocking to change used keys (by @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 @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 @fredwu)
* Check the type of HTTP Authentication before using Basic headers
* Avoid invalid_salt errors by checking salt presence (by @thibaudgg)
* Forget user deletes the right cookie before logout, not remembering the user anymore (by @emtrane)
* Fix for failed first-ever logins on PostgreSQL where column default is nil (by @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 @trevorturk)
* Rememberable module allows you to activate the period the remember me token is extended (by @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 @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 @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 @mantas)
* Added navigational formats to specify when it should return a 302 and when a 401.
* Added authenticate(scope) support in routes (by @wildchild)
* Added after_update_path_for to registrations controller (by @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
== 1.0.8
* enhancements
* Support for latest MongoMapper
* Added anybody_signed_in? helper (by @SSDany)
* bug fix
* confirmation_required? is properly honored on active? calls. (by @paulrosania)
== 1.0.7
* bug fix
* Ensure password confirmation is always required
* deprecations
* authenticatable was deprecated and renamed to database_authenticatable
* confirmable is not included by default on generation
== 1.0.6
* bug fix
* Do not allow unlockable strategies based on time to access a controller.
* Do not send unlockable email several times.
* Allow controller to upstram custom! failures to Warden.
== 1.0.5
* bug fix
* Use prepend_before_filter in require_no_authentication.
* require_no_authentication on unlockable.
* Fix a bug when giving an association proxy to devise.
* Do not use lock! on lockable since it's part of ActiveRecord API.
== 1.0.4
* bug fix
* Fixed a bug when deleting an account with rememberable
* Fixed a bug with custom controllers
== 1.0.3
* enhancements
* HTML e-mails now have proper formatting
* Do not remove MongoMapper options in find
== 1.0.2
* enhancements
* Allows you set mailer content type (by @glennr)
* bug fix
* Uses the same content type as request on http authenticatable 401 responses
== 1.0.1
* enhancements
* HttpAuthenticatable is not added by default automatically.
* Avoid mass assignment error messages with current password.
* bug fix
* Fixed encryptors autoload
== 1.0.0
* deprecation
* :old_password in update_with_password is deprecated, use :current_password instead
* enhancements
* Added Registerable
* Added Http Basic Authentication support
* Allow scoped_views to be customized per controller/mailer class
* [#99] Allow authenticatable to used in change_table statements
== 0.9.2
* bug fix
* Ensure inactive user cannot sign in
* Ensure redirect to proper url after sign up
* enhancements
* Added gemspec to repo
* Added token authenticatable (by @grimen)
== 0.9.1
* bug fix
* Allow bigger salt size (by @jgeiger)
* Fix relative url root
== 0.9.0
* deprecation
* devise :all is deprecated
* :success and :failure flash messages are now :notice and :alert
* enhancements
* Added devise lockable (by @mhfs)
* Warden 0.9.0 compatibility
* Mongomapper 0.6.10 compatibility
* Added Devise.add_module as hooks for extensions (by @grimen)
* Ruby 1.9.1 compatibility (by @grimen)
* bug fix
* Accept path prefix not starting with slash
* url helpers should rely on find_scope!
== 0.8.2
* enhancements
* Allow Devise.mailer_sender to be a proc (by @grimen)
* bug fix
* Fix bug with passenger, update is required to anyone deploying on passenger (by @dvdpalm)
== 0.8.1
* enhancements
* Move salt to encryptors
* Devise::Lockable
* Moved view links into partial and I18n'ed them
* bug fix
* Bcrypt generator was not being loaded neither setting the proper salt
== 0.8.0
* enhancements
* Warden 0.8.0 compatibility
* Add an easy for map.connect "sign_in", :controller => "sessions", :action => "new" to work
* Added :bcrypt encryptor (by @capotej)
* bug fix
* sign_in_count is also increased when user signs in via password change, confirmation, etc..
* More DataMapper compatibility (by @lancecarlson)
* deprecation
* Removed DeviseMailer.sender
== 0.7.5
* enhancements
* Set a default value for mailer to avoid find_template issues
* Add models configuration to MongoMapper::EmbeddedDocument as well
== 0.7.4
* enhancements
* Extract Activatable from Confirmable
* Decouple Serializers from Devise modules
== 0.7.3
* bug fix
* Give scope to the proper model validation
* enhancements
* Mail views are scoped as well
* Added update_with_password for authenticatable
* Allow render_with_scope to accept :controller option
== 0.7.2
* deprecation
* Renamed reset_confirmation! to resend_confirmation!
* Copying locale is part of the installation process
* bug fix
* Fixed render_with_scope to work with all controllers
* Allow sign in with two different users in Devise::TestHelpers
== 0.7.1
* enhancements
* Small enhancements for other plugins compatibility (by @grimen)
== 0.7.0
* deprecations
* :authenticatable is not included by default anymore
* enhancements
* Improve loading process
* Extract SessionSerializer from Authenticatable
== 0.6.3
* bug fix
* Added trackable to migrations
* Allow inflections to work
== 0.6.2
* enhancements
* More DataMapper compatibility
* Devise::Trackable - track sign in count, timestamps and ips
== 0.6.1
* enhancements
* Devise::Timeoutable - timeout sessions without activity
* DataMapper now accepts conditions
== 0.6.0
* deprecations
* :authenticatable is still included by default, but yields a deprecation warning
* enhancements
* Added DataMapper support
* Remove store_location from authenticatable strategy and add it to failure app
* Allow a strategy to be placed after authenticatable
* [#45] Do not rely attribute? methods, since they are not added on Datamapper
== 0.5.6
* enhancements
* [#42] Do not send nil to build (DataMapper compatibility)
* [#44] Allow to have scoped views
== 0.5.5
* enhancements
* Allow overwriting find for authentication method
* [#38] Remove Ruby 1.8.7 dependency
== 0.5.4
* deprecations
* Deprecate :singular in devise_for and use :scope instead
* enhancements
* [#37] Create after_sign_in_path_for and after_sign_out_path_for hooks to be
overwriten in ApplicationController
* Create sign_in_and_redirect and sign_out_and_redirect helpers
* Warden::Manager.default_scope is automatically configured to the first given scope
== 0.5.3
* bug fix
* MongoMapper now converts DateTime to Time
* Ensure all controllers are unloadable
* enhancements
* [#35] Moved friendly_token to Devise
* Added Devise.all, so you can freeze your app strategies
* Added Devise.apply_schema, so you can turn it to false in Datamapper or MongoMapper
in cases you don't want it be handlded automatically
== 0.5.2
* enhancements
* [#28] Improved sign_in and sign_out helpers to accepts resources
* [#28] Added stored_location_for as a helper
* [#20] Added test helpers
== 0.5.1
* enhancements
* Added serializers based on Warden ones
* Allow authentication keys to be set
== 0.5.0
* bug fix
* Fixed a bug where remember me module was not working properly
* enhancements
* Moved encryption strategy into the Encryptors module to allow several algorithms (by @mhfs)
* Implemented encryptors for Clearance, Authlogic and Restful-Authentication (by @mhfs)
* Added support for MongoMapper (by @shingara)
== 0.4.3
* bug fix
* [#29] Authentication just fails if user cannot be serialized from session, without raising errors;
* Default configuration values should not overwrite user values;
== 0.4.2
* deprecations
* Renamed mail_sender to mailer_sender
* enhancements
* skip_before_filter added in Devise controllers
* Use home_or_root_path on require_no_authentication as well
* Added devise_controller?, useful to select or reject filters in ApplicationController
* Allow :path_prefix to be given to devise_for
* Allow default_url_options to be configured through devise (:path_prefix => "/:locale" is now supported)
== 0.4.1
* bug fix
* [#21] Ensure options can be set even if models were not loaded
== 0.4.0
* deprecations
* Notifier is deprecated, use DeviseMailer instead. Remember to rename
app/views/notifier to app/views/devise_mailer and I18n key from
devise.notifier to devise.mailer
* :authenticable calls are deprecated, use :authenticatable instead
* enhancements
* [#16] Allow devise to be more agnostic and do not require ActiveRecord to be loaded
* Allow Warden::Manager to be configured through Devise
* Created a generator which creates an initializer
== 0.3.0
* bug fix
* [#15] Allow yml messages to be configured by not using engine locales
* deprecations
* Renamed confirm_in to confirm_within
* [#14] Do not send confirmation messages when user changes his e-mail
* [#13] Renamed authenticable to authenticatable and added deprecation warnings
== 0.2.3
* enhancements
* Ensure fail! works inside strategies
* [#12] Make unauthenticated message (when you haven't signed in) different from invalid message
* bug fix
* Do not redirect on invalid authenticate
* Allow model configuration to be set to nil
== 0.2.2
* bug fix
* [#9] Fix a bug when using customized resources
== 0.2.1
* refactor
* Clean devise_views generator to use devise existing views
* enhancements
* [#7] Create instance variables (like @user) for each devise controller
* Use Devise::Controller::Helpers only internally
* bug fix
* [#6] Fix a bug with Mongrel and Ruby 1.8.6
== 0.2.0
* enhancements
* [#4] Allow option :null => true in authenticable migration
* [#3] Remove attr_accessible calls from devise modules
* Customizable time frame for rememberable with :remember_for config
* Customizable time frame for confirmable with :confirm_in config
* Generators for creating a resource and copy views
* optimize
* Do not load hooks or strategies if they are not used
* bug fixes
* [#2] Fixed requiring devise strategies
== 0.1.1
* bug fixes
* [#1] Fixed requiring devise mapping
== 0.1.0
* Devise::Authenticable
* Devise::Confirmable
* Devise::Recoverable
* Devise::Validatable
* Devise::Migratable
* Devise::Rememberable
* SessionsController
* PasswordsController
* ConfirmationsController
* Create an example app
* devise :all, :except => :rememberable
* Use sign_in and sign_out in SessionsController
* Mailer subjects namespaced by model
* Allow stretches and pepper per model
* Store session[:return_to] in session
* Sign user in automatically after confirming or changing it's password
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/)
Avoid opening new issues to ask questions in our issues tracker. Please go through
the project wiki, documentation and source code first, or try to ask your question
on [Stack Overflow](http://stackoverflow.com/questions/tagged/devise).
**If you find a security bug, do not report it through GitHub. Please send an
e-mail to [opensource@plataformatec.com.br](mailto:opensource@plataformatec.com.br)
instead.**
## Sending Pull Requests
Before sending a new Pull Request, take a look on existing Pull Requests and Issues
to see if the proposed change or fix has been discussed in the past, or if the
change was already implemented but not yet released.
We expect new Pull Requests to include enough tests for new or changed behavior,
and we aim to maintain everything as most backwards compatible as possible,
reserving breaking changes to be ship in major releases when necessary - you
can wrap the new code path with a setting toggle from the `Devise` module defined
as `false` by default to require developers to opt-in for the new behavior.
If your Pull Request includes new or changed behavior, be sure that the changes
are beneficial to a wide range of use cases or it's an application specific change
that might not be so valuable to other applications. Some changes can be introduced
as a new `devise-something` gem instead of belonging to the main codebase.
When adding new settings, you can take advantage of the [`Devise::Models.config`](https://github.com/plataformatec/devise/blob/245b1f9de0b3386b7913e14b60ea24f43b77feb0/lib/devise/models.rb#L13-L50) method to add class and instance level fallbacks
to the new setting.
We also welcome Pull Requests that improve our existing documentation (both our
`README.md` and the RDoc sections in the source code) or improve existing rough
edges in our API that might be blocking existing integrations or 3rd party gems.
## Other ways to contribute
We welcome anyone that wants to contribute to Devise to triage and reply to
open issues to help troubleshoot and fix existing bugs on Devise. Here is what
you can do:
* Help ensure that existing issues follows the recommendations from the
_[Reporting Issues](#reporting-issues)_ section, providing feeback to the issue's
author on what might be missing.
* Review and update the existing content of our [Wiki](https://github.com/plataformatec/devise/wiki)
with up to date instructions and code samples - the wiki was grown with several
different tutorials and references that we can't keep track of everything, so if
there is a page that showcases an integration or customization that you are
familiar with feel free to update it as necessary.
* Review existing Pull Requests, and testing patches against real existing
applications that use Devise.
Thanks again for your interest on contributing to the project!
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 roles (or models/scopes) signed in at the same time;
* Is based on a modularity concept: use just what you really need.
* 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.
* 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
@@ -34,7 +77,7 @@ It's comprised of 12 modules:
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://wiki.github.com/plataformatec/devise
https://github.com/plataformatec/devise/wiki
### Bug reports
@@ -42,11 +85,15 @@ If you discover a problem with Devise, we would like to know about it. However,
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.
If you have discovered a security related bug, please do *NOT* use the GitHub issue tracker. Send an email to opensource@plataformatec.com.br.
### Mailing list
### StackOverflow and Mailing List
If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker:
If you have any questions, comments, or concerns, please use StackOverflow 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.
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
@@ -80,43 +127,63 @@ You will usually want to write tests for your changes. To run the test suite, g
## 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:
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: http://railstutorial.org/chapters/modeling-and-viewing-users-two#top
* 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. :)
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 2.0 works with Rails 3.1 onwards. You can install it with:
Devise 4.0 works with Rails 4.1 onwards. You can add it to your Gemfile with:
```console
gem install devise
```ruby
gem 'devise'
```
After you install Devise and add it to your Gemfile, you need to run the generator:
Then run `bundle install`
Next, you need to run the generator:
```console
rails generate devise:install
$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:
At this point, a number of instructions will appear in the console. Among these instructions, you'll need to set up the default URL options for the Devise mailer in each environment. Here is a possible configuration for `config/environments/development.rb`:
The generator will install an initializer which describes ALL of Devise's configuration options. It is *imperative* that you take a look at it. When you are done, you are ready to add Devise to any of your models using the generator.
In the following command you will replace `MODEL` with the class name used for the application’s users (it’s frequently `User` but could also be `Admin`). This will create a model (if one does not exist) and configure it with the default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller.
```console
rails generate devise MODEL
$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 "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 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 `rails db:migrate`
You should restart your application after changing Devise's configuration options (this includes stopping spring). Otherwise, you will run into strange errors, for example, users being unable to login and route helpers being undefined.
### Controller filters and helpers
Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_filter:
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_filter:authenticate_user!
before_action:authenticate_user!
```
For Rails 5, note that `protect_from_forgery` is no longer prepended to the `before_action` chain, so if you have set `authenticate_user` before `protect_from_forgery`, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use `protect_from_forgery prepend: true`.
If your devise model is something other than User, replace "_user" with "_yourmodel". The same logic applies to the instructions below.
To verify if a user is signed in, use the following helper:
```ruby
@@ -135,24 +202,18 @@ 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:
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
root:to=>"home#index"
rootto:'home#index'
```
You can also overwrite +after_sign_in_path_for+ and +after_sign_out_path_for+ to customize your redirect hooks.
You can also override `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 called `Member` instead of `User`, for example, then the helpers available are:
Notice that if your devise model is not called "user" but "member", then the helpers you should use are:
```ruby
before_filter:authenticate_member!
before_action:authenticate_member!
member_signed_in?
@@ -163,42 +224,109 @@ 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 encryption algorithm with:
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 and other values. For details, see the initializer file that was created when you invoked the "devise:install" generator described above.
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`.
### Configuring multiple models
### Strong Parameters
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 and timeoutable features. If so, just follow these steps:

*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`:
On the other hand, you can simply run the generator!
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:
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
@@ -207,69 +335,112 @@ We built Devise to help you quickly develop an application that uses authenticat
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
$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".
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:
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
$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.
class Users::SessionsController < Devise::SessionsController
# GET /resource/sign_in
# def new
# super
# end
...
end
```
3) And since we changed the controller, it won't use the "devise/sessions" views, so remember to copy "devise/sessions" to "admin/sessions".
2. Tell the router to use this controller:
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.
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 for details.
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 to create your routes normally and wrap them in a +devise_scope+ block in the router:
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"
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:
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.
Please note: You will still need to add `devise_for` in your routes in order to use helper methods such as `current_user`.
```ruby
devise_for :usersdo
get"sign_in",:to=>"devise/sessions#new"
end
devise_for:users, skip: :all
```
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:
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:
@@ -307,55 +478,181 @@ Take a look at our locale file to check all available messages. You may also be
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 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:
Devise includes some test helpers for controller and integration tests.
In order to use them, you need to include the respective module in your test
cases/specs.
### Controller tests
Controller tests require that you include `Devise::Test::ControllerHelpers` on
your test case or its parent `ActionController::TestCase` superclass.
```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)
```
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:
```ruby
classActionController::TestCase
includeDevise::TestHelpers
class PostsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
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:
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`):
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 (https://wiki.github.com/plataformatec/devise).
Just be sure that this inclusion is made *after* the `require 'rspec/rails'` directive.
### Omniauth
Now you are ready to use the `sign_in` and `sign_out` methods on your controller
tests:
Devise comes with Omniauth support out of the box to authenticate from other providers. You can read more about Omniauth support in the wiki:
```ruby
sign_in @user
sign_in @user, scope: :admin
```
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 controller tests do not pass through the router, it needs to be stated
explicitly. For example, if you are testing the user scope, simply use:
```ruby
test 'GET new' do
# Mimic the router behavior of setting the Devise scope through the env.
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 choose other ORM, you just need to require it in the initializer file.
Devise supports ActiveRecord (default) and Mongoid. To select another ORM, simply 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).
## Troubleshooting
## Additional information
### Heroku
Using devise on Heroku with Ruby on Rails 3.1 requires setting:
Using Devise on Heroku with Ruby on Rails 3.2 requires setting:
Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html
## 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:
# 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"
email_changed:
subject:"Email Changed"
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."
one:"1 error prohibited this %{resource} from being saved:"
other:"%{count} errors prohibited this %{resource} from being saved:"
devise:
failure:
already_authenticated:'You are already signed in.'
unauthenticated:'You need to sign in or sign up before continuing.'
unconfirmed:'You have to confirm your account before continuing.'
locked:'Your account is locked.'
invalid:'Invalid email or password.'
invalid_token:'Invalid authentication token.'
timeout:'Your session expired, please sign in again to continue.'
inactive:'Your account was not activated yet.'
sessions:
signed_in:'Signed in successfully.'
signed_out:'Signed out successfully.'
passwords:
send_instructions:'You will receive an email with instructions about how to reset your password in a few minutes.'
updated:'Your password was changed successfully. You are now signed in.'
updated_not_active:'Your password was changed successfully.'
send_paranoid_instructions:"If your e-mail exists on our database, you will receive a password recovery link on your e-mail"
confirmations:
send_instructions:'You will receive an email with instructions about how to confirm your account in a few minutes.'
send_paranoid_instructions:'If your e-mail exists on our database, you will receive an email with instructions about how to confirm your account in a few minutes.'
confirmed:'Your account was successfully confirmed. You are now signed in.'
registrations:
signed_up:'Welcome! You have signed up successfully.'
signed_up_but_unconfirmed:'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.'
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.'
updated:'You updated your account successfully.'
update_needs_confirmation:"You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
destroyed:'Bye! Your account was successfully cancelled. We hope to see you again soon.'
unlocks:
send_instructions:'You will receive an email with instructions about how to unlock your account in a few minutes.'
unlocked:'Your account has been unlocked successfully. Please sign in to continue.'
send_paranoid_instructions:'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.'
omniauth_callbacks:
success:'Successfully authorized from %{kind} account.'
failure:'Could not authorize you from %{kind} because "%{reason}".'
Rails.logger.debug"[Devise] Trying to deserialize invalid class #{klass}"
nil
else
raise
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.