Given a lot of time has passed since the last v4.x release, and there's
been many changes (including breaking ones) merged to main, let's go
with an "RC" version before doing a final release.
If we don't hear any major issues, I plan to release a final version in
a couple of weeks.
Otherwise if we humanized the whole string, it could cause us to change
the output of strings with periods and maybe other side-effects, since
we're changing the whole string from i18n.
This is safer as it only changes the first char of the translated
message, and only if it is a match with the first translated auth key,
so we can more safely humanize & downcase all auth keys to interpolate
in the message whenever needed.
Also add changelog for the change.
"Invalid Email or password." is grammatically incorrect, a change
introduced a while ago by #4014.
Signed-off-by: Carlos Antonio da Silva <carlosantoniodasilva@gmail.com>
It's an unauthenticated request, so return 401 Unauthorized like most
other similar requests.
Signed-off-by: Carlos Antonio da Silva <carlosantoniodasilva@gmail.com>
Used Rails' secure_compare method inside the definition of
secure_compare. This will handle the empty strings comparison and
return true when both the parameters are empty strings.
Fixes#4441, #4829
In Rack v3.1.0, the symbol for HTTP status code 422 was changed from `:unprocessable_entity` to `:unprocessable_content`.
As a result, when using rack 3.2 with the following configuration in `config/initializers/devise.rb`, a warning is shown on login failure:
```ruby
# config/initializers/devise.rb
Devise.setup do |config|
...
config.responder.error_status = :unprocessable_entity
```
Warning message:
```sh
/path-to-app/vendor/bundle/ruby/3.4.0/gems/devise-4.9.4/lib/devise/failure_app.rb:80: warning: Status code :unprocessable_entity is deprecated and will be removed in a future version of Rack. Please use :unprocessable_content instead.
```
This warning can be resolved by updating the config as follows:
```diff
# config/initializers/devise.rb
Devise.setup do |config|
...
+ config.responder.error_status = :unprocessable_content
- config.responder.error_status = :unprocessable_entity
```
This fixes the root cause of the warning for new apps by adjusting the generated config during `$ rails generate devise:install` depending on the rack version, so new apps using newer Rack versions generate `error_status = :unprocessable_content` instead of `:unprocessable_entity`.
Existing apps are handled by [latest versions of Rails, which will now transparently convert the code under the hood to avoid the Rack warning](https://github.com/rails/rails/pull/53383), and Devise will use that translation layer when available in the failure app to prevent the warning there as well (since that isn't covered by Rails automatic conversion).
Signed-off-by: Carlos Antonio da Silva <carlosantoniodasilva@gmail.com>
We need to explicitly pass the `locale` around from the options (passed
to `warden.authenticate!` for instance) or the `I18n.locale` when
logging out and redirecting the user via `throw :warden`, otherwise in a
multi-locale app we'd lose the locale previously set / passed around and
fallback to the default for that flash message.
This is a follow-up of the fixes in #5567 where we implemented the
locale passing logic down to the failure app, but it missed these places
where we were using `throw :warden`.
Closes#5812
https://www.ruby-lang.org/en/news/2025/12/25/ruby-4-0-0-released/
We need to add `ostruct` as a dev dependency because it doesn't come
as a default gem with Ruby 4.0 anymore.
Lock minitest < 6 since v6 has some incompatibilities with released
versions of Rails that will be fixed in future versions.
This is something I didn't run into a few other gems, but SimpleForm
did, presumabily because it touches additional areas like AV tests.
This is no longer in Rails since v5, it's been extracted to
`protected_attributes`, and we're dropping support to older versions of
Rails in main.
https://github.com/rails/protected_attributes
All of these have been deprecated for years, if we're releasing a new
major version, let's take the opportunity to do some cleanup.
* Remove deprecated `:bypass` option from `sign_in` helper,
use `bypass_sign_in` instead.
* Remove deprecated `devise_error_messages!` helper,
use `render "devise/shared/error_messages", resource: resource` instead.
* Remove deprecated `scope` second argument from `sign_in(resource, :admin)`
controller test helper, use `sign_in(resource, scope: :admin)` instead.
* Remove deprecated `Devise::TestHelpers`,
use `Devise::Test::ControllerHelpers` instead.
Closes#5739
Devise hasn't been tested with Mongoid since Rails version 5, only 4.x was still running those tests.
This enables the tests again on all currently supported Rails versions, with their respective mongoid supported versions. There were a couple of minor tweaks to make it happen, namely:
* The way we were dropping the session before doesn't work in later versions so I changed back to calling `purge!` which appears to work fine. We used to call `Mongoid.purge!` but that changed in #4686.
* Some of the configs in the Rails test app were setting Active Record values when outside of the AR ORM tests, updated those to make sure they are not set when running mongoid ORM tests.
* The validations added to the shared admin code in tests were only checking for Rails version 5.1, but we need to use the same check for AR 5.1 that is used in code, otherwise it will try to use methods not available in mongoid there.
We pointed to github to fix issues with Ruby 2.7 and kwargs, but since
then a version 1.0.5 was released which includes those fixes.
There's a few more things in their main, but nothing we need if all is
green.
./devise/test/support/webrat/matchers.rb:6: warning:
Nokogiri::CSS.parse is deprecated and will be removed in a future
version of Nokogiri. Use Nokogiri::CSS::Parser#parse instead.
Update argument name for config.warden [ci skip]
The argument for the block passed to `config.warden` is no a `Warden::Manager` instance but a `Warden::Config` instance, but it is confusingly named `manager` in the generated file.
Renaming this to `warden_config` for clarity.
When ActionMailer is not defined we have empty app/mailers/devise/mailer.rb file and Zeitwerk doesn't
like that and errors with
```
expected file app/mailers/devise/mailer.rb to define constant Devise::Mailer
```
The fix is to tell Zeitwerk to ignore that file if ActionMailer constant if not defined.
I tried to write a spec for it but since specs are run in the same process it's hard to have two
Rails applications where one of them has ActionMailer define and the seconds one doesn't.
Starting from Rails 8.0, routes are lazy-loaded by default in test and development environments.
However, Devise's mappings are built during the routes loading phase.
To ensure it works correctly, we need to load the routes first before accessing @@mappings.
main is targetting a v5 with some possible breaking changes, for main
it's mainly dropping support for older Ruby/Rails versions, but more
might come.
[ci skip]
A common usage of I18n with different locales is to create some around
callback in the application controller that sets the locale for the
entire action, via params/url/user/etc., which ensure the locale is
respected for the duration of that action, and resets at the end.
Devise was not respecting the locale when the authenticate failed and
triggered the failure app, because that happens in a warden middleware
right up in the change, by that time the controller around callback had
already reset the locale back to its default, and the failure app would
just translate flash messages using the default locale.
Now we are passing the current locale down to the failure app via warden
options, and wrapping it with an around callback, which makes the
failure app respect the set I18n locale by the controller at the time
the authentication failure is triggered, working as expected. (much more
like a normal controller would.)
I chose to introduce a callback in the failure app so we could wrap the
whole `respond` action processing rather than adding individual `locale`
options to the `I18n.t` calls, because that should ensure other possible
`I18n.t` calls from overridden failure apps would respect the set locale
as well, and makes it more like one would implement in a controller. I
don't recommend people using callbacks in their own failure apps though,
as this is not going to be documented as a "feature" of failures apps,
it's considered "internal" and could be refactored at any point.
It is possible to override the locale with the new `i18n_locale` method,
which simply defaults to the passed locale from the controller.
Closes#5247Closes#5246
Related to: #3052, #4823, and possible others already closed.
Related to warden: (may be closed there afterwards)
https://github.com/wardencommunity/warden/issues/180https://github.com/wardencommunity/warden/issues/170
It's EOL but the current versions of Rails are still supporting it, so
it makes sense for us to keep supporting it as well. And it doesn't give
us any extra maintenance burden as older versions have been doing.
There was a change introduced in Rails 7.1 that causes all public
actions of non-abstract controllers to become action methods, even if
they happen to match the name of an internal method defined by abstract
`ActionController::Base` and such, which is the case with `_prefixes`.
This change was intentional, it allows for example to have an action
called `status`, which is an internal method, and that is properly
managed as an action method now. However, it broke Devise due to
overriding `_prefixes`, which is a public method of Action Controller.
To fix, we are simply ensuring we keep `_prefixes` as an internal method
rather than action method, which matches previous behavior for this
particular method/implementation in Devise.
Ref: https://github.com/rails/rails/pull/48699
There's some incompatibility issue with loofah there since it uses an
older version of nokogiri, so I'm locking it on those older versions to
try to get a green build again there.
We still support super old versions, yes, and it doesn't like `ensure`
without a `begin..end` unfortunately.
I plan to remove this support soon, but for now I don't want to stop
supporting it yet.
- ### Context
Since version 2.0.0, Omniauth no longer recognizes `GET` request
on the auth path (`/users/auth/<provider>`). `POST` is the only
verb that is by default recognized in order to mitigate CSRF
attack. 66110da85e/lib/omniauth/strategy.rb (L205)
Ultimatelly, when a user try to access `GET /users/auth/facebook`,
Devise [passthru action](6d32d2447c/app/controllers/devise/omniauth_callbacks_controller.rb (L6))
will be called which just return a raw 404 page.
### Problem
There is no problem per se and everything work. However the
advantage of not matching GET request at the router layer allows
to get that same 404 page stylized for "free" (Rails ending up
rendering the 404 page of the app).
I believe it's also more consistent and less surprising for users
if this passthru action don't get called.
### Drawback
An application can no longer override the `passthru` to perform
the logic it wants (i.e. redirect the user).
If this is a dealbreaker, feel free to close this PR :).
Rails allow procs and lambda with either zero or more argument. Devise
however always tried to call instance_eval on those values, which does
always pass one argument: self.
There was a PR to fix this specific problem in Devise https://github.com/heartcombo/devise/pull/4627,
before the arity check was fixed in rails itself: https://github.com/rails/rails/pull/30391.
But even if the problem was fixed in Rails, Devise was still calling
the proc/lambas with instance_eval. That meant the fix added to Rails
did not apply to Devise.
The fix is to let Rails handle the :from and :reply_to defaults. We do
that by unsetting the headers instead of trying to replicate Rails handling
in Devise. This lets Rails handle it when setting up the mailer.
In regular HTML `<br>` is a void element, so it
Many of the shared templates used by devise use `<br/>`
to separate lines, which is invalid html because `<br>`
doesn't need a closing tag or a closing slash. See the
WhatWG spec here:
https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-br-element
Also, the WhatWG spec uses `<p>` tags to separate
`<label>` and `<input>` tags rather than `<br>`, see
here:
https://html.spec.whatwg.org/multipage/input.html
To clean this up I've replaced `<br/>` with paragraph
tags throughout all of the templates.
This reverts b86c1c241b
DEPRECATION WARNING: SchemaMigration no longer inherits from
ActiveRecord::Base. If you want to use the default connection, remove
this argument. If you want to use a specific connection, instantiate
MigrationContext with the connection's schema migration, for example
`MigrationContext.new(path, Dog.connection.schema_migration)`.
Even though this is considered an internal / non-public / nodoc method,
it seems some libraries relied on it internally, causing some breakage.
Known libraries so far are `devise-security` and
`devise-pwned_password`.
Closes#5580
Devise is able to work with a specific ORM, either Active Record or
Mongoid, but nothing stops apps from using multiple ORMs within the same
application -- they just need to pick one to use with Devise. That's
generally determined by the require that is added to the Devise
initializer, that will load up either ORM's extensions so you can call
things like `devise` on your model to set it up.
However, some conditional logic in Devise, more specifically around
dirty tracking, was only considering having Active Record loaded up
after a certain version, to determine which methods to call in parts of
the implementation. In a previous change we refactored all that dirty
tracking code into this `OrmDirtyTracking` module to make it easier to
view all the methods that were being conditionally called, and now we're
repurposing this into a more generic `Orm` module (that's nodoc'ed by
default) so that upon including it, we can conditionally include the
proper dirty tracking extensions but also check whether the including
model is really Active Record or not, so we can trigger the correct
dirty tracking behavior for Mongoid as well if both are loaded on the
same app, whereas previously the Mongoid behavior would always use the
new Active Record behavior, but support may differ.
While we are also working to ensure the latest versions of Mongoid are
fully running with Devise, this should improve the situation by giving
apps with multiple ORMs loaded a chance to rely on some of these Devise
bits of functionality better now that weren't working properly before
without some monkey-patching on their end.
Closes#5539Closes#4542
We have an number of conditions due to how dirty tracking changed around
Rails 5.1, that implement methods using one or another method call. I
might need more of this for mongo upgrades based on an initial
investigation, plus this makes the code really hard to reason about
sometimes with these many conditionals.
While I want to drop support for older versions of Rails soon, this
centralization of dirty methods that are used by devise conditionally
simplifies the usage considerably across the board, moves the version
condition to a single place, and will make it easier to refactor later
once we drop older Rails version by simply removing the `devise_*`
versions of the methods, alongside the prefix on the method calls for
the most part, since those methods follow the naming of the newer Rails
versions.
It appears some people use the recall functionality with a redirect
response, and Devise starting on version 4.9 was overriding that status
code to the configured `error_status` for better Turbo support, which
broke the redirect functionality / expectation.
While I don't think it's really great usage of the recall functionality,
or at least it was unexpected usage, it's been working like that
basically forever where recalling would use the status code of the
recalled action, so this at least keeps it more consistent with that
behavior by respecting redirects and keeping that response as a redirect
based on the configured status, which should also work with Turbo I
believe, and makes this less of a breaking change.
Closes#5570Closes#5561 (it was closed previously, but related / closes with an
actual change now.)
While introducing this on turbo, looks like no specific test was added,
so this at least covers that a bit.
It needs some conditional checks since not all supported Rails +
Responders version work with the customization, so there's one test for
the hardcoded status version too, which can be removed in the future.
Rails main / 7.1.0.alpha introduced a change to improve typography by
default, by converting all apostrophes to be single quotation marks.
https://github.com/rails/rails/pull/45463
The change caused all our text based matching to fail, this updates the
tests to ensure compatibility.
Model tests were changed to test against the error type & information
rather than the translated string, which I think is an improvement
overall that should make them a little less brittle. I thought of using
[of_kind?] but that isn't available on all Rails versions we currently
support, while `added?` is. The drawback is that `added?` require full
details like the `:confirmation` example which requires the related
attribute that is being confirmed, but that's a small price to pay.
Integration tests were changed to match on a regexp that accepts both
quotes. I could've used a simple `.` to match anything there, but
thought I'd just keep it specific for clarity on what it is really
expected to match there. Plus, since it's integration testing against a
rendered response body, it's better to match the actual text rather than
resort on other ways. (like using I18n directly, etc.)
[of_kind?] https://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-of_kind-3F
We can't just "swap" those model properties, as that sets instance vars
on the classes that get reverted to their "previous" value, which ends
up leaving the instance vars set as `nil`. However, our logic for those
model/class properties actually checks for `defined?` as a way to
override them, and delegates up to `Devise` global config if they are
not defined, so leaving instance vars back with `nil` values isn't
enough, we need to actually remove them.
This introduces a new test helper specifically for overriding those
model configs so that we can do proper cleanup.
This is an attempt to address the Webrat / Nokogiri compatibility issue
[discussed here]. It monkeypatches Webrat to explicitly add the old
default arguments to the invocation of to_xpath.
Move monkey patch to its own file under test/support/webrat.
I really need to get rid of webrat.
Closes#5475
[discussed here] https://github.com/sparklemotion/nokogiri/issues/2469
Expand tests to check for the actual validatable exception message
This was raising a `FrozenError` on Ruby < 3 where interpolated strings
were considered frozen. This [changed in Ruby 3], since such strings are
dynamic there's no point in freezing them by default.
The test wasn't catching this because `FrozenError` actually inherits
from `RuntimeError`:
>> FrozenError.ancestors
=> [FrozenError, RuntimeError, StandardError, Exception, Object ...]
So the exception check passed. Now we're also checking for the error
message to ensure it raised the exception we really expected there.
Closes#5465
[changed in Ruby 3] https://bugs.ruby-lang.org/issues/17104
Co-authored-by: Martin <martin@edv-beratung-meier.de>
It is indeed recommended for consistency, but Rails will be able to find
the views under `devise/` due to inheritance still, so make that a bit
clearer in the readme docs about customizing controllers, explaining
that copying or moving the views is an optional step.
Closes#5526
[ci skip]
Albeit it's not super recommended, it's possible and even mentioned in
the changelog/wiki in case the app has some additional responder logic
that needs to be applied to Devise across the board.
Explain a bit more about how `data-confirm` and `data-method` need to be
updated to the turbo versions `data-turbo-confirm` and
`data-turbo-method`, respectively. (and depending on its usage.)
[ci skip]
There's some additional information in the wiki upgrade guide for those
interested, but most of it is covered in the changelog and should
suffice.
The post install message should help guide people upgrading to make sure
they know what to do in this new version, since some may be using Turbo
out there with custom responders and failure apps and those would have
to be removed in order to use these new changes fully. Hopefully that's
enough of a nudge for them.
Just want to have something different than the currently released
version to test out more easily. Plus, this is probably going to become
v4.9.0 final soon anyway.
Unfortunately we can't enforce the version in the gemspec because
responders only supports Rails 5.2 now, and Devise still supports
previous versions.
We'll drop support for those in a future major release, so for now I'm
not adding any version.
This also adds a warning in case someone is using an older version of
responders and tries to set the error/redirect statuses via Devise, so
that they know what to do (upgrade responders) in that case.
This changes the OmniAuth "sign in" links to use buttons, which can be
wrapped in an actual HTML form with a method POST, making them work
better with and without Turbo in the app. It doesn't require rails/ujs
anymore in case of a non-Turbo app, as it previously did with links +
method=POST.
Turbo is disabled for those OmniAuth buttons, as they simply don't work
trying to follow the redirect to the OmniAuth provider via fetch,
causing CORS issues/errors.
Rails master on Ruby 2.7/3.0 is failing with the following error:
Resolving dependencies...
Could not find compatible versions
Because every version of rails depends on RubyGems >= 3.3.13
and Gemfile-rails-main depends on rails >= 0,
RubyGems >= 3.3.13 is required.
So, because current RubyGems version is = 3.1.6,
version solving has failed.
Trying to run with the latest available rubygems to see if that can fix
the problem, but sticking to the "default" rubygems version on older
Ruby versions to avoid build issues there.
It appears we're getting a newer version of this multipart-post
dependency, which doesn't work well with Ruby 2.2 by using
`Object.deprecate_constant`, resulting in the following error:
.../multipart-post-2.2.0/lib/multipart/post/parts.rb:152:in `<top (required)>':
undefined method `deprecate_constant' for Object:Class (NoMethodError)
Hopefully by locking on a previous version we can just get the build
back to green for now.
This simplifies the logic considerably, as we don't need to reach out to
what seems more internal-ish implementation of Rails with the
interaction between the request and controller objects.
b925880914
Rails implemented a CSRF token storage strategy to allow storing the
CSRF tokens outside of the sessios (for example, in an encrypted
cookie), and changed how the value is kept around during the request
cycle, by using a request.env value.
We still want to ensure the final session value is cleaned correctly in
the test, but the implementation needed to change since we can't simply
delete from the session anymore, we need to make sure we call the Rails
methods for resetting the current storage strategy so it works with all
of them.
https://github.com/rails/rails/pull/44283
* Rails and Ruby versions follow the most recent to oldest, except for
Rails main, so we can keep the Gemfile the first one.
* Excluding specific matrix combinations based on the Gemfile first,
Ruby version next, and keep the same order (most recent -> oldest)
* Quote all Ruby versions to keep things consistent. It's required for
the '3.0' version to avoid the float issue where it'd use the latest
3.x instead.
When you copy the commands that have the terminal beginning of line symbol in front of them you now no longer need to first delete this before running the command
Use `AS::Dependencies` as before if we still can, otherwise use the new
direct `constantize` call for Rails 7+.
Leave a TODO to help remind us this can be removed once we drop support
to Rails versions prior to 7 in the future.
It appears setting the `rack.session` to a simple hash doesn't work
anymore as it now has a few additional methods Rails is relying on to
determine whether it's enabled or not:
https://github.com/rails/rails/pull/42231
Failure:
NoMethodError: undefined method `enabled?' for {}:Hash
rails (f55cdafe4b82) actionpack/lib/action_dispatch/middleware/flash.rb:62:in `commit_flash'
Turns we we don't seem to need to set `rack.session` for the tests here.
Changes deprecated `ActiveSupport::Dependencies.constantize(model_name)` to `model_name.constantize`
Co-authored-by: Carlos Antonio da Silva <carlosantoniodasilva@gmail.com>
Remove `ActiveSupport::Dependencies.reference`
This was deleted from Rails: 14d4edd7c3
As far as I can tell, it was meant to add a performance boost at some point in the past but doesn't seem to do anything useful these days.
Update a couple other modules that still referred to `devise_for` to
point to `devise`, and make all of them more consistent. We can only
mention `devise`, that should be clear enough about it being options
for the model method.
Resetting failed attempts after sign in happened inside a warden hook
specific for the lockable module, but that was hidden inside the hook
implementation and didn't allow any user customization.
One such customization needed for example is to direct these updates to
a write DB when using a multi-DB setup. With the logic hidden in the
warden hook this wasn't possible, now that it's exposed in a model
method much like trackable, we can override the model method to wrap it
in a connection switch block for example, point to a write DB, and
simply call `super`.
Closes#5310
Related to #5264 and #5133
2.2.10 is causing the dependency resolution on Rails 6-0-stable to fail:
```
Bundler could not find compatible versions for gem "railties":
In Gemfile-rails-6-0:
devise was resolved to 4.7.3, which depends on
railties (>= 4.1.0)
rails was resolved to 6.0.3.5, which depends on
railties (= 6.0.3.5)
responders (~> 3.0) was resolved to 3.0.1, which depends on
railties (>= 5.0)
Took 27.49 seconds
```
https://github.com/heartcombo/devise/runs/1905780158?check_suite_focus=true#step:5:23
The `railties` version 6.0.3.5 should work, given the other two are
using >= declarations, but it fails in 2.2.10.
Downgrading to 2.2.9 works.
The test suite was failing on Rails 6.0 + Ruby 3 with errors like:
Expected "{\"errors\":\"#<ActiveModel::Errors:0x000055f2e6cb8188>\"}"
to include "{\"errors\":{".
The ActiveModel::Errors object wasn't being serialized to JSON as
expected, and this only happened with that combination of Ruby/Rails.
Upon further investigation, this was caused by a change in Ruby and
fixed in Rails in this PR: https://github.com/rails/rails/pull/39697
(which describes in more details the exact same problem and links to the
Ruby bug tracker with more information).
That fix was backported to 6-0-stable in June 2020, but hasn't been
officially released in a stable version yet: (there have been only
security fixes since then for 6.0)
75f6539d0e
Since the branch contains the fix, I'm pointing directly to it to get
the tests passing. We can't tell if there'll be a new stable 6.0 release
at this point, but hopefully yes, in which case we can go back at
pointing to it.
This allows us to remove the dependency on the XML serializer provided
by the external `activemodel-serializers-xml` gem, and eliminates the
following deprecation warning:
DEPRECATION WARNING: ActiveModel::Errors#to_xml is deprecated and
will be removed in Rails 6.2.
Please note: this does not mean Devise doesn't support XML, it simply
means our test suite will use JSON to test non-navigatable formats
instead of XML, for simplicity. Devise's job is not to test object
serialization, so as long as your objects properly serialize to
XML/JSON/any other format, it should work out of the box.
And remove dupe entry in the exclude matrix.
In order to get Ruby 3 working we needed to install `rexml` as part of
the test dependencies, only done on the main Gemfile (Rails 6.1) and the
6.0 versions. (which are the only ones supported by Ruby 3.)
Devise itself doesn't require `rexml` as it does nothing with it, but a
dependency we use during tests seem to require it. I was able to track
it down to omniauth-openid -> rack-openid -> ruby-openid requiring it:
13a88ad644/lib/openid/yadis/xrds.rb (L1)
So while we have tests using omniauth-openid, we'll need this require in
place as well. Ideally that upstream version of ruby-openid should have
it, but it seems that one isn't updated in a while.
I'm sure more people will hit issues so I'm trying to add more guidance
here about how to upgrade... maybe that should be in its own wiki but
I'll keep it all in the changelog for now.
* Make test for validation to be Rails 6.1 compatible
The `ActiveModel::Errors` has been changed in Rails 6.1.
https://github.com/rails/rails/pull/32313
* Add gemfile for Rails 6.1
* Add CI matrix for Rails 6.1
Seven year ago rails `session.keys` could be empty if the session was
not loaded yet.
To prevent an error the removed code was introduced
https://github.com/heartcombo/devise/issues/2660
Since then rails changed the behaviour and makes sure that the session
is loaded before someone wants to access any session keys
3498aacbbe
Which means the `session.empty?` is not needed anymore once Rails 5.2+
and upwards only supported.
Deprecate `BLACKLIST_FOR_SERIALIZATION` constant in favor of a more
descriptive name `UNSAFE_ATTRIBUTES_FOR_SERIALIZATION`, removing
unnecessary usage of the word `blacklist` from devise.
The previous constant still works but will emit a warning if used, to
allow anyone still depending on it to upgrade.
This includes an internal backport of the Rails `deprecate_constant`
implementation that exists on Rails 5.1+ to be able to deprecate it
properly in prior versions, while we support those. (which I intend to
drop soon.)
I ran into an issue where options[:except] is a frozen array, which
explodes when we try to concat values in `serializable_hash`. To fix this
we dup the `:except` option before concatenating with the other options
there.
Closes#5278.
This one has been showing up when running tests:
Deprecation warning: Expected string default value for '--orm'; got false (boolean).
This will be rejected in the future unless you explicitly pass the options
`check_default_type: false` or call `allow_incompatible_default_type!` in your code
You can silence deprecations warning by setting the environment variable THOR_SILENCE_DEPRECATION.
The deprecation of `devise_error_messages!` wasn't super clear on what
was happening and how to get rid of the message, not it has a more
detailed explanation with an example of what to look for and what to
replace it with.
Closes#5257.
This is warning on Ruby 2.7, and seems unnecessary since Rails 5+
adopted kwargs approach. We still need to handle the difference for
Rails < 5 for now, while we support it (which I would like to remove
soon.)
Mocha deprecation warning at
...../active_support/dependencies.rb:324:in `require':
Require 'mocha/test_unit', 'mocha/minitest' or 'mocha/api'
instead of 'mocha/setup'.
This reverts commit d85d45bcef.
My mistake: this section is about *not* using Devise when starting with
Rails and building authentication for the first time, therefore we
should not be linking to Devise specific resources here.
[ci skip]
This is essentially the same as `gemfiles/Gemfile.rails-6.0-stable`, but
I'm keeping both for now since I want to change the main `Gemfile` later
to point to Rails master (`6.1.0.alpha`), so then I won't need to
recreate the `6.0-stable` Gemfile again.
Not sure how/when this one was removed, probably just mistakenly, so
let's add it back for now, at least while we support multiple old Ruby /
Rails versions. (which I plan to remove support in the near future.)
* `changed?` behaviour has been updated
Due to 16ae3db5a5 `changed?` has been updated to check for dirtiness after save. The new method that behaves like the old `changed` is `saved_changes?`.
* Add comment to explain which method to used based on which rails version it is
As reported in https://github.com/plataformatec/devise/issues/5071, if
for some reason, a user in the database had the `confirmation_token`
column as a blank string, Devise would confirm that user after receiving
a request with a blank `confirmation_token` parameter.
After this commit, a request sending a blank `confirmation_token`
parameter will receive a validation error.
For applications that have users with a blank `confirmation_token` in
the database, it's recommended to manually regenerate or to nullify
them.
* Fix specs on Rails 6 RC2
`ActiveRecord::MigrationContext` now has a `schema_migration` attribute.
Ref: https://github.com/rails/rails/pull/36439/files#diff-8d3c44120f7b67ff79e2fbe6a40d0ad6R1018
* Use `media_type` instead of `content_type`
Before Rails 6 RC2, the `ActionDispatch::Response#content_type` method
would return only the media part of the `Content-Type` header, without any
other parts. Now the `#content_type` method returns the entire header -
as it is - and `#media_type` should be used instead to get the previous
behavior.
Ref:
- https://github.com/rails/rails/pull/36034
- https://github.com/rails/rails/pull/36854
* Use render template instead of render file
Render file will need the full path in order to avoid security breaches.
In this particular case, there's no need to use render file, it's ok to
use render template.
Ref: https://github.com/rails/rails/pull/35688
* Don't set `represent_boolean_as_integer` on Rails 6
* Update comments [ci skip]
Comment incorrectly states that default method is "get", while line 228 of /lib/devise.rb sets "delete": "The default method used while signing out: @@sign_out_via = :delete"
Also bumped sqlite from 1.3.6 to 1.4 because besides conflicting with
the version that the sqlite adapter was trying to load [0], it is supported
officially since rails 6 [1].
Related:
[0] rails/rails#35153
[1] rails/rails#35844
Forwarding methods to private methods is deprecated and produces a
warning after Ruby 2.4.
see: https://bugs.ruby-lang.org/issues/12782
To fix this issue I'm mocking patching webrat making RailsAdatper#response
method public since Webrat::Session is delegating functions to it.
The command bin/test stop running single tests once Devise started to
support Rails 5.2. The problem is because we used `rails/test_unit/minitest_plugin`
and this file was moved to another place.
See: https://github.com/rails/rails/pull/29572
I'm not sure if we should require the `minitest-plugin` directly from
Rails like we were doing, I tried it and it didn't work. So I'm
changing this `bin/test` completely based on how Rails does that [here](https://github.com/rails/rails/blob/master/tools/test.rb)
Before setting this option, our test suite was giving the following warning:
```
DEPRECATION WARNING: Leaving `ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer`
set to false is deprecated. SQLite databases have used 't' and 'f' to serialize
boolean values and must have old data converted to 1 and 0 (its native boolean
serialization) before setting this flag to true. Conversion can be accomplished
by setting up a rake task which runs
ExampleModel.where("boolean_column = 't'").update_all(boolean_column: 1)
ExampleModel.where("boolean_column = 'f'").update_all(boolean_column: 0)
for all models and all boolean columns, after which the flag must be set to
true by adding the following to your application.rb file:
Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
(called from <top (required)> at $PATH/devise/test/rails_app/app/active_record/user.rb:5)
```
After configuring `represent_boolean_as_integer = true` as specified
above, we don't have this warning anymore.
More info:
https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html#method-c-represent_boolean_as_integer
As reported in #4981, the method `#increment_failed_attempts` of `Devise::Models::Lockable` was
not concurrency safe. The increment operation was being done in two steps: first the value was read from the database, and then incremented by 1. This may result in wrong values if two requests try to update the value concurrently. For example:
```
Browser1 -------> Read `failed_attempts` from DB (1) -------> Increment `failed_attempts` to 2
Browser2 -------> Read `failed_attempts` from DB (1) -------> Increment `failed_attempts` to 2
```
In the example above, `failed_attempts` should have been set to 3, but it will be set to 2.
This commit handles this case by calling `ActiveRecord::CounterCache.increment_counter` method, which will do both steps at once, reading the value straight from the database.
This commit also adds a `ActiveRecord::AttributeMethods::Dirty#reload` call to ensure that the application gets the updated value - i.e. that other request might have updated.
Although this does not ensure that the value is in fact the most recent one - other request could've updated it after the `reload` call - it seems good enough for this implementation.
Even if a request does not locks the account because it has a stale value, the next one - that updated that value - will do it. That's why we decided not to use a pessimistic lock here.
Closes#4981.
If `Confirmable#confirmation_sent_at` is equal to `0.days.ago`, then
`confirmation_period_valid?` will be deemed valid even if the setting is
configured to disable this outright. To prevent this error, we explicitly
check the configuration setting to be `0.days.ago`.
After merging https://github.com/plataformatec/devise/pull/4797, I
noticed that we had no specs for the scenarios where this method was
adding the errors to the resource. This commit adds tests to cover those
cases.
The original text:
> You can add it to your Gemfile with:
Could easily be read as: "Run this command to add it to your Gemfile"
That's what I did at least. I think the change makes it much clearer that you need to really manually add a line of text into the Gemfile.
One of the reasons why this is not fully clear is that it's badly visible on Github whether a command is a console / terminal command or a ruby line of code. Visually they look the same except for the $ sign which is easy to overlook.
If called with a hash that has a `default` / `default_proc`
configured, `Devise::ParameterFilter` can add in missing keys
it was due to attempt to sanitise the values for.
This patch prevents this from happening, whilst also clarifying
the filtering intent of `ParamaterFilter`.
(This can also occur if NilClass has been augmented with definitions
for `strip` or `downcase`.)
Fixes#3431.
With this fix, we will try latest changes in Rails 5.2 together with standard auto-generated secret_key_base in development as a fallback.
If no specified key found, auto-generated value will be used instead.
Use `autocomplete="new-password"` or `autocomplete="current-password"` to better signal to browsers and password managers how to handle the password fields.
This feature is especially useful for “change your password” and “new user” forms
In order to use the `sign_in` helper along with the timeoutable module,
we have to set `env["devise.skip_timeout"] = true` in the request.
Currently, we do this in the sessions controller: https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb#L7
This commit adds a note to the `sign_in` documentation to help other
developers that want to use custom warden strategies.
Closes#4773
This permits users to easily customize where the ip address
should be resolved. When fronting the application with a webserver or
load balancer, the ip address may be the server and not be the user.
E.g. consider the IP address is passed as the header: "X-Forwarded-For".
```ruby
class User
devise :trackable
protected
def extract_ip_from(request)
request.headers["X-Forwarded-For"]
end
end
```
- DRY up some of the sample code by refactoring into smaller methods.
- ‘Namespace’ method names to reduce chances of conflict.
- Mark send_pending_devise_notifications, pending_devise_notifications, and render_and_send_devise_message as `private` since they are only used internally.
- Update comments.
When supporting Rails 5.2 credentials on
https://github.com/plataformatec/devise/pull/4712, we ended up breaking
apps that were upgraded to Rails 5.2 and weren't using `credentials`
to store their `secret_key_base`. See
https://github.com/plataformatec/devise/issues/4807 for more context.
To fix it, we're now checking whether the key is present before using it.
Since there weren't any automated test for this - the conditionals were
in a Rails engine initializer - I've extracted it to a new class so that
we are able to test it easily.
Fixes#4807
Creating a new section called `Controller configuration`.
An optional devise configuration is set `config.parent_controller` but this configuration is missing in the `devise.rb` template file.
In Rails 4, for unauthenticated controller tests which trigger the
failure app, ensure that the simulated failure response includes a
content_type (broken in bb44d42).
This works in Rails5, which parses the content-type header on-demand,
but not in Rails4 which requires setting the response's content_type
explicitly.
Fixes#4783.
This fixes#4710.
Rails introduced :secrets in v5.1. They somehow changed it to :credentials. This fix represents this change.
Devise will now look :credentials first, then fallback to :secrets for 5.1.x compatibility then it will check for standard secret key. If three not found then exception will arise.
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
```
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 [heartcombo.oss@gmail.com](heartcombo.oss@gmail.com) or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
1) Do not post questions in the issues tracker. If you have any questions about Devise, search the [Wiki](https://github.com/plataformatec/devise/wiki) or use the [Mailing List](https://groups.google.com/group/plataformatec-devise) or [Stack Overflow](http://stackoverflow.com/questions/tagged/devise).
Thanks for your interest on contributing to Devise! Here are a few general
guidelines on contributing and reporting bugs to Devise that we ask you to
take a look first. Notice that all of your interactions in the project are
expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md).
2) If you find a security bug, **DO NOT** submit an issue here. Please send an e-mail to [opensource@plataformatec.com.br](mailto:opensource@plataformatec.com.br) instead.
## Reporting Issues
3) Do a small search on the issues tracker before submitting your issue to see if it was already reported / fixed.
Before reporting a new issue, please be sure that the issue wasn't already
reported or fixed by searching on GitHub through our [issues](https://github.com/heartcombo/devise/issues).
4) When reporting an issue, include Rails, Devise and Warden versions. If you are getting exceptions, please include the full backtrace.
When creating a new issue, be sure to include a **title and cleardescription**,
as much relevant information as possible, and either a test case example or
even better a **sample Rails app that replicates the issue** - Devise has a lot
of moving parts and it's functionality can be affected by third party gems, so
we need as much context and details as possible to identify what might be broken
for you. We have a [test case template](guides/bug_report_templates/integration_test.rb)
that can be used to replicate issues with minimal setup.
That's it! The more information you give, the easier it becomes for us to track it down and fix it.
Ideally, you should provide an application that reproduces the error or a test case to Devise's suite.
Please do not attempt to translate Devise built in views. The views are meant
to be a starting point for fresh apps and not production material - eventually
all applications will require custom views where you can write your own copy and
translate it if the application requires it . For historical references, please look into closed
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 [heartcombo.oss@gmail.com](mailto:heartcombo.oss@gmail.com)
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/heartcombo/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 feedback to the issue's
author on what might be missing.
* Review and update the existing content of our [Wiki](https://github.com/heartcombo/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!
Devise is a flexible authentication solution for Rails based on Warden. It:
* Is Rack based;
* Is a complete MVC solution based on Rails engines;
* Allows you to have multiple models signed in at the same time;
* Is based on a modularity concept: use just what you really need.
* 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): 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.
* [Confirmable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
* [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions.
* [Registerable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account.
* [Rememberable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie.
* [Trackable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address.
* [Timeoutable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have no activity in a specified period of time.
* [Validatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations.
* [Lockable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.
* [Database Authenticatable](https://www.rubydoc.info/gems/devise/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](https://www.rubydoc.info/gems/devise/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
* [Recoverable](https://www.rubydoc.info/gems/devise/Devise/Models/Recoverable): resets the user password and sends reset instructions.
* [Registerable](https://www.rubydoc.info/gems/devise/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account.
* [Rememberable](https://www.rubydoc.info/gems/devise/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie.
* [Trackable](https://www.rubydoc.info/gems/devise/Devise/Models/Trackable): tracks sign in count, timestamps and IP address.
* [Timeoutable](https://www.rubydoc.info/gems/devise/Devise/Models/Timeoutable): expires sessions that have not been active in a specified period of time.
* [Validatable](https://www.rubydoc.info/gems/devise/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](https://www.rubydoc.info/gems/devise/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.
Devise is guaranteed to be thread-safe on YARV. Thread-safety support on JRuby is in progress.
## Information
@@ -35,27 +65,32 @@ Devise is guaranteed to be thread-safe on YARV. Thread-safety support on JRuby i
The Devise Wiki has lots of additional information about Devise including many "how-to" articles and answers to the most frequently asked questions. Please browse the Wiki after finishing this README:
https://github.com/plataformatec/devise/wiki
https://github.com/heartcombo/devise/wiki
### Bug reports
If you discover a problem with Devise, we would like to know about it. However, we ask that you please review these guidelines before submitting a bug report:
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.
@@ -63,64 +98,121 @@ If you need to use Devise with previous versions of Rails, you can always run "g
There are a few example applications available on GitHub that demonstrate various features of Devise with different versions of Rails. You can view them here:
Our community has created a number of extensions that add functionality above and beyond what is included with Devise. You can view a list of available extensions and add your own here:
You will usually want to write tests for your changes. To run the test suite, go into Devise's top-level directory and run "bundle install" and "rake". For the tests to pass, you will need to have a MongoDB server (version 2.0 or newer) running on your system.
You will usually want to write tests for your changes. To run the test suite, go into Devise's top-level directory and run `bundle install` and `bin/test`.
Devise works with multiple Ruby and Rails versions, and ActiveRecord and Mongoid ORMs, which means you can run the test suite with some modifiers: `DEVISE_ORM` and `BUNDLE_GEMFILE`.
#### DEVISE_ORM
Since Devise supports both Mongoid and ActiveRecord, we rely on this variable to run specific code for each ORM.
The default value of `DEVISE_ORM` is `active_record`. To run the tests for Mongoid, you can pass `mongoid`:
```
DEVISE_ORM=mongoid bin/test
==> Devise.orm = :mongoid
```
When running the tests for Mongoid, you will need to have a MongoDB server (version 2.0 or newer) running on your system.
Please note that the command output will show the variable value being used.
#### BUNDLE_GEMFILE
We can use this variable to tell bundler what Gemfile it should use (instead of the one in the current directory).
Inside the [gemfiles](https://github.com/heartcombo/devise/tree/main/gemfiles) directory, we have one for each version of Rails we support. When you send us a pull request, it may happen that the test suite breaks using some of them. If that's the case, you can simulate the same environment using the `BUNDLE_GEMFILE` variable.
For example, if the tests broke using Ruby 3.4 and Rails 8.0, you can do the following:
```bash
chruby 3.4.0 # or rbenv shell 3.4.0, or rvm use 3.4.0, etc.
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. Here's a few resources that should help you get started:
* Michael Hartl's online book: http://www.railstutorial.org/book/demo_app#sec-modeling_demo_users
* Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch
* Michael Hartl's online book: https://www.railstutorial.org/book/modeling_users
* Ryan Bates' Railscasts: http://railscasts.com/episodes/250-authentication-from-scratch and http://railscasts.com/episodes/250-authentication-from-scratch-revised
* Codecademy's Ruby on Rails: Authentication and Authorization: https://www.codecademy.com/learn/rails-auth
Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :)
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 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with:
Devise 5 works with Rails 7 onwards. Run:
```ruby
gem'devise'
```sh
bundle add devise
```
Run the bundle command to install it.
After you install Devise and add it to your Gemfile, you need to run the generator:
Next, you need to run the generator:
```console
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:
```console
rails generate devise MODEL
```
Replace MODEL with the class name used for the application’s users (it’s frequently `User` but could also be `Admin`). This will create a model (if one does not exist) and configure it with default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller.
Next, check the MODEL for any additional configuration options you might want to add, such as confirmable or lockable. If you add an option, be sure to inspect the migration file (created by the generator if your ORM supports them) and uncomment the appropriate section. For example, if you add the confirmable option in the model, you'll need to uncomment the Confirmable section in the migration. Then run `rake db:migrate`
Next, you need to set up the default URL options for the Devise mailer in each environment. Here is a possible configuration for `config/environments/development.rb`:
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`:
You should restart your application after changing Devise's configuration options. Otherwise you'll run into strange errors like users being unable to login and route helpers being undefined.
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
```
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
@@ -130,6 +222,8 @@ Devise will create some helpers to use inside your controllers and views. To set
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:
@@ -150,10 +244,10 @@ 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. For instance, for a `:user` resource, the `user_root_path` will be used if it exists, otherwise the default `root_path` will be used. This means that you need to set the root inside your routes:
After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect to. For instance, when using a `:user` resource, the `user_root_path` will be used if it exists; otherwise, the default `root_path` will be used. This means that you need to set the root inside your routes:
```ruby
rootto:"home#index"
rootto:'home#index'
```
You can also override `after_sign_in_path_for` and `after_sign_out_path_for` to customize your redirect hooks.
@@ -172,25 +266,29 @@ 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` among other options. For more 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`.
### Strong Parameters
The Parameter Sanitizer API has changed for Devise 4 :warning:
*For previous Devise versions see https://github.com/heartcombo/devise/tree/3-stable#strong-parameters*
When you customize your own views, you may end up adding new attributes to forms. Rails 4 moved the parameter sanitization from the model to the controller, causing Devise to handle this concern at the controller as well.
There are just three actions in Devise that allows any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and the permitted parameters by default are:
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#new`) - Permits only the authentication keys (like `email`)
*`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 with a simple before filter in your `ApplicationController`:
In case you want to permit additional parameters (the lazy way™), you can do so using a simple before action in your `ApplicationController`:
```ruby
classApplicationController<ActionController::Base
@@ -199,38 +297,57 @@ class ApplicationController < ActionController::Base
The above works for any additional fields where the parameters are simple scalar types. If you have nested attributes (say you're using `accepts_nested_attributes_for`), then you will need to tell devise about those nestings and types. Devise allows you to completely change Devise defaults or invoke custom behaviour by passing a block:
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 thusly:
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 different parameter sanitizer per model. In this case, we recommend inheriting from `Devise::ParameterSanitizer` and add your own logic:
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:
3. Copy the views from `devise/sessions` to `admins/sessions`. Since the controller was changed, it won't use the default views located in `devise/sessions`.
3. Recommended but not required: copy (or move) the views from `devise/sessions` to `users/sessions`. Rails will continue using the views from `devise/sessions` due to inheritance if you skip this step, but having the views matching the controller(s) keeps things consistent.
4. Finally, change or extend the desired controller actions.
You can completely override a controller action:
```ruby
class Admins::SessionsController < Devise::SessionsController
class Users::SessionsController < Devise::SessionsController
def create
# custom sign-in code
end
end
```
Or you can simply add new behaviour to it:
Or you can simply add new behavior to it:
```ruby
class Admins::SessionsController < Devise::SessionsController
class Users::SessionsController < Devise::SessionsController
def create
super do |resource|
BackgroundWorker.trigger(resource)
@@ -325,31 +453,68 @@ If the customization at the views level is not enough, you can customize each co
This is useful for triggering background jobs or logging events during certain actions.
Remember that Devise uses flash messages to let users know if sign in was successful or failed. Devise expects your application to call `flash[:notice]` and `flash[:alert]` as appropriate. Do not print the entire flash hash, print only specific keys. In some circumstances, Devise adds a `:timedout` key to the flash hash, which is not meant for display. Remove this key from the hash if you intend to print the entire hash.
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](https://www.rubydoc.info/gems/devise/ActionDispatch/Routing/Mapper#devise_for-instance_method) 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` in your router.
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 :users, skip: :all
```
### Hotwire/Turbo
Devise integrates with Hotwire/Turbo by treating such requests as navigational, and configuring certain responses for errors and redirects to match the expected behavior. New apps are generated with the following response configuration by default, and existing apps may opt-in by adding the config to their Devise initializers:
```ruby
Devise.setup do |config|
# ...
# When using Devise with Hotwire/Turbo, the http status for error responses
# and some redirects must match the following. The default in Devise for existing
# apps is `200 OK` and `302 Found` respectively, but new apps are generated with
# these new defaults that match Hotwire/Turbo behavior.
# Note: These might become the new default in future versions of Devise.
config.responder.error_status = :unprocessable_content # for Rack 3.1 or higher
# config.responder.error_status = :unprocessable_entity # for Rack 3.0 or lower
config.responder.redirect_status = :see_other
end
```
**Important**: these custom responses require the `responders` gem version to be `3.1.0` or higher, please make sure you update it if you're going to use this configuration. Check [this upgrade guide](https://github.com/heartcombo/devise/wiki/How-To:-Upgrade-to-Devise-4.9.0-[Hotwire-Turbo-integration]) for more info.
_Note_: the above statuses configuration may become the default for Devise in a future release.
There are a couple other changes you might need to make in your app to work with Hotwire/Turbo, if you're migrating from rails-ujs:
* The `data-confirm` option that adds a confirmation modal to buttons/forms before submission needs to change to `data-turbo-confirm`, so that Turbo handles those appropriately.
* The `data-method` option that sets the request method for link submissions needs to change to `data-turbo-method`. This is not necessary for `button_to` or `form`s since Turbo can handle those.
If you're setting up Devise to sign out via `:delete`, and you're using links (instead of buttons wrapped in a form) to sign out with the `method: :delete` option, they will need to be updated as described above. (Devise does not provide sign out links/buttons in its shared views.)
Make sure to inspect your views looking for those, and change appropriately.
### 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:
@@ -385,60 +550,125 @@ en:
Take a look at our locale file to check all available messages. You may also be interested in one of the many translations that are available on our wiki:
https://github.com/plataformatec/devise/wiki/I18n
https://github.com/heartcombo/devise/wiki/I18n
Caution: Devise Controllers inherit from ApplicationController. If your app uses multiple locales, you should be sure to set I18n.locale in ApplicationController
Caution: Devise Controllers inherit from ApplicationController. If your app uses multiple locales, you should be sure to set I18n.locale in ApplicationController.
### Test helpers
Devise includes some test helpers for functional specs. In order to use them, you need to include Devise in your functional tests by adding the following to the bottom of your `test/test_helper.rb` file:
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::IntegrationHelpers` on
your test case or its parent `ActionController::TestCase` superclass.
For Rails versions prior to 5, include `Devise::Test::ControllerHelpers` instead, since the superclass
for controller tests was changed to ActionDispatch::IntegrationTest
(for more details, see the [Integration tests](#integration-tests) section).
```ruby
class ActionController::TestCase
include Devise::TestHelpers
class PostsControllerTest < ActionController::TestCase
include Devise::Test::IntegrationHelpers # Rails >= 5
end
```
If you're using RSpec, you can put the following inside a file named `spec/support/devise.rb` or in your `spec/spec_helper.rb`:
```ruby
class PostsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers # Rails < 5
end
```
If you're using RSpec, you can put the following inside a file named
`spec/support/devise.rb` or in your `spec/spec_helper.rb` (or
`spec/rails_helper.rb` if you are using `rspec-rails`):
Now you are ready to use the `sign_in` and `sign_out` methods. Such methods have the same signature as in controllers:
Just be sure that this inclusion is made *after* the `require 'rspec/rails'` directive.
Now you are ready to use the `sign_in` and `sign_out` methods on your controller
tests:
```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)
sign_in @user
sign_in @user, scope: :admin
```
There are two things that are important to keep in mind:
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:
1. These helpers are not going to work for integration tests driven by Capybara or Webrat. They are meant to be used with functional tests only. Instead, fill in the form or explicitly set the user in session;
```ruby
test 'GET new' do
# Mimic the router behavior of setting the Devise scope through the env.
2. If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from the router, but since functional tests do not pass through the router, it needs to be told explicitly. For example, if you are testing the user scope, simply do:
# Use the sign_in helper to sign in a fixture `User` record.
Devise comes with Omniauth support out of the box to authenticate with other providers. To use it, just specify your omniauth configuration in `config/initializers/devise.rb`:
### Integration tests
Integration test helpers are available by including the
`Devise::Test::IntegrationHelpers` module.
```ruby
class PostsTests < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
end
```
Now you can use the following `sign_in` and `sign_out` methods in your integration
tests:
```ruby
sign_in users(:bob)
sign_in users(:bob), scope: :admin
sign_out :user
```
RSpec users can include the `IntegrationHelpers` module on their `:feature` specs.
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`:
Alternatively, you can simply run the Devise generator.
Keep in mind that those models will have completely different routes. They **do not** and **cannot** share the same controller for sign in, sign out and so on. In case you want to have different roles sharing the same actions, we recommend you to use a role-based approach, by either providing a role column or using a dedicated gem for authorization.
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.
### Active Job Integration
If you are using Active Job to deliver Action Mailer 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](https://www.rubydoc.info/gems/devise/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 INFO 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.
## Additional information
### Rails API Mode
### Heroku
Rails 5+ has a built-in [API Mode](https://edgeguides.rubyonrails.org/api_app.html) which optimizes Rails for use as an API (only). Devise is _somewhat_ able to handle applications that are built in this mode without additional modifications in the sense that it should not raise exceptions and the like. But some issues may still arise during `development`/`testing`, as we still don't know the full extent of this compatibility. (For more information, see [issue #4947](https://github.com/heartcombo/devise/issues/4947/))
Using Devise on Heroku with Ruby on Rails 3.1 requires setting:
#### Supported Authentication Strategies
API-only applications don't support browser-based authentication via cookies, which is devise's default. Yet, devise can still provide authentication out of the box in those cases with the `http_authenticatable` strategy, which uses HTTP Basic Auth and authenticates the user on each request. (For more info, see this wiki article for [How To: Use HTTP Basic Authentication](https://github.com/heartcombo/devise/wiki/How-To:-Use-HTTP-Basic-Authentication))
The devise default for HTTP Auth is disabled, so it will need to be enabled in the devise initializer for the database strategy:
```ruby
config.assets.initialize_on_precompile = false
config.http_authenticatable = [:database]
```
Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html
This restriction does not limit you from implementing custom warden strategies, either in your application or via gem-based extensions for devise.
A common authentication strategy for APIs is token-based authentication. For more information on extending devise to support this type of authentication and others, see the wiki article for [Simple Token Authentication Examples and alternatives](https://github.com/heartcombo/devise/wiki/How-To:-Simple-Token-Authentication-Example#alternatives) or this blog post on [Custom authentication methods with Devise](http://blog.plataformatec.com.br/2019/01/custom-authentication-methods-with-devise/).
#### Testing
API Mode changes the order of the middleware stack, and this can cause problems for `Devise::Test::IntegrationHelpers`. This problem usually surfaces as an ```undefined method `[]=' for nil:NilClass``` error when using integration test helpers, such as `#sign_in`. The solution is simply to reorder the middlewares by adding the following to test.rb:
For a deeper understanding of this, review [this issue](https://github.com/heartcombo/devise/issues/4696).
Additionally be mindful that without views supported, some email-based flows from Confirmable, Recoverable and Lockable are not supported directly at this time.
## 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:
https://github.com/hassox/warden
### Contributors
We have a long list of valued contributors. Check them all at:
MIT License. Copyright 2009-2014 Plataformatec. http://plataformatec.com.br
MIT License.
Copyright 2020-CURRENT Rafael França, Carlos Antonio da Silva.
Copyright 2009-2019 Plataformatec.
You are not granted rights or licenses to the trademarks of the Plataformatec, including without limitation the Devise name or logo.
The Devise logo is licensed under [Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License](https://creativecommons.org/licenses/by-nc-nd/4.0/).
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
# Additional translations at https://github.com/heartcombo/devise/wiki/I18n
en:
devise:
@@ -9,10 +9,10 @@ en:
failure:
already_authenticated:"You are already signed in."
inactive:"Your account is not activated yet."
invalid:"Invalid email or password."
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 email address or password."
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."
@@ -23,6 +23,10 @@ en:
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."
@@ -38,8 +42,9 @@ en:
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."
update_needs_confirmation:"You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address."
updated:"Your account has been updated successfully."
updated_but_not_signed_in:"Your account has been updated successfully, but since your password was changed, you need to sign in again."
# ensure that the controller response is set up. In production, this is
# not necessary since warden returns the results to rack. However, at
# testing time, we want the response to be available to the testing
# framework to verify what would be returned to rack.
ifret.is_a?(Array)
status,headers,body=*ret
# ensure the controller response is set to our response.
@controller.response||=@response
@response.status=status
@response.headers.merge!(headers)
@response.body=body
end
ret
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.