diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 000000000..75ad21eca --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,25 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/ruby +{ + "name": "Ruby", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/ruby:0-3-bullseye", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {} + }, + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "bundle install", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.github/code-scanning.yml b/.github/code-scanning.yml new file mode 100644 index 000000000..0245ae21d --- /dev/null +++ b/.github/code-scanning.yml @@ -0,0 +1,2 @@ +paths-ignore: + - test/** diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..5ace4600a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..d3a7488b9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,71 @@ +name: Test + +permissions: + contents: read +on: + push: + branches: + - main + pull_request: + workflow_dispatch: +jobs: + test: + strategy: + fail-fast: false + matrix: + gemfile: + - Gemfile + - gemfiles/Gemfile-rails-main + - gemfiles/Gemfile-rails-7-0 + - gemfiles/Gemfile-rails-7-1 + - gemfiles/Gemfile-rails-7-2 + - gemfiles/Gemfile-rails-8-0 + ruby: + - '4.0' + - '3.4' + - '3.3' + - '3.2' + - '3.1' + - '3.0' + - '2.7' + orm: + - active_record + - mongoid + exclude: + - gemfile: Gemfile + ruby: '3.1' + - gemfile: Gemfile + ruby: '3.0' + - gemfile: Gemfile + ruby: '2.7' + - gemfile: gemfiles/Gemfile-rails-main + ruby: '3.2' + - gemfile: gemfiles/Gemfile-rails-main + ruby: '3.1' + - gemfile: gemfiles/Gemfile-rails-main + ruby: '3.0' + - gemfile: gemfiles/Gemfile-rails-main + ruby: '2.7' + - gemfile: gemfiles/Gemfile-rails-8-0 + ruby: '3.1' + - gemfile: gemfiles/Gemfile-rails-8-0 + ruby: '3.0' + - gemfile: gemfiles/Gemfile-rails-8-0 + ruby: '2.7' + - gemfile: gemfiles/Gemfile-rails-7-2 + ruby: '3.0' + - gemfile: gemfiles/Gemfile-rails-7-2 + ruby: '2.7' + runs-on: ubuntu-latest + env: # $BUNDLE_GEMFILE must be set at the job level, so it is set for all steps + BUNDLE_GEMFILE: ${{ matrix.gemfile }} + DEVISE_ORM: ${{ matrix.orm }} + steps: + - uses: actions/checkout@v6 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true # runs bundle install and caches installed gems automatically + - uses: supercharge/mongodb-github-action@1.12.1 + if: ${{ matrix.orm == 'mongoid' }} + - run: bundle exec rake diff --git a/.gitignore b/.gitignore index 0ff774271..ac2a95781 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ rdoc/* pkg log test/tmp/* +gemfiles/*.lock diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index feeb80b18..000000000 --- a/.travis.yml +++ /dev/null @@ -1,58 +0,0 @@ -language: ruby - -rvm: - - 2.1.10 - - 2.2.7 - - 2.3.4 - - 2.4.1 - - ruby-head - -gemfile: - - Gemfile - - gemfiles/Gemfile.rails-5.0-stable - - gemfiles/Gemfile.rails-4.2-stable - - gemfiles/Gemfile.rails-4.1-stable - -matrix: - exclude: - - rvm: 2.1.10 - gemfile: Gemfile - - rvm: 2.4.1 - gemfile: gemfiles/Gemfile.rails-4.1-stable - - rvm: ruby-head - gemfile: gemfiles/Gemfile.rails-4.1-stable - - rvm: 2.1.10 - gemfile: gemfiles/Gemfile.rails-5.0-stable - - rvm: 2.1.10 - gemfile: Gemfile - - env: DEVISE_ORM=mongoid - gemfile: Gemfile - - env: DEVISE_ORM=mongoid - gemfile: gemfiles/Gemfile.rails-5.0-stable - allow_failures: - - rvm: ruby-head -services: - - mongodb - -sudo: false - -cache: bundler - -env: - matrix: - - DEVISE_ORM=active_record - - DEVISE_ORM=mongoid - -before_install: "rm ${BUNDLE_GEMFILE}.lock" - -before_script: "bundle update" - -script: "bin/test" - -notifications: - email: false - slack: - on_pull_requests: false - on_success: change - on_failure: always - secure: Q3M+kmude3FjisibEeeGe0wSMXgvwLH+vL7Zrx9//q4QtkfnrQ/BBMvY9KXxPEsNF+eys4YopYjTkJ8uRmeboUATW/oQ4Jrv3+u3zkIHK2sFn/Q2cQWpK5w+CbgEnHPjKYnUu34b09njXTgDlr/mqtbPqrKeZ1dLlpKXCB/q4GY= diff --git a/CHANGELOG.md b/CHANGELOG.md index f0ead4c46..7ccb0882a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,193 +1,88 @@ -### 4.3.0 - 2017-05-14 +### 5.0.4 - 2026-05-08 -* Enhancements - * Dependency support added for Rails 5.1.x. +* security fixes + * Fix open redirect in `FailureApp` via unvalidated `Referer` header on non-GET session timeout. CVE-2026-40295 [GHSA-jp94-3292-c3xv](https://github.com/heartcombo/devise/security/advisories/GHSA-jp94-3292-c3xv) -### 4.2.1 - 2017-03-15 +### 5.0.3 - 2026-03-16 + +* security fixes + * Fix race condition vulnerability on confirmable "change email" which would allow confirming an email they don't own CVE-2026-32700 [GHSA-57hq-95w6-v4fc](https://github.com/heartcombo/devise/security/advisories/GHSA-57hq-95w6-v4fc) [#5783](https://github.com/heartcombo/devise/pull/5783) [#5784](https://github.com/heartcombo/devise/pull/5784) + +### 5.0.2 - 2026-02-18 -* removals - * `Devise::Mailer#scope_name` and `Devise::Mailer#resource` are now protected - methods instead of public. -* bug fixes - * Attempt to reset password without the password field in the request now results in a `:blank` validation error. - Before this change, Devise would accept the reset password request and log the user in, without validating/changing - the password. (by @victor-am) - * Confirmation links now expire based on UTC time, working properly when using different timezones. (by @jjuliano) -* enhancements - * Notify the original email when it is changed with a new `Devise.send_email_changed_notification` setting. - When using `reconfirmable`, the notification will be sent right away instead of when the unconfirmed email is confirmed. - (original change by @ethirajsrinivasan) - -### 4.2.0 - 2016-07-01 - -* removals - * Remove the deprecated `Devise::ParameterSanitizer` API from Devise 3. - Please use the `#permit` and `#sanitize` methods over `#for`. - * Remove the deprecated OmniAuth URL helpers. Use the fully qualified helpers - (`user_facebook_omniauth_authorize_path`) over the scope based helpers - ( `user_omniauth_authorize_path(:facebook)`). - * Remove the `Devise.bcrypt` method, use `Devise::Encryptor.digest` instead. - * Remove the `Devise::Models::Confirmable#confirm!` method, use `confirm` instead. - * Remove the `Devise::Models::Recoverable#reset_password!` method, use `reset_password` instead. - * Remove the `Devise::Models::Recoverable#after_password_reset` method. -* bug fixes - * Fix an `ActionDispatch::IllegalStateError` when testing controllers with Rails 5 rc 2(by @hamadata). - * Use `ActiveSupport.on_load` hooks to include Devise on `ActiveRecord` and `Mongoid`, - avoiding autoloading these constants too soon (by @lucasmazza, @rafaelfranca). * enhancements - * Display the minimum password length on `registrations/edit` view (by @Yanchek99). - * You can disable Devise's routes reloading on boot by through the `reload_routes = false` config. - This can reduce the time taken to boot the application but it might trigger - some errors if you application (mostly your controllers) requires that - Devise mappings be loaded during boot time (by @sidonath). - * Added `Devise::Test::IntegrationHelpers` to bypass the sign in process using - Warden test API (by @lucasmazza). - * Define `inspect` in `Devise::Models::Authenticatable` to help ensure password hashes - aren't included in exceptions or otherwise accidentally serialized (by @tkrajcar). - * Add missing support of `Rails.application.config.action_controller.relative_url_root` (by @kosdiamantis). -* deprecations - * `Devise::TestHelpers` is deprecated in favor of `Devise::Test::ControllerHelpers` - (by @lucasmazza). - * The `sign_in` test helper has changed to use keyword arguments when passing - a scope. `sign_in :admin, users(:alice)` should be rewritten as - `sign_in users(:alice), scope: :admin` (by @lucasmazza). - * The option `bypass` of `Devise::Controllers::SignInOut#sign_in` method is - deprecated in favor of `Devise::Controllers::SignInOut#bypass_sign_in` - method (by @ulissesalmeida). - -### 4.1.1 - 2016-05-15 + * Allow resource class scopes to override the global configuration for `sign_in_after_change_password` behaviour. [#5825](https://github.com/heartcombo/devise/pull/5825) + * _Note_: some users ran into an issue with this change because `RegistrationsController` now relies on a setting from the `:registerable` module. These users were configuring their own routes pointing to the `RegistrationsController` for resource edit/update actions mostly, without relying on the other registration actions (e.g. user sign up.), so they omitted `:registerable` from the model declaration. While using just a portion of the controller functionality is a valid use for `:registerable` (or any module really), the module must still be declared in the model, much like the other modules must be declared if you plan on using just a portion of their behavior. Please check [this issue](https://github.com/heartcombo/devise/pull/5828#issuecomment-3926822788) for more info. + * Add `sign_in_after_reset_password?` check hook to passwords controller, to allow it to be customized by users. [#5826](https://github.com/heartcombo/devise/pull/5826) + +### 5.0.1 - 2026-02-13 * bug fixes - * Fix overwriting the remember_token when a valid one already exists (by @ralinchimev). + * Fix translation issue with German `E-Mail` on invalid authentication messages caused by previous fix for incorrect grammar [#5822](https://github.com/heartcombo/devise/pull/5822) -### 4.1.0 +### 5.0.0 - 2026-01-23 -* bug fixes - * Fix race condition of sending the confirmation instructions e-mail using background jobs. - Using the previous `after_create` callback, the e-mail can be sent before - the record be committed on database, generating a `ActiveRecord::NotFound` error. - Now the confirmation e-mail will be only sent after the database commit, - using the `after_commit` callback. - It may break your test suite on Rails 4 if you are testing the sent e-mails - or enqueued jobs using transactional fixtures enabled or `DatabaseCleaner` with `transaction` strategy. - You can easily fix your test suite using the gem - [test_after_commit](https://github.com/grosser/test_after_commit). For example, put in your Gemfile: - - ```ruby - gem 'test_after_commit', :group => :test - ``` +no changes - On Rails 5 `after_commit` callbacks are triggered even using transactional - fixtures, then this fix will not break your test suite. If you are using `DatabaseCleaner` with the `deletion` or `truncation` strategies it may not break your tests. (by @allenwq) - * Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` and - `:undefined` strategies. (by @f3ndot) -* features - * Humanize authentication keys in failure flash message (by @byzg) - When you are configuring the translations of `devise.failure.invalid`, the - `authentication_keys` is translated now. -* deprecations - * Remove code supporting old session serialization format (by @fphilipe). - * Now the `email_regexp` default uses a more permissive regex: - `/\A[^@\s]+@[^@\s]+\z/` (by @kimgb) - * Now the `strip_whitespace_keys` default is `[:email]` (by @ulissesalmeida) - * Now the `reconfirmable` default is `true` (by @ulissesalmeida) - * Now the `skip_session_storage` default is `[:http_auth]` (by @ulissesalmeida) - * Now the `sign_out_via` default is `:delete` (by @ulissesalmeida) -* improvements - * Avoids extra computation of friendly token for confirmation token (by @sbc100) - -### 4.0.3 - 2016-05-15 - - * bug fixes - * Fix overwriting the remember_token when a valid one already exists (by @ralinchimev). - -### 4.0.2 - 2016-05-02 +### 5.0.0.rc - 2025-12-31 -* bug fixes - * Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` - and `:undefined` strategies. (by @f3ndot) +* breaking changes + * Drop support to Ruby < 2.7 + * Drop support to Rails < 7.0 + * Remove deprecated `:bypass` option from `sign_in` helper, use `bypass_sign_in` instead. [#5803](https://github.com/heartcombo/devise/pull/5803) + * Remove deprecated `devise_error_messages!` helper, use `render "devise/shared/error_messages", resource: resource` instead. [#5803](https://github.com/heartcombo/devise/pull/5803) + * Remove deprecated `scope` second argument from `sign_in(resource, :admin)` controller test helper, use `sign_in(resource, scope: :admin)` instead. [#5803](https://github.com/heartcombo/devise/pull/5803) + * Remove deprecated `Devise::TestHelpers`, use `Devise::Test::ControllerHelpers` instead. [#5803](https://github.com/heartcombo/devise/pull/5803) + * Remove deprecated `Devise::Models::Authenticatable::BLACKLIST_FOR_SERIALIZATION` [#5598](https://github.com/heartcombo/devise/pull/5598) + * Remove deprecated `Devise.activerecord51?` method. + * Remove `SecretKeyFinder` and use `app.secret_key_base` as the default secret key for `Devise.secret_key` if a custom `Devise.secret_key` is not provided. -### 4.0.1 - 2016-04-25 + This is potentially a breaking change because Devise previously used the following order to find a secret key: -* bug fixes - * Fix the e-mail confirmation instructions send when a user updates the email - address from nil. (by @lmduc) - * Remove unnecessary `attribute_will_change!` call. (by @cadejscroggins) - * Consistent `permit!` check. (by @ulissesalmeida) + ``` + app.credentials.secret_key_base > app.secrets.secret_key_base > application.config.secret_key_base > application.secret_key_base + ``` -### 4.0.0 - 2016-04-18 + Now, it always uses `application.secret_key_base`. Make sure you're using the same secret key after the upgrade; otherwise, previously generated tokens for `recoverable`, `lockable`, and `confirmable` will be invalid. + [#5645](https://github.com/heartcombo/devise/pull/5645) + * Change password instructions button label on devise view from `Send me reset password instructions` to `Send me password reset instructions` [#5515](https://github.com/heartcombo/devise/pull/5515) + * Change `
` tags separating form elements to wrapping them in `

` tags [#5494](https://github.com/heartcombo/devise/pull/5494) + * Replace `[data-turbo-cache=false]` with `[data-turbo-temporary]` on `devise/shared/error_messages` partial. This has been [deprecated by Turbo since v7.3.0 (released on Mar 1, 2023)](https://github.com/hotwired/turbo/releases/tag/v7.3.0). -* bug fixes - * Fix the `extend_remember_period` configuration. When set to `false` it does - not update the cookie expiration anymore.(by @ulissesalmeida) - -* deprecations - * Added a warning of default value change in Devise 4.1 for users that uses - the the default configuration of the following configurations: (by @ulissesalmeida) - * `strip_whitespace_keys` - The default will be `[:email]`. - * `skip_session_storage` - The default will be `[:http_auth]`. - * `sign_out_via` - The default will be `:delete`. - * `reconfirmable` - The default will be `true`. - * `email_regexp` - The default will be `/\A[^@\s]+@[^@\s]+\z/`. - * Removed deprecated argument of `Devise::Models::Rememberable#remember_me!` (by @ulissesalmeida) - * Removed deprecated private method Devise::Controllers::Helpers#expire_session_data_after_sign_in! - (by @bogdanvlviv) - -### 4.0.0.rc2 - 2016-03-09 + If you are using an older version of Turbo and the default devise template, you'll need to copy it over to your app and change that back to `[data-turbo-cache=false]`. * enhancements - * Introduced `DeviseController#set_flash_message!` for conditional flash - messages setting to reduce complexity. - * `rails g devise:install` will fail if the app does not have a ORM configured - (by @arjunsharma) - * Support to Rails 5 versioned migrations added. - -* deprecations - * omniauth routes are no longer defined with a wildcard `:provider` parameter, - and provider specific routes are defined instead, so route helpers like `user_omniauth_authorize_path(:github)` are deprecated in favor of `user_github_omniauth_authorize_path`. - You can still use `omniauth_authorize_path(:user, :github)` if you need to - call the helpers dynamically. - -### 4.0.0.rc1 - 2016-02-01 - -* Support added to Rails 5 (by @twalpole). -* Devise no longer supports Rails 3.2 and 4.0. -* Devise no longer supports Ruby 1.9 and 2.0. - -* deprecations - * The `devise_parameter_sanitize` API has changed: - The `for` method was deprecated in favor of `permit`: - - ```ruby - def configure_permitted_parameters - devise_parameter_sanitizer.for(:sign_up) << :subscribe_newsletter - # Should become the following. - devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) - end - ``` + * Add Rails 8 support. + - Routes are lazy-loaded by default in test and development environments now so Devise loads them before `Devise.mappings` call. [#5728](https://github.com/heartcombo/devise/pull/5728) + * New apps using Rack 3.1+ will be generated using `config.responder.error_status = :unprocessable_content`, since [`:unprocessable_entity` has been deprecated by Rack](https://github.com/rack/rack/pull/2137). - The customization through instance methods on the sanitizer implementation - should be done through it's `initialize` method: + Latest versions of [Rails transparently convert `:unprocessable_entity` -> `:unprocessable_content`](https://github.com/rails/rails/pull/53383), and Devise will use that in the failure app to avoid Rack deprecation warnings for apps that are configured with `:unprocessable_entity`. They can also simply change their `error_status` to `:unprocessable_content` in latest Rack versions to avoid the warning. + * Add Ruby 3.4 and 4.0 support. + * Reenable Mongoid test suite across all Rails 7+ versions, to ensure we continue supporting it. Changes to dirty tracking to support Mongoid 8.0+. [#5568](https://github.com/heartcombo/devise/pull/5568) + * Password length validator is changed from - ```ruby - class User::ParameterSanitizer < Devise::ParameterSanitizer - def sign_up - default_params.permit(:username, :email) - end - end + ``` + validates_length_of :password, within: password_length, allow_blank: true` + ``` - # The `sign_up` method can be a `permit` call on the sanitizer `initialize`. + to - class User::ParameterSanitizer < Devise::ParameterSanitizer - def initialize(*) - super - permit(:sign_up, keys: [:username, :email]) - end - end ``` + validates_length_of :password, minimum: proc { password_length.min }, maximum: proc { password_length.max }, allow_blank: true + ``` + + so it's possible to override `password_length` at runtime. [#5734](https://github.com/heartcombo/devise/pull/5734) + +* bug fixes + * Make `Devise` work without `ActionMailer` when `Zeitwerk` autoloader is used. [#5731](https://github.com/heartcombo/devise/pull/5731) + * Handle defaults `:from` and `:reply_to` as procs correctly by delegating to Rails [#5595](https://github.com/heartcombo/devise/pull/5595) + * Use `OmniAuth.config.allowed_request_methods` as routing verbs for the auth path [#5508](https://github.com/heartcombo/devise/pull/5508) + * Handle `on` and `ON` as true values to check params [#5514](https://github.com/heartcombo/devise/pull/5514) + * Fix passing `format` option to `devise_for` [#5732](https://github.com/heartcombo/devise/pull/5732) + * Use `ActiveRecord::SecurityUtils.secure_compare` in `Devise.secure_compare` to match two empty strings correctly. [#4829](https://github.com/heartcombo/devise/pull/4829) + * Respond with `401 Unauthorized` for non-navigational requests to destroy the session when there is no authenticated resource. [#4878](https://github.com/heartcombo/devise/pull/4878) + * Fix incorrect grammar of invalid authentication message with capitalized attributes, e.g.: "Invalid Email or password" => "Invalid email or password". (originally introduced by [#4014](https://github.com/heartcombo/devise/pull/4014), released on v4.1.0) [#4834](https://github.com/heartcombo/devise/pull/4834) - You can check more examples and explanations on the [README section](/plataformatec/devise#strong-parameters) - and on the [ParameterSanitizer docs](lib/devise/parameter_sanitizer.rb). -Please check [3-stable](https://github.com/plataformatec/devise/blob/3-stable/CHANGELOG.md) +Please check [4-stable](https://github.com/heartcombo/devise/blob/4-stable/CHANGELOG.md) for previous changes. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index cae2742e1..3fc1d0982 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -17,6 +17,6 @@ Project maintainers have the right and responsibility to remove, edit, or reject This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by sending an email to [conduct@plataformatec.com.br](conduct@plataformatec.com.br) or contacting one or more of the project maintainers. +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/) +This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org), version 1.2.0, available at [https://contributor-covenant.org/version/1/2/0/](https://contributor-covenant.org/version/1/2/0/) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fb9dd7ad4..6327e4ddb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,7 @@ expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md). ## Reporting Issues 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/plataformatec/devise/issues). +reported or fixed by searching on GitHub through our [issues](https://github.com/heartcombo/devise/issues). When creating a new issue, be sure to include a **title and clear description**, as much relevant information as possible, and either a test case example or @@ -22,15 +22,15 @@ 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 -[Issues/Pull Requests](https://github.com/plataformatec/devise/issues?q=i18n) regarding +[Issues/Pull Requests](https://github.com/heartcombo/devise/issues?q=i18n) regarding internationalization. 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). +on [Stack Overflow](https://stackoverflow.com/questions/tagged/devise). **If you find a security bug, do not report it through GitHub. Please send an -e-mail to [opensource@plataformatec.com.br](mailto:opensource@plataformatec.com.br) +e-mail to [heartcombo.oss@gmail.com](mailto:heartcombo.oss@gmail.com) instead.** ## Sending Pull Requests @@ -50,7 +50,7 @@ are beneficial to a wide range of use cases or it's an application specific chan that might not be so valuable to other applications. Some changes can be introduced as a new `devise-something` gem instead of belonging to the main codebase. -When adding new settings, you can take advantage of the [`Devise::Models.config`](https://github.com/plataformatec/devise/blob/245b1f9de0b3386b7913e14b60ea24f43b77feb0/lib/devise/models.rb#L13-L50) method to add class and instance level fallbacks +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 @@ -64,9 +64,9 @@ open issues to help troubleshoot and fix existing bugs on Devise. Here is what you can do: * Help ensure that existing issues follows the recommendations from the -_[Reporting Issues](#reporting-issues)_ section, providing feeback to the issue's +_[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/plataformatec/devise/wiki) +* 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 diff --git a/Gemfile b/Gemfile index dc7b6b4ae..3fc8499f9 100644 --- a/Gemfile +++ b/Gemfile @@ -1,40 +1,33 @@ +# frozen_string_literal: true + source "https://rubygems.org" gemspec -gem "rails", "~> 5.1" -gem "omniauth", "~> 1.3" -gem "oauth2" +gem "omniauth" gem "omniauth-oauth2" +gem "rails", "~> 8.1.0" gem "rdoc" -gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml" - gem "rails-controller-testing" -gem "responders", "~> 2.1" - -# TODO: Remove this line when Rails 5.1.1 is released -gem "minitest", "< 5.10.2" +gem "responders", "~> 3.1" group :test do + gem "minitest", "< 6" + gem "mocha", "~> 2.1", require: false gem "omniauth-facebook" gem "omniauth-openid" - gem "webrat", "0.7.3", require: false - gem "mocha", "~> 1.1", require: false -end - -platforms :jruby do - gem "activerecord-jdbc-adapter" - gem "activerecord-jdbcsqlite3-adapter" - gem "jruby-openssl" + gem "rexml" + gem "timecop" + gem "webrat" + gem "ostruct" end platforms :ruby do gem "sqlite3" end -# TODO: -# group :mongoid do -# gem "mongoid", "~> 4.0.0" -# end +group :mongoid do + gem "mongoid", "~> 9.0", github: "mongodb/mongoid", branch: "9.0-stable" +end diff --git a/Gemfile.lock b/Gemfile.lock index 9b012392a..a6fdb5a71 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,194 +1,314 @@ GIT - remote: git://github.com/rails/activemodel-serializers-xml.git - revision: dd9c0acf26aab111ebc647cd8deb99ebc6946531 + remote: https://github.com/mongodb/mongoid.git + revision: 0623af687a234392ed4b8872f474a9208b908500 + branch: 9.0-stable specs: - activemodel-serializers-xml (1.0.1) - activemodel (> 5.x) - activesupport (> 5.x) - builder (~> 3.1) + mongoid (9.0.10) + activemodel (>= 5.1, < 8.2, != 7.0.0) + concurrent-ruby (>= 1.0.5, < 2.0) + mongo (>= 2.18.0, < 3.0.0) PATH remote: . specs: - devise (4.3.0) + devise (5.0.4) bcrypt (~> 3.0) orm_adapter (~> 0.1) - railties (>= 4.1.0, < 5.2) + railties (>= 7.0) responders warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: - actioncable (5.1.0) - actionpack (= 5.1.0) + action_text-trix (2.1.18) + railties + actioncable (8.1.3) + actionpack (= 8.1.3) + activesupport (= 8.1.3) nio4r (~> 2.0) - websocket-driver (~> 0.6.1) - actionmailer (5.1.0) - actionpack (= 5.1.0) - actionview (= 5.1.0) - activejob (= 5.1.0) - mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 2.0) - actionpack (5.1.0) - actionview (= 5.1.0) - activesupport (= 5.1.0) - rack (~> 2.0) - rack-test (~> 0.6.3) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.0.2) - actionview (5.1.0) - activesupport (= 5.1.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.3) + actionpack (= 8.1.3) + activejob (= 8.1.3) + activerecord (= 8.1.3) + activestorage (= 8.1.3) + activesupport (= 8.1.3) + mail (>= 2.8.0) + actionmailer (8.1.3) + actionpack (= 8.1.3) + actionview (= 8.1.3) + activejob (= 8.1.3) + activesupport (= 8.1.3) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.3) + actionview (= 8.1.3) + activesupport (= 8.1.3) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.1.3) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.3) + activerecord (= 8.1.3) + activestorage (= 8.1.3) + activesupport (= 8.1.3) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.3) + activesupport (= 8.1.3) builder (~> 3.1) - erubi (~> 1.4) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.0.3) - activejob (5.1.0) - activesupport (= 5.1.0) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.3) + activesupport (= 8.1.3) globalid (>= 0.3.6) - activemodel (5.1.0) - activesupport (= 5.1.0) - activerecord (5.1.0) - activemodel (= 5.1.0) - activesupport (= 5.1.0) - arel (~> 8.0) - activesupport (5.1.0) - concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (~> 0.7) - minitest (~> 5.1) - tzinfo (~> 1.1) - arel (8.0.0) - bcrypt (3.1.11) - builder (3.2.3) - concurrent-ruby (1.0.5) - erubi (1.6.0) - faraday (0.11.0) - multipart-post (>= 1.2, < 3) - globalid (0.4.0) - activesupport (>= 4.2.0) - hashie (3.5.5) - i18n (0.8.1) - jwt (1.5.6) - loofah (2.0.3) - nokogiri (>= 1.5.9) - mail (2.6.5) - mime-types (>= 1.16, < 4) - metaclass (0.0.4) - method_source (0.8.2) - mime-types (3.1) - mime-types-data (~> 3.2015) - mime-types-data (3.2016.0521) - mini_portile2 (2.1.0) - minitest (5.10.1) - mocha (1.2.1) - metaclass (~> 0.0.1) - multi_json (1.12.1) - multi_xml (0.6.0) - multipart-post (2.0.0) - nio4r (2.0.0) - nokogiri (1.7.1) - mini_portile2 (~> 2.1.0) - oauth2 (1.3.1) - faraday (>= 0.8, < 0.12) - jwt (~> 1.0) - multi_json (~> 1.3) + activemodel (8.1.3) + activesupport (= 8.1.3) + activerecord (8.1.3) + activemodel (= 8.1.3) + activesupport (= 8.1.3) + timeout (>= 0.4.0) + activestorage (8.1.3) + actionpack (= 8.1.3) + activejob (= 8.1.3) + activerecord (= 8.1.3) + activesupport (= 8.1.3) + marcel (~> 1.0) + activesupport (8.1.3) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + base64 (0.3.0) + bcrypt (3.1.22) + bigdecimal (4.0.1) + bson (5.2.0) + builder (3.3.0) + concurrent-ruby (1.3.6) + connection_pool (3.0.2) + crass (1.0.6) + date (3.5.1) + drb (2.2.3) + erb (6.0.2) + erubi (1.13.1) + faraday (2.14.1) + faraday-net_http (>= 2.0, < 3.5) + json + logger + faraday-net_http (3.4.2) + net-http (~> 0.5) + globalid (1.3.0) + activesupport (>= 6.1) + hashie (5.1.0) + logger + i18n (1.14.8) + concurrent-ruby (~> 1.0) + io-console (0.8.2) + irb (1.17.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (2.19.3) + jwt (3.1.2) + base64 + logger (1.7.0) + loofah (2.25.1) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.0) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.1.0) + mini_mime (1.1.5) + mini_portile2 (2.8.9) + minitest (5.27.0) + mocha (2.8.2) + ruby2_keywords (>= 0.0.5) + mongo (2.23.0) + base64 + bson (>= 4.14.1, < 6.0.0) + multi_xml (0.8.1) + bigdecimal (>= 3.1, < 5) + net-http (0.9.1) + uri (>= 0.11.1) + net-imap (0.6.3) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.5.1) + net-protocol + nio4r (2.7.5) + nokogiri (1.19.2) + mini_portile2 (~> 2.8.2) + racc (~> 1.4) + oauth2 (2.0.18) + faraday (>= 0.17.3, < 4.0) + jwt (>= 1.0, < 4.0) + logger (~> 1.2) multi_xml (~> 0.5) - rack (>= 1.2, < 3) - omniauth (1.6.1) - hashie (>= 3.4.6, < 3.6.0) - rack (>= 1.6.2, < 3) - omniauth-facebook (4.0.0) - omniauth-oauth2 (~> 1.2) - omniauth-oauth2 (1.4.0) - oauth2 (~> 1.0) - omniauth (~> 1.2) - omniauth-openid (1.0.1) - omniauth (~> 1.0) - rack-openid (~> 1.3.1) + rack (>= 1.2, < 4) + snaky_hash (~> 2.0, >= 2.0.3) + version_gem (~> 1.1, >= 1.1.9) + omniauth (2.1.4) + hashie (>= 3.4.6) + logger + rack (>= 2.2.3) + rack-protection + omniauth-facebook (10.0.0) + bigdecimal + omniauth-oauth2 (>= 1.2, < 3) + omniauth-oauth2 (1.9.0) + oauth2 (>= 2.0.2, < 3) + omniauth (~> 2.0) + omniauth-openid (2.0.2) + omniauth (>= 1.1) + rack-openid (~> 1.4) + ruby-openid (~> 2.1, >= 2.1.8) + version_gem (~> 1.1, >= 1.1.8) orm_adapter (0.5.0) - rack (2.0.1) - rack-openid (1.3.1) + ostruct (0.6.3) + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.9.0) + psych (5.3.1) + date + stringio + racc (1.8.1) + rack (3.2.5) + rack-openid (1.4.2) rack (>= 1.1.0) ruby-openid (>= 2.1.8) - rack-test (0.6.3) - rack (>= 1.0) - rails (5.1.0) - actioncable (= 5.1.0) - actionmailer (= 5.1.0) - actionpack (= 5.1.0) - actionview (= 5.1.0) - activejob (= 5.1.0) - activemodel (= 5.1.0) - activerecord (= 5.1.0) - activesupport (= 5.1.0) - bundler (>= 1.3.0, < 2.0) - railties (= 5.1.0) - sprockets-rails (>= 2.0.0) - rails-controller-testing (1.0.1) - actionpack (~> 5.x) - actionview (~> 5.x) - activesupport (~> 5.x) - rails-dom-testing (2.0.2) - activesupport (>= 4.2.0, < 6.0) - nokogiri (~> 1.6) - rails-html-sanitizer (1.0.3) - loofah (~> 2.0) - railties (5.1.0) - actionpack (= 5.1.0) - activesupport (= 5.1.0) - method_source - rake (>= 0.8.7) - thor (>= 0.18.1, < 2.0) - rake (12.0.0) - rdoc (5.1.0) - responders (2.4.0) - actionpack (>= 4.2.0, < 5.3) - railties (>= 4.2.0, < 5.3) - ruby-openid (2.7.0) - sprockets (3.7.1) + rack-protection (4.2.1) + base64 (>= 0.1.0) + logger (>= 1.6.0) + rack (>= 3.0.0, < 4) + rack-session (2.1.1) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.3.1) + rack (>= 3) + rails (8.1.3) + actioncable (= 8.1.3) + actionmailbox (= 8.1.3) + actionmailer (= 8.1.3) + actionpack (= 8.1.3) + actiontext (= 8.1.3) + actionview (= 8.1.3) + activejob (= 8.1.3) + activemodel (= 8.1.3) + activerecord (= 8.1.3) + activestorage (= 8.1.3) + activesupport (= 8.1.3) + bundler (>= 1.15.0) + railties (= 8.1.3) + rails-controller-testing (1.0.5) + actionpack (>= 5.0.1.rc1) + actionview (>= 5.0.1.rc1) + activesupport (>= 5.0.1.rc1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.0) + loofah (~> 2.25) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.3) + actionpack (= 8.1.3) + activesupport (= 8.1.3) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rake (13.3.1) + rdoc (7.2.0) + erb + psych (>= 4.0.0) + tsort + reline (0.6.3) + io-console (~> 0.5) + responders (3.2.0) + actionpack (>= 7.0) + railties (>= 7.0) + rexml (3.4.4) + ruby-openid (2.9.2) + ruby2_keywords (0.0.5) + securerandom (0.4.1) + snaky_hash (2.0.3) + hashie (>= 0.1.0, < 6) + version_gem (>= 1.1.8, < 3) + sqlite3 (2.9.2) + mini_portile2 (~> 2.8.0) + stringio (3.2.0) + thor (1.5.0) + timecop (0.9.10) + timeout (0.6.1) + tsort (0.2.0) + tzinfo (2.0.6) concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (3.2.0) - actionpack (>= 4.0) - activesupport (>= 4.0) - sprockets (>= 3.0.0) - sqlite3 (1.3.13) - thor (0.19.4) - thread_safe (0.3.6) - tzinfo (1.2.3) - thread_safe (~> 0.1) - warden (1.2.7) - rack (>= 1.0) + uri (1.1.1) + useragent (0.16.11) + version_gem (1.1.9) + warden (1.2.9) + rack (>= 2.0.9) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) - websocket-driver (0.6.5) + websocket-driver (0.8.0) + base64 websocket-extensions (>= 0.1.0) - websocket-extensions (0.1.2) + websocket-extensions (0.1.5) + zeitwerk (2.7.5) PLATFORMS ruby DEPENDENCIES - activemodel-serializers-xml! - activerecord-jdbc-adapter - activerecord-jdbcsqlite3-adapter devise! - jruby-openssl - minitest (< 5.10.2) - mocha (~> 1.1) - oauth2 - omniauth (~> 1.3) + minitest (< 6) + mocha (~> 2.1) + mongoid (~> 9.0)! + omniauth omniauth-facebook omniauth-oauth2 omniauth-openid - rails (~> 5.1) + ostruct + rails (~> 8.1.0) rails-controller-testing rdoc - responders (~> 2.1) + responders (~> 3.1) + rexml sqlite3 - webrat (= 0.7.3) + timecop + webrat BUNDLED WITH - 1.14.6 + 4.0.3 diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..445eedba5 --- /dev/null +++ b/ISSUE_TEMPLATE.md @@ -0,0 +1,20 @@ +## Pre-check + +- Do not use the issues tracker for help or support, try Stack Overflow. +- For bugs, do a quick search and make sure the bug has not yet been reported +- If you found a security bug, do not report it through GitHub. Please send an e-mail to heartcombo.oss@gmail.com instead. +- Finally, be nice and have fun! + +## Environment + +- Ruby **[version]** +- Rails **[version]** +- Devise **[version]** + +## Current behavior + +Include code samples, errors, steps to reproduce the error and stack traces if appropriate. + +Will be even more helpful if you provide a sample application or a test case that reproduces the error. + +## Expected behavior diff --git a/MIT-LICENSE b/MIT-LICENSE index 73b88e91c..ad599708f 100644 --- a/MIT-LICENSE +++ b/MIT-LICENSE @@ -1,4 +1,5 @@ -Copyright 2009-2017 Plataformatec. http://plataformatec.com.br +Copyright (c) 2020-CURRENT Rafael França, Carlos Antonio da Silva +Copyright (c) 2009-2019 Plataformatec Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md index 19c9d6a30..37e2d3160 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,4 @@ -![Devise Logo](https://raw.github.com/plataformatec/devise/master/devise.png) - -By [Plataformatec](http://plataformatec.com.br/). - -[![Build Status](https://api.travis-ci.org/plataformatec/devise.svg?branch=master)](http://travis-ci.org/plataformatec/devise) -[![Code Climate](https://codeclimate.com/github/plataformatec/devise.svg)](https://codeclimate.com/github/plataformatec/devise) - -This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/). +![Devise Logo](https://raw.github.com/heartcombo/devise/main/devise.png) Devise is a flexible authentication solution for Rails based on Warden. It: @@ -16,16 +9,55 @@ Devise is a flexible authentication solution for Rails based on Warden. It: It's composed of 10 modules: -* [Database Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): hashes and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication. -* [Omniauthable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Omniauthable): adds OmniAuth (https://github.com/omniauth/omniauth) support. -* [Confirmable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in. -* [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions. -* [Registerable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account. -* [Rememberable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie. -* [Trackable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address. -* [Timeoutable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have not been active in a specified period of time. -* [Validatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations. -* [Lockable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period. +* [Database Authenticatable](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. +* [Omniauthable](https://www.rubydoc.info/gems/devise/Devise/Models/Omniauthable): adds OmniAuth (https://github.com/omniauth/omniauth) support. +* [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. + +## Table of Contents + + + +- [Information](#information) + - [The Devise wiki](#the-devise-wiki) + - [Bug reports](#bug-reports) + - [StackOverflow and Mailing List](#stackoverflow-and-mailing-list) + - [RDocs](#rdocs) + - [Example applications](#example-applications) + - [Extensions](#extensions) + - [Supported Ruby / Rails versions](#supported-ruby--rails-versions) + - [Contributing](#contributing) +- [Starting with Rails?](#starting-with-rails) +- [Getting started](#getting-started) + - [Controller filters and helpers](#controller-filters-and-helpers) + - [Configuring Models](#configuring-models) + - [Strong Parameters](#strong-parameters) + - [Configuring views](#configuring-views) + - [Configuring controllers](#configuring-controllers) + - [Configuring routes](#configuring-routes) + - [I18n](#i18n) + - [Test helpers](#test-helpers) + - [Controller tests](#controller-tests) + - [Integration tests](#integration-tests) + - [OmniAuth](#omniauth) + - [Configuring multiple models](#configuring-multiple-models) + - [Active Job Integration](#active-job-integration) + - [Password reset tokens and Rails logs](#password-reset-tokens-and-rails-logs) + - [Other ORMs](#other-orms) + - [Rails API mode](#rails-api-mode) +- [Additional information](#additional-information) + - [Warden](#warden) +- [License](#license) + + + + ## Information @@ -33,31 +65,32 @@ It's composed of 10 modules: The Devise Wiki has lots of additional information about Devise including many "how-to" articles and answers to the most frequently asked questions. Please browse the Wiki after finishing this README: -https://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: -https://github.com/plataformatec/devise/wiki/Bug-reports +https://github.com/heartcombo/devise/wiki/Bug-reports -If you have discovered a security related bug, please do *NOT* use the GitHub issue tracker. Send an email to opensource@plataformatec.com.br. +If you have discovered a security related bug, please do *NOT* use the GitHub issue tracker. Send an email to heartcombo.oss@gmail.com. ### StackOverflow and Mailing List If you have any questions, comments, or concerns, please use StackOverflow instead of the GitHub issue tracker: -http://stackoverflow.com/questions/tagged/devise +https://stackoverflow.com/questions/tagged/devise -The deprecated mailing list can still be read on +The deprecated mailing lists can still be read on: https://groups.google.com/group/plataformatec-devise +https://groups.google.com/group/heartcombo ### RDocs You can view the Devise documentation in RDoc format here: -http://rubydoc.info/github/plataformatec/devise/master/frames +https://rubydoc.info/github/heartcombo/devise/main/frames If you need to use Devise with previous versions of Rails, you can always run "gem server" from the command line after you install the gem to access the old documentation. @@ -65,46 +98,99 @@ 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: -https://github.com/plataformatec/devise/wiki/Example-Applications +https://github.com/heartcombo/devise/wiki/Example-Applications ### Extensions Our community has created a number of extensions that add functionality above and beyond what is included with Devise. You can view a list of available extensions and add your own here: -https://github.com/plataformatec/devise/wiki/Extensions +https://github.com/heartcombo/devise/wiki/Extensions + +### Supported Ruby / Rails versions + +We intend to maintain support for all Ruby / Rails versions that haven't reached end-of-life. + +For more information about specific versions please check [Ruby](https://www.ruby-lang.org/en/downloads/branches/) +and [Rails](https://guides.rubyonrails.org/maintenance_policy.html) maintenance policies, and our test matrix. ### Contributing We hope that you will consider contributing to Devise. Please read this short overview for some information about how to get started: -https://github.com/plataformatec/devise/wiki/Contributing +https://github.com/heartcombo/devise/wiki/Contributing + +You will usually want to write tests for your changes. To run the test suite, go into Devise's top-level directory and 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. +BUNDLE_GEMFILE=gemfiles/Gemfile-rails-8-0 bundle install +BUNDLE_GEMFILE=gemfiles/Gemfile-rails-8-0 bin/test +``` + +You can also combine both of them if the tests broke for Mongoid: +```bash +BUNDLE_GEMFILE=gemfiles/Gemfile-rails-8-0 bundle install +BUNDLE_GEMFILE=gemfiles/Gemfile-rails-8-0 DEVISE_ORM=mongoid bin/test +``` -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. +### Running tests +Devise uses [minitest](https://github.com/seattlerb/minitest) as test framework. + +* Running all tests: +```bash +bin/test +``` + +* Running tests for an specific file: +```bash +bin/test test/models/trackable_test.rb +``` + +* Running a specific test given a line number or a regex: +```bash +bin/test test/models/trackable_test.rb:16 +bin/test test/models/trackable_test.rb -n '/update.*record/' +``` ## Starting with Rails? -If you are building your first Rails application, we recommend you *do not* use Devise. Devise requires a good understanding of the Rails Framework. In such cases, we advise you to start a simple authentication system from scratch. Today, we have three resources that should help you get started: +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: https://www.railstutorial.org/book/modeling_users -* Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch -* Codecademy's Ruby on Rails: Authentication and Authorization: http://www.codecademy.com/en/learn/rails-auth +* 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. :smiley: ## Getting started -Devise 4.0 works with Rails 4.1 onwards. You can add it to your Gemfile with: +Devise 5 works with Rails 7 onwards. Run: -```ruby -gem 'devise' +```sh +bundle add devise ``` -Then run `bundle install` - Next, you need to run the generator: ```console -$ rails generate devise:install +rails generate devise:install ``` At this point, a number of instructions will appear in the console. Among these instructions, you'll need to set up the default URL options for the Devise mailer in each environment. Here is a possible configuration for `config/environments/development.rb`: @@ -119,14 +205,14 @@ The generator will install an initializer which describes ALL of Devise's config In the following command you will replace `MODEL` with the class name used for the application’s users (it’s frequently `User` but could also be `Admin`). This will create a model (if one does not exist) and configure it with the default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller. ```console -$ rails generate devise MODEL +rails generate devise MODEL ``` -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. +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. Otherwise, you will run into strange errors, for example, users being unable to login and route helpers being undefined. +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 @@ -183,16 +269,16 @@ member_session The Devise method in your models also accepts some options to configure its modules. For example, you can choose the cost of the hashing algorithm with: ```ruby -devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 12 +devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 13 ``` Besides `:stretches`, you can define `:pepper`, `:encryptor`, `:confirm_within`, `:remember_for`, `:timeout_in`, `:unlock_in` among other options. For more details, see the initializer file that was created when you invoked the "devise:install" generator described above. This file is usually located at `/config/initializers/devise.rb`. ### Strong Parameters -![The Parameter Sanitizer API has changed for Devise 4](http://messages.hellobits.com/warning.svg?message=The%20Parameter%20Sanitizer%20API%20has%20changed%20for%20Devise%204) +The Parameter Sanitizer API has changed for Devise 4 :warning: -*For previous Devise versions see https://github.com/plataformatec/devise/tree/3-stable#strong-parameters* +*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. @@ -202,7 +288,7 @@ There are just three actions in Devise that allow any set of parameters to be pa * `sign_up` (`Devise::RegistrationsController#create`) - Permits authentication keys plus `password` and `password_confirmation` * `account_update` (`Devise::RegistrationsController#update`) - Permits authentication keys plus `password`, `password_confirmation` and `current_password` -In case you want to permit additional parameters (the lazy way™), you can do so using a simple before filter in your `ApplicationController`: +In case you want to permit additional parameters (the lazy way™), you can do so using a simple before action in your `ApplicationController`: ```ruby class ApplicationController < ActionController::Base @@ -216,7 +302,21 @@ class ApplicationController < ActionController::Base end ``` -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: + +```ruby +class ApplicationController < ActionController::Base + before_action :configure_permitted_parameters, if: :devise_controller? + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, address_attributes: [:country, :state, :city, :area, :postal_code]]) + end +end +``` + +Devise allows you to completely change Devise defaults or invoke custom behavior by passing a block: To permit simple scalar values for username and email, use this @@ -277,7 +377,7 @@ We built Devise to help you quickly develop an application that uses authenticat Since Devise is an engine, all its views are packaged inside the gem. These views will help you get started, but after some time you may want to change them. If this is the case, you just need to invoke the following generator, and it will copy all views to your application: ```console -$ rails generate devise:views +rails generate devise:views ``` If you have more than one Devise model in your application (such as `User` and `Admin`), you will notice that Devise uses the same views for all models. Fortunately, Devise offers an easy way to customize views. All you need to do is set `config.scoped_views = true` inside the `config/initializers/devise.rb` file. @@ -285,14 +385,14 @@ If you have more than one Devise model in your application (such as `User` and ` After doing so, you will be able to have views based on the role like `users/sessions/new` and `admins/sessions/new`. If no view is found within the scope, Devise will use the default view at `devise/sessions/new`. You can also use the generator to generate scoped views: ```console -$ rails generate devise:views users +rails generate devise:views users ``` If you would like to generate only a few sets of views, like the ones for the `registerable` and `confirmable` module, -you can pass a list of modules to the generator with the `-v` flag. +you can pass a list of views to the generator with the `-v` flag. ```console -$ rails generate devise:views -v registrations confirmations +rails generate devise:views -v registrations confirmations ``` ### Configuring controllers @@ -302,7 +402,7 @@ If the customization at the views level is not enough, you can customize each co 1. Create your custom controllers using the generator which requires a scope: ```console - $ rails generate devise:controllers [scope] + rails generate devise:controllers [scope] ``` If you specify `users` as the scope, controllers will be created in `app/controllers/users/`. @@ -317,6 +417,7 @@ If the customization at the views level is not enough, you can customize each co ... end ``` + Use the `-c` flag to specify one or more controllers, for example: `rails generate devise:controllers users -c sessions` 2. Tell the router to use this controller: @@ -324,7 +425,7 @@ If the customization at the views level is not enough, you can customize each co devise_for :users, controllers: { sessions: 'users/sessions' } ``` -3. Copy the views from `devise/sessions` to `users/sessions`. Since the controller was changed, it won't use the default views located in `devise/sessions`. +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. @@ -338,7 +439,7 @@ If the customization at the views level is not enough, you can customize each co end ``` - Or you can simply add new behaviour to it: + Or you can simply add new behavior to it: ```ruby class Users::SessionsController < Devise::SessionsController @@ -362,7 +463,7 @@ Devise also ships with default routes. If you need to customize them, you should devise_for :users, path: 'auth', path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unblock', registration: 'register', sign_up: 'cmon_let_me_in' } ``` -Be sure to check `devise_for` [documentation](http://www.rubydoc.info/github/plataformatec/devise/master/ActionDispatch/Routing/Mapper%3Adevise_for) 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 create your routes normally and wrap them in a `devise_scope` block in the router: @@ -374,6 +475,43 @@ 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. +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, in conjunction with the flash keys :notice and :alert. To customize your app, you can set up your locale file: @@ -412,7 +550,7 @@ 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. @@ -424,12 +562,21 @@ cases/specs. ### Controller tests -Controller tests require that you include `Devise::Test::ControllerHelpers` on +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 PostsControllerTest < ActionController::TestCase - include Devise::Test::ControllerHelpers + include Devise::Test::IntegrationHelpers # Rails >= 5 +end +``` + +```ruby +class PostsControllerTest < ActionController::TestCase + include Devise::Test::ControllerHelpers # Rails < 5 end ``` @@ -507,9 +654,9 @@ Unlike controller tests, integration tests do not need to supply the `devise.mapping` `env` value, as the mapping can be inferred by the routes that are executed in your tests. -You can read more about testing your Rails 3 - Rails 4 controllers with RSpec in the wiki: +You can read more about testing your Rails controllers with RSpec in the wiki: -* https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29 +* https://github.com/heartcombo/devise/wiki/How-To:-Test-controllers-with-Rails-(and-RSpec) ### OmniAuth @@ -521,7 +668,7 @@ config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' You can read more about OmniAuth support in the wiki: -* https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview +* https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview ### Configuring multiple models @@ -554,9 +701,9 @@ Alternatively, you can simply run the Devise generator. Keep in mind that those models will have completely different routes. They **do not** and **cannot** share the same controller for sign in, sign out and so on. In case you want to have different roles sharing the same actions, we recommend that you use a role-based approach, by either providing a role column or using a dedicated gem for authorization. -### ActiveJob Integration +### Active Job Integration -If you are using Rails 4.2 and ActiveJob to deliver ActionMailer messages in the +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. @@ -568,12 +715,12 @@ end ### Password reset tokens and Rails logs -If you enable the [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable) module, note that a stolen password reset token could give an attacker access to your application. Devise takes effort to generate random, secure tokens, and stores only token digests in the database, never plaintext. However the default logging behavior in Rails can cause plaintext tokens to leak into log files: +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 DEBUG by default. Consider changing your production logger level to WARN if you wish to prevent tokens from being leaked into your logs. In `config/environments/production.rb`: +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 @@ -584,32 +731,46 @@ config.log_level = :warn 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.2 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](https://blog.plataformatec.com.br/2019/01/custom-authentication-methods-with-devise/). -### Warden +#### 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: -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: +```ruby +Rails.application.config.middleware.insert_before Warden::Manager, ActionDispatch::Cookies +Rails.application.config.middleware.insert_before Warden::Manager, ActionDispatch::Session::CookieStore +``` + +For a deeper understanding of this, review [this issue](https://github.com/heartcombo/devise/issues/4696). -https://github.com/hassox/warden +Additionally be mindful that without views supported, some email-based flows from Confirmable, Recoverable and Lockable are not supported directly at this time. -### Contributors +## Additional information + +### Warden -We have a long list of valued contributors. Check them all at: +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/plataformatec/devise/graphs/contributors +https://github.com/wardencommunity/warden ## License -MIT License. Copyright 2009-2017 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 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/). diff --git a/Rakefile b/Rakefile index bbf716633..6e2ab1802 100644 --- a/Rakefile +++ b/Rakefile @@ -1,4 +1,5 @@ # encoding: UTF-8 +# frozen_string_literal: true require 'bundler/gem_tasks' require 'rake/testtask' diff --git a/app/controllers/devise/confirmations_controller.rb b/app/controllers/devise/confirmations_controller.rb index 4981545a3..39ff669be 100644 --- a/app/controllers/devise/confirmations_controller.rb +++ b/app/controllers/devise/confirmations_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Devise::ConfirmationsController < DeviseController # GET /resource/confirmation/new def new @@ -25,6 +27,7 @@ def show set_flash_message!(:notice, :confirmed) respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) } else + # TODO: use `error_status` when the default changes to `:unprocessable_entity` / `:unprocessable_content`. respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new } end end diff --git a/app/controllers/devise/omniauth_callbacks_controller.rb b/app/controllers/devise/omniauth_callbacks_controller.rb index d5b2c094e..a9a2c30ea 100644 --- a/app/controllers/devise/omniauth_callbacks_controller.rb +++ b/app/controllers/devise/omniauth_callbacks_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Devise::OmniauthCallbacksController < DeviseController prepend_before_action { request.env["devise.skip_timeout"] = true } @@ -6,7 +8,7 @@ def passthru end def failure - set_flash_message :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message + set_flash_message! :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message redirect_to after_omniauth_failure_path_for(resource_name) end diff --git a/app/controllers/devise/passwords_controller.rb b/app/controllers/devise/passwords_controller.rb index f4291c76a..68b8dc877 100644 --- a/app/controllers/devise/passwords_controller.rb +++ b/app/controllers/devise/passwords_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Devise::PasswordsController < DeviseController prepend_before_action :require_no_authentication # Render the #edit only if coming from a reset password email link @@ -34,9 +36,10 @@ def update if resource.errors.empty? resource.unlock_access! if unlockable?(resource) - if Devise.sign_in_after_reset_password + if sign_in_after_reset_password? flash_message = resource.active_for_authentication? ? :updated : :updated_not_active set_flash_message!(:notice, flash_message) + resource.after_database_authentication sign_in(resource_name, resource) else set_flash_message!(:notice, :updated_not_active) @@ -50,7 +53,7 @@ def update protected def after_resetting_password_path_for(resource) - Devise.sign_in_after_reset_password ? after_sign_in_path_for(resource) : new_session_path(resource_name) + sign_in_after_reset_password? ? after_sign_in_path_for(resource) : new_session_path(resource_name) end # The path used after sending reset password instructions @@ -66,6 +69,11 @@ def assert_reset_token_passed end end + # Check if the user should be signed in automatically after resetting the password. + def sign_in_after_reset_password? + resource_class.sign_in_after_reset_password + end + # Check if proper Lockable module methods are present & unlock strategy # allows to unlock resource on password reset def unlockable?(resource) diff --git a/app/controllers/devise/registrations_controller.rb b/app/controllers/devise/registrations_controller.rb index 31ba0887b..79e2b0e81 100644 --- a/app/controllers/devise/registrations_controller.rb +++ b/app/controllers/devise/registrations_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Devise::RegistrationsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create, :cancel] prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy] @@ -5,7 +7,7 @@ class Devise::RegistrationsController < DeviseController # GET /resource/sign_up def new - build_resource({}) + build_resource yield resource if block_given? respond_with resource end @@ -48,12 +50,9 @@ def update resource_updated = update_resource(resource, account_update_params) yield resource if block_given? if resource_updated - if is_flashing_format? - flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ? - :update_needs_confirmation : :updated - set_flash_message :notice, flash_key - end - bypass_sign_in resource, scope: resource_name + set_flash_message_for_update(resource, prev_unconfirmed_email) + bypass_sign_in resource, scope: resource_name if sign_in_after_change_password? + respond_with resource, location: after_update_path_for(resource) else clean_up_passwords resource @@ -68,7 +67,7 @@ def destroy Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name) set_flash_message! :notice, :destroyed yield resource if block_given? - respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) } + respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name), status: Devise.responder.redirect_status } end # GET /resource/cancel @@ -83,12 +82,6 @@ def cancel protected - def update_needs_confirmation?(resource, previous) - resource.respond_to?(:pending_reconfirmation?) && - resource.pending_reconfirmation? && - previous != resource.unconfirmed_email - end - # By default we want to require a password checks on update. # You can overwrite this method in your own RegistrationsController. def update_resource(resource, params) @@ -97,8 +90,8 @@ def update_resource(resource, params) # Build a devise resource passing in the session. Useful to move # temporary session data to the newly created user. - def build_resource(hash=nil) - self.resource = resource_class.new_with_session(hash || {}, session) + def build_resource(hash = {}) + self.resource = resource_class.new_with_session(hash, session) end # Signs in a user on sign up. You can overwrite this method in your own @@ -110,7 +103,7 @@ def sign_up(resource_name, resource) # The path used after sign up. You need to overwrite this method # in your own RegistrationsController. def after_sign_up_path_for(resource) - after_sign_in_path_for(resource) + after_sign_in_path_for(resource) if is_navigational_format? end # The path used after sign up for inactive accounts. You need to overwrite @@ -125,7 +118,7 @@ def after_inactive_sign_up_path_for(resource) # The default url to be used after updating a resource. You need to overwrite # this method in your own RegistrationsController. def after_update_path_for(resource) - signed_in_root_path(resource) + sign_in_after_change_password? ? signed_in_root_path(resource) : new_session_path(resource_name) end # Authenticates the current scope and gets the current resource from the session. @@ -134,6 +127,13 @@ def authenticate_scope! self.resource = send(:"current_#{resource_name}") end + # Check if the user should be signed in automatically after updating the password. + def sign_in_after_change_password? + return true if account_update_params[:password].blank? + + resource_class.sign_in_after_change_password + end + def sign_up_params devise_parameter_sanitizer.sanitize(:sign_up) end @@ -145,4 +145,25 @@ def account_update_params def translation_scope 'devise.registrations' end + + private + + def set_flash_message_for_update(resource, prev_unconfirmed_email) + return unless is_flashing_format? + + flash_key = if update_needs_confirmation?(resource, prev_unconfirmed_email) + :update_needs_confirmation + elsif sign_in_after_change_password? + :updated + else + :updated_but_not_signed_in + end + set_flash_message :notice, flash_key + end + + def update_needs_confirmation?(resource, previous) + resource.respond_to?(:pending_reconfirmation?) && + resource.pending_reconfirmation? && + previous != resource.unconfirmed_email + end end diff --git a/app/controllers/devise/sessions_controller.rb b/app/controllers/devise/sessions_controller.rb index d0ddf7506..41b74f39c 100644 --- a/app/controllers/devise/sessions_controller.rb +++ b/app/controllers/devise/sessions_controller.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + class Devise::SessionsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create] prepend_before_action :allow_params_authentication!, only: :create prepend_before_action :verify_signed_out_user, only: :destroy - prepend_before_action only: [:create, :destroy] { request.env["devise.skip_timeout"] = true } + prepend_before_action(only: [:create, :destroy]) { request.env["devise.skip_timeout"] = true } # GET /resource/sign_in def new @@ -26,7 +28,7 @@ def destroy signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)) set_flash_message! :notice, :signed_out if signed_out yield if block_given? - respond_to_on_destroy + respond_to_on_destroy(non_navigational_status: :no_content) end protected @@ -43,7 +45,7 @@ def serialize_options(resource) end def auth_options - { scope: resource_name, recall: "#{controller_path}#new" } + { scope: resource_name, recall: "#{controller_path}#new", locale: I18n.locale } end def translation_scope @@ -60,7 +62,7 @@ def verify_signed_out_user if all_signed_out? set_flash_message! :notice, :already_signed_out - respond_to_on_destroy + respond_to_on_destroy(non_navigational_status: :unauthorized) end end @@ -70,12 +72,12 @@ def all_signed_out? users.all?(&:blank?) end - def respond_to_on_destroy + def respond_to_on_destroy(non_navigational_status: :no_content) # We actually need to hardcode this as Rails default responder doesn't # support returning empty response on GET request respond_to do |format| - format.all { head :no_content } - format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name) } + format.all { head non_navigational_status } + format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name), status: Devise.responder.redirect_status } end end end diff --git a/app/controllers/devise/unlocks_controller.rb b/app/controllers/devise/unlocks_controller.rb index 179c9525f..8cff126c9 100644 --- a/app/controllers/devise/unlocks_controller.rb +++ b/app/controllers/devise/unlocks_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Devise::UnlocksController < DeviseController prepend_before_action :require_no_authentication @@ -27,6 +29,7 @@ def show set_flash_message! :notice, :unlocked respond_with_navigational(resource){ redirect_to after_unlock_path_for(resource) } else + # TODO: use `error_status` when the default changes to `:unprocessable_entity` / `:unprocessable_content`. respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new } end end diff --git a/app/controllers/devise_controller.rb b/app/controllers/devise_controller.rb index 0679a62e6..1c3b41626 100644 --- a/app/controllers/devise_controller.rb +++ b/app/controllers/devise_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # All Devise controllers are inherited from here. class DeviseController < Devise.parent_controller.constantize include Devise::Controllers::ScopedViews @@ -13,6 +15,7 @@ class DeviseController < Devise.parent_controller.constantize end prepend_before_action :assert_is_devise_resource! + self.responder = Devise.responder respond_to :html if mimes_for_respond_to.empty? # Override prefixes to consider the scoped view. @@ -20,7 +23,7 @@ class DeviseController < Devise.parent_controller.constantize # Action Controller tests that forces _prefixes to be # loaded before even having a request object. # - # This method should be public as it is is in ActionPack + # This method should be public as it is in ActionPack # itself. Changing its visibility may break other gems. def _prefixes #:nodoc: @_prefixes ||= if self.class.scoped_views? && request && devise_mapping @@ -30,6 +33,19 @@ def _prefixes #:nodoc: end end + # Override internal methods to exclude `_prefixes` from action methods since + # we override it above. + # + # There was an intentional change in Rails 7.1 that will allow it to become + # an action method because it's a public method of a non-abstract controller, + # but we also can't make this abstract because it can affect potential actions + # defined in the parent controller, so instead we ensure `_prefixes` is going + # to be considered internal. (and thus, won't become an action method.) + # Ref: https://github.com/rails/rails/pull/48699 + def self.internal_methods #:nodoc: + super << :_prefixes + end + protected # Gets the actual resource stored in the instance variable @@ -110,7 +126,7 @@ def require_no_authentication end if authenticated && resource = warden.user(resource_name) - flash[:alert] = I18n.t("devise.failure.already_authenticated") + set_flash_message(:alert, 'already_authenticated', scope: 'devise.failure') redirect_to after_sign_in_path_for(resource) end end @@ -182,7 +198,7 @@ def find_message(kind, options = {}) options[:default] = Array(options[:default]).unshift(kind.to_sym) options[:resource_name] = resource_name options = devise_i18n_options(options) - I18n.t("#{options[:resource_name]}.#{kind}", options) + I18n.t("#{options[:resource_name]}.#{kind}", **options) end # Controllers inheriting DeviseController are advised to override this diff --git a/app/helpers/devise_helper.rb b/app/helpers/devise_helper.rb index f2d072615..0bfcb0630 100644 --- a/app/helpers/devise_helper.rb +++ b/app/helpers/devise_helper.rb @@ -1,25 +1,5 @@ -module DeviseHelper - # A simple way to show error messages for the current devise resource. If you need - # to customize this method, you can either overwrite it in your application helpers or - # copy the views to your application. - # - # This method is intended to stay simple and it is unlikely that we are going to change - # it to add more behavior or options. - def devise_error_messages! - return "" if resource.errors.empty? - - messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join - sentence = I18n.t("errors.messages.not_saved", - count: resource.errors.count, - resource: resource.class.model_name.human.downcase) +# frozen_string_literal: true - html = <<-HTML -

-

#{sentence}

- -
- HTML - - html.html_safe - end +# Keeping the helper around for backward compatibility. +module DeviseHelper end diff --git a/app/mailers/devise/mailer.rb b/app/mailers/devise/mailer.rb index 857a8bc69..e617edcd0 100644 --- a/app/mailers/devise/mailer.rb +++ b/app/mailers/devise/mailer.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + if defined?(ActionMailer) class Devise::Mailer < Devise.parent_mailer.constantize include Devise::Mailers::Helpers - def confirmation_instructions(record, token, opts={}) + def confirmation_instructions(record, token, opts = {}) @token = token devise_mail(record, :confirmation_instructions, opts) end - def reset_password_instructions(record, token, opts={}) + def reset_password_instructions(record, token, opts = {}) @token = token devise_mail(record, :reset_password_instructions, opts) end - def unlock_instructions(record, token, opts={}) + def unlock_instructions(record, token, opts = {}) @token = token devise_mail(record, :unlock_instructions, opts) end - def email_changed(record, opts={}) + def email_changed(record, opts = {}) devise_mail(record, :email_changed, opts) end - def password_change(record, opts={}) + def password_change(record, opts = {}) devise_mail(record, :password_change, opts) end end diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb index 2dc668fc5..3c21122e1 100644 --- a/app/views/devise/confirmations/new.html.erb +++ b/app/views/devise/confirmations/new.html.erb @@ -1,11 +1,11 @@

Resend confirmation instructions

<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> - <%= devise_error_messages! %> + <%= render "devise/shared/error_messages", resource: resource %>
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true, value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %> +

<%= f.label :email %>

+

<%= f.email_field :email, autofocus: true, autocomplete: "email", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb index 6a796b050..3f1dbc72e 100644 --- a/app/views/devise/passwords/edit.html.erb +++ b/app/views/devise/passwords/edit.html.erb @@ -1,20 +1,20 @@

Change your password

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> - <%= devise_error_messages! %> + <%= render "devise/shared/error_messages", resource: resource %> <%= f.hidden_field :reset_password_token %>
- <%= f.label :password, "New password" %>
+

<%= f.label :password, "New password" %>

<% if @minimum_password_length %> - (<%= @minimum_password_length %> characters minimum)
+

(<%= @minimum_password_length %> characters minimum)

<% end %> - <%= f.password_field :password, autofocus: true, autocomplete: "off" %> +

<%= f.password_field :password, autofocus: true, autocomplete: "new-password" %>

- <%= f.label :password_confirmation, "Confirm new password" %>
- <%= f.password_field :password_confirmation, autocomplete: "off" %> +

<%= f.label :password_confirmation, "Confirm new password" %>

+

<%= f.password_field :password_confirmation, autocomplete: "new-password" %>

diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb index 3d6d11aae..bea7ad130 100644 --- a/app/views/devise/passwords/new.html.erb +++ b/app/views/devise/passwords/new.html.erb @@ -1,15 +1,15 @@

Forgot your password?

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> - <%= devise_error_messages! %> + <%= render "devise/shared/error_messages", resource: resource %>
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> +

<%= f.label :email %>

+

<%= f.email_field :email, autofocus: true, autocomplete: "email" %>

- <%= f.submit "Send me reset password instructions" %> + <%= f.submit "Send me password reset instructions" %>
<% end %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb index 1e66f3d7a..19bb019bc 100644 --- a/app/views/devise/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -1,11 +1,11 @@

Edit <%= resource_name.to_s.humanize %>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> - <%= devise_error_messages! %> + <%= render "devise/shared/error_messages", resource: resource %>
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> +

<%= f.label :email %>

+

<%= f.email_field :email, autofocus: true, autocomplete: "email" %>

<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> @@ -13,22 +13,21 @@ <% end %>
- <%= f.label :password %> (leave blank if you don't want to change it)
- <%= f.password_field :password, autocomplete: "off" %> +

<%= f.label :password %> (leave blank if you don't want to change it)

+

<%= f.password_field :password, autocomplete: "new-password" %>

<% if @minimum_password_length %> -
- <%= @minimum_password_length %> characters minimum +

<%= @minimum_password_length %> characters minimum

<% end %>
- <%= f.label :password_confirmation %>
- <%= f.password_field :password_confirmation, autocomplete: "off" %> +

<%= f.label :password_confirmation %>

+

<%= f.password_field :password_confirmation, autocomplete: "new-password" %>

- <%= f.label :current_password %> (we need your current password to confirm your changes)
- <%= f.password_field :current_password, autocomplete: "off" %> +

<%= f.label :current_password %> (we need your current password to confirm your changes)

+

<%= f.password_field :current_password, autocomplete: "current-password" %>

@@ -38,6 +37,6 @@

Cancel my account

-

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

+
Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?", turbo_confirm: "Are you sure?" }, method: :delete %>
<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index 5a238ce6e..03f48fbb6 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -1,24 +1,24 @@

Sign up

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> - <%= devise_error_messages! %> + <%= render "devise/shared/error_messages", resource: resource %>
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> +

<%= f.label :email %>

+

<%= f.email_field :email, autofocus: true, autocomplete: "email" %>

- <%= f.label :password %> +

<%= f.label :password %>

<% if @minimum_password_length %> - (<%= @minimum_password_length %> characters minimum) - <% end %>
- <%= f.password_field :password, autocomplete: "off" %> +

(<%= @minimum_password_length %> characters minimum)

+ <% end %> +

<%= f.password_field :password, autocomplete: "new-password" %>

- <%= f.label :password_confirmation %>
- <%= f.password_field :password_confirmation, autocomplete: "off" %> +

<%= f.label :password_confirmation %>

+

<%= f.password_field :password_confirmation, autocomplete: "new-password" %>

diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb index b261cfd15..6eeb9fc76 100644 --- a/app/views/devise/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -2,21 +2,21 @@ <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> +

<%= f.label :email %>

+

<%= f.email_field :email, autofocus: true, autocomplete: "email" %>

- <%= f.label :password %>
- <%= f.password_field :password, autocomplete: "off" %> +

<%= f.label :password %>

+

<%= f.password_field :password, autocomplete: "current-password" %>

- <% if devise_mapping.rememberable? -%> + <% if devise_mapping.rememberable? %>
- <%= f.check_box :remember_me %> - <%= f.label :remember_me %> +

<%= f.check_box :remember_me %>

+

<%= f.label :remember_me %>

- <% end -%> + <% end %>
<%= f.submit "Log in" %> diff --git a/app/views/devise/shared/_error_messages.html.erb b/app/views/devise/shared/_error_messages.html.erb new file mode 100644 index 000000000..8c9c17114 --- /dev/null +++ b/app/views/devise/shared/_error_messages.html.erb @@ -0,0 +1,15 @@ +<% if resource.errors.any? %> +
+

+ <%= I18n.t("errors.messages.not_saved", + count: resource.errors.count, + resource: resource.class.model_name.human.downcase) + %> +

+
    + <% resource.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+<% end %> diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb index e6a3e4196..21cf422d5 100644 --- a/app/views/devise/shared/_links.html.erb +++ b/app/views/devise/shared/_links.html.erb @@ -1,25 +1,25 @@ <%- if controller_name != 'sessions' %> - <%= link_to "Log in", new_session_path(resource_name) %>
-<% end -%> +

<%= link_to "Log in", new_session_path(resource_name) %>

+<% end %> <%- if devise_mapping.registerable? && controller_name != 'registrations' %> - <%= link_to "Sign up", new_registration_path(resource_name) %>
-<% end -%> +

<%= link_to "Sign up", new_registration_path(resource_name) %>

+<% end %> <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> - <%= link_to "Forgot your password?", new_password_path(resource_name) %>
-<% end -%> +

<%= link_to "Forgot your password?", new_password_path(resource_name) %>

+<% end %> <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> - <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
-<% end -%> +

<%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>

+<% end %> <%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> - <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
-<% end -%> +

<%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>

+<% end %> <%- if devise_mapping.omniauthable? %> <%- resource_class.omniauth_providers.each do |provider| %> - <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %>
- <% end -%> -<% end -%> +

<%= button_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider), data: { turbo: false } %>

+ <% end %> +<% end %> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb index 16586bc7a..6b68d724c 100644 --- a/app/views/devise/unlocks/new.html.erb +++ b/app/views/devise/unlocks/new.html.erb @@ -1,11 +1,11 @@

Resend unlock instructions

<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> - <%= devise_error_messages! %> + <%= render "devise/shared/error_messages", resource: resource %>
- <%= f.label :email %>
- <%= f.email_field :email, autofocus: true %> +

<%= f.label :email %>

+

<%= f.email_field :email, autofocus: true, autocomplete: "email" %>

diff --git a/bin/test b/bin/test index cb9baa81e..28141f2c7 100755 --- a/bin/test +++ b/bin/test @@ -2,12 +2,11 @@ $: << File.expand_path(File.expand_path('../../test', __FILE__)) require 'bundler/setup' -begin - require 'rails/test_unit/minitest_plugin' -rescue LoadError - exec 'rake' -end +require 'rails/test_unit/runner' +require 'rails/test_unit/reporter' +require 'rails/test_unit/line_filtering' Rails::TestUnitReporter.executable = 'bin/test' -exit Minitest.run(ARGV) +Rails::TestUnit::Runner.parse_options(ARGV) +Rails::TestUnit::Runner.run(ARGV) diff --git a/config/locales/en.yml b/config/locales/en.yml index 0b8f13027..260e1c4ba 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,4 +1,4 @@ -# Additional translations at https://github.com/plataformatec/devise/wiki/I18n +# Additional translations at https://github.com/heartcombo/devise/wiki/I18n en: devise: @@ -42,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." sessions: signed_in: "Signed in successfully." signed_out: "Signed out successfully." diff --git a/devise.gemspec b/devise.gemspec index 3e67230b1..1caa6aeb3 100644 --- a/devise.gemspec +++ b/devise.gemspec @@ -1,4 +1,6 @@ # -*- encoding: utf-8 -*- +# frozen_string_literal: true + $:.push File.expand_path("../lib", __FILE__) require "devise/version" @@ -8,19 +10,26 @@ Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.licenses = ["MIT"] s.summary = "Flexible authentication solution for Rails with Warden" - s.email = "contact@plataformatec.com.br" - s.homepage = "https://github.com/plataformatec/devise" + s.email = "heartcombo.oss@gmail.com" + s.homepage = "https://github.com/heartcombo/devise" s.description = "Flexible authentication solution for Rails with Warden" s.authors = ['José Valim', 'Carlos Antônio'] + s.metadata = { + "homepage_uri" => "https://github.com/heartcombo/devise", + "documentation_uri" => "https://rubydoc.info/github/heartcombo/devise", + "changelog_uri" => "https://github.com/heartcombo/devise/blob/main/CHANGELOG.md", + "source_code_uri" => "https://github.com/heartcombo/devise", + "bug_tracker_uri" => "https://github.com/heartcombo/devise/issues", + "wiki_uri" => "https://github.com/heartcombo/devise/wiki" + } - s.files = `git ls-files`.split("\n") - s.test_files = `git ls-files -- test/*`.split("\n") + s.files = Dir["{app,config,lib}/**/*", "CHANGELOG.md", "MIT-LICENSE", "README.md"] s.require_paths = ["lib"] - s.required_ruby_version = '>= 2.1.0' + s.required_ruby_version = '>= 2.7.0' s.add_dependency("warden", "~> 1.2.3") s.add_dependency("orm_adapter", "~> 0.1") s.add_dependency("bcrypt", "~> 3.0") - s.add_dependency("railties", ">= 4.1.0", "< 5.2") + s.add_dependency("railties", ">= 7.0") s.add_dependency("responders") end diff --git a/gemfiles/Gemfile-rails-7-0 b/gemfiles/Gemfile-rails-7-0 new file mode 100644 index 000000000..a397d04fc --- /dev/null +++ b/gemfiles/Gemfile-rails-7-0 @@ -0,0 +1,31 @@ +source "https://rubygems.org" + +gemspec path: ".." + +gem "rails", "~> 7.0.0" +gem "omniauth" +gem "omniauth-oauth2" +gem "rdoc" + +gem "rails-controller-testing" + +gem "responders", "~> 3.1" + +group :test do + gem "omniauth-facebook" + gem "omniauth-openid" + gem "rexml" + gem "timecop" + gem "webrat", "0.7.3", require: false + gem "mocha", "~> 2.1", require: false + gem "minitest", "< 6" + gem "ostruct" +end + +platforms :ruby do + gem "sqlite3", "~> 1.4" +end + +group :mongoid do + gem "mongoid", "~> 7.5" +end diff --git a/gemfiles/Gemfile-rails-7-1 b/gemfiles/Gemfile-rails-7-1 new file mode 100644 index 000000000..41caefa80 --- /dev/null +++ b/gemfiles/Gemfile-rails-7-1 @@ -0,0 +1,31 @@ +source "https://rubygems.org" + +gemspec path: ".." + +gem "rails", "~> 7.1.0" +gem "omniauth" +gem "omniauth-oauth2" +gem "rdoc" + +gem "rails-controller-testing" + +gem "responders", "~> 3.1" + +group :test do + gem "omniauth-facebook" + gem "omniauth-openid" + gem "rexml" + gem "timecop" + gem "webrat" + gem "mocha", "~> 2.1", require: false + gem "minitest", "< 6" + gem "ostruct" +end + +platforms :ruby do + gem "sqlite3", "~> 1.4" +end + +group :mongoid do + gem "mongoid", "~> 8.1" +end diff --git a/gemfiles/Gemfile-rails-7-2 b/gemfiles/Gemfile-rails-7-2 new file mode 100644 index 000000000..deecdfe9c --- /dev/null +++ b/gemfiles/Gemfile-rails-7-2 @@ -0,0 +1,31 @@ +source "https://rubygems.org" + +gemspec path: ".." + +gem "rails", "~> 7.2.0" +gem "omniauth" +gem "omniauth-oauth2" +gem "rdoc" + +gem "rails-controller-testing" + +gem "responders", "~> 3.1" + +group :test do + gem "omniauth-facebook" + gem "omniauth-openid" + gem "rexml" + gem "timecop" + gem "webrat", require: false + gem "mocha", "~> 2.1", require: false + gem "minitest", "< 6" + gem "ostruct" +end + +platforms :ruby do + gem "sqlite3" +end + +group :mongoid do + gem "mongoid", "~> 8.1" +end diff --git a/gemfiles/Gemfile-rails-8-0 b/gemfiles/Gemfile-rails-8-0 new file mode 100644 index 000000000..23954ff58 --- /dev/null +++ b/gemfiles/Gemfile-rails-8-0 @@ -0,0 +1,31 @@ +source "https://rubygems.org" + +gemspec path: ".." + +gem "rails", "~> 8.0.0" +gem "omniauth" +gem "omniauth-oauth2" +gem "rdoc" + +gem "rails-controller-testing" + +gem "responders", "~> 3.1" + +group :test do + gem "omniauth-facebook" + gem "omniauth-openid" + gem "rexml" + gem "timecop" + gem 'webrat' + gem "mocha", "~> 2.1", require: false + gem "minitest", "< 6" + gem "ostruct" +end + +platforms :ruby do + gem "sqlite3" +end + +group :mongoid do + gem "mongoid", "~> 8.1" +end diff --git a/gemfiles/Gemfile-rails-main b/gemfiles/Gemfile-rails-main new file mode 100644 index 000000000..57ed95a1b --- /dev/null +++ b/gemfiles/Gemfile-rails-main @@ -0,0 +1,31 @@ +source "https://rubygems.org" + +gemspec path: ".." + +gem "rails", github: "rails/rails", branch: "main" +gem "omniauth" +gem "omniauth-oauth2" +gem "rdoc" + +gem "rails-controller-testing" + +gem "responders", "~> 3.1" + +group :test do + gem "omniauth-facebook" + gem "omniauth-openid" + gem "rexml" + gem "timecop" + gem "webrat", "0.7.3", require: false + gem "mocha", "~> 2.1", require: false + gem "minitest", "< 6" + gem "ostruct" +end + +platforms :ruby do + gem "sqlite3" +end + +group :mongoid do + gem "mongoid", github: "mongodb/mongoid", branch: "master" +end diff --git a/gemfiles/Gemfile.rails-4.1-stable b/gemfiles/Gemfile.rails-4.1-stable deleted file mode 100644 index 2dde99dd6..000000000 --- a/gemfiles/Gemfile.rails-4.1-stable +++ /dev/null @@ -1,30 +0,0 @@ -source "https://rubygems.org" - -gemspec path: ".." - -gem "rails", github: "rails/rails", branch: "4-1-stable" -gem "omniauth" -gem "omniauth-oauth2" -gem "rdoc" - -group :test do - gem "omniauth-facebook" - gem "omniauth-openid" - gem "webrat", "0.7.3", require: false - gem "mocha", "~> 1.1", require: false - gem 'test_after_commit', require: false -end - -platforms :jruby do - gem "activerecord-jdbc-adapter" - gem "activerecord-jdbcsqlite3-adapter" - gem "jruby-openssl" -end - -platforms :ruby do - gem "sqlite3" -end - -group :mongoid do - gem "mongoid", "~> 4.0" -end diff --git a/gemfiles/Gemfile.rails-4.1-stable.lock b/gemfiles/Gemfile.rails-4.1-stable.lock deleted file mode 100644 index 864d944be..000000000 --- a/gemfiles/Gemfile.rails-4.1-stable.lock +++ /dev/null @@ -1,171 +0,0 @@ -GIT - remote: git://github.com/rails/rails.git - revision: 0cad778c2605a5204a05a9f1dbd3344e39f248d8 - branch: 4-1-stable - specs: - actionmailer (4.1.16) - actionpack (= 4.1.16) - actionview (= 4.1.16) - mail (~> 2.5, >= 2.5.4) - rails (4.1.16) - actionmailer (= 4.1.16) - actionpack (= 4.1.16) - actionview (= 4.1.16) - activemodel (= 4.1.16) - activerecord (= 4.1.16) - activesupport (= 4.1.16) - bundler (>= 1.3.0, < 2.0) - railties (= 4.1.16) - sprockets-rails (~> 2.0) - -PATH - remote: .. - specs: - devise (4.3.0) - bcrypt (~> 3.0) - orm_adapter (~> 0.1) - railties (>= 4.1.0, < 5.2) - responders - warden (~> 1.2.3) - -GEM - remote: https://rubygems.org/ - specs: - actionpack (4.1.16) - actionview (= 4.1.16) - activesupport (= 4.1.16) - rack (~> 1.5.2) - rack-test (~> 0.6.2) - actionview (4.1.16) - activesupport (= 4.1.16) - builder (~> 3.1) - erubis (~> 2.7.0) - activemodel (4.1.16) - activesupport (= 4.1.16) - builder (~> 3.1) - activerecord (4.1.16) - activemodel (= 4.1.16) - activesupport (= 4.1.16) - arel (~> 5.0.0) - activesupport (4.1.16) - i18n (~> 0.6, >= 0.6.9) - json (~> 1.7, >= 1.7.7) - minitest (~> 5.1) - thread_safe (~> 0.1) - tzinfo (~> 1.1) - arel (5.0.1.20140414130214) - bcrypt (3.1.11) - bson (3.2.6) - builder (3.2.3) - concurrent-ruby (1.0.5) - connection_pool (2.2.1) - erubis (2.7.0) - faraday (0.11.0) - multipart-post (>= 1.2, < 3) - hashie (3.5.5) - i18n (0.8.1) - json (1.8.6) - jwt (1.5.6) - mail (2.6.4) - mime-types (>= 1.16, < 4) - metaclass (0.0.4) - mime-types (3.1) - mime-types-data (~> 3.2015) - mime-types-data (3.2016.0521) - mini_portile2 (2.1.0) - minitest (5.10.1) - mocha (1.2.1) - metaclass (~> 0.0.1) - mongoid (4.0.2) - activemodel (~> 4.0) - moped (~> 2.0.0) - origin (~> 2.1) - tzinfo (>= 0.3.37) - moped (2.0.7) - bson (~> 3.0) - connection_pool (~> 2.0) - optionable (~> 0.2.0) - multi_json (1.12.1) - multi_xml (0.6.0) - multipart-post (2.0.0) - nokogiri (1.7.0.1) - mini_portile2 (~> 2.1.0) - oauth2 (1.3.1) - faraday (>= 0.8, < 0.12) - jwt (~> 1.0) - multi_json (~> 1.3) - multi_xml (~> 0.5) - rack (>= 1.2, < 3) - omniauth (1.4.2) - hashie (>= 1.2, < 4) - rack (>= 1.0, < 3) - omniauth-facebook (4.0.0) - omniauth-oauth2 (~> 1.2) - omniauth-oauth2 (1.4.0) - oauth2 (~> 1.0) - omniauth (~> 1.2) - omniauth-openid (1.0.1) - omniauth (~> 1.0) - rack-openid (~> 1.3.1) - optionable (0.2.0) - origin (2.3.0) - orm_adapter (0.5.0) - rack (1.5.5) - rack-openid (1.3.1) - rack (>= 1.1.0) - ruby-openid (>= 2.1.8) - rack-test (0.6.3) - rack (>= 1.0) - railties (4.1.16) - actionpack (= 4.1.16) - activesupport (= 4.1.16) - rake (>= 0.8.7) - thor (>= 0.18.1, < 2.0) - rake (12.0.0) - rdoc (5.1.0) - responders (1.1.2) - railties (>= 3.2, < 4.2) - ruby-openid (2.7.0) - sprockets (3.7.1) - concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (2.3.3) - actionpack (>= 3.0) - activesupport (>= 3.0) - sprockets (>= 2.8, < 4.0) - sqlite3 (1.3.13) - test_after_commit (1.1.0) - activerecord (>= 3.2) - thor (0.19.4) - thread_safe (0.3.6) - tzinfo (1.2.2) - thread_safe (~> 0.1) - warden (1.2.7) - rack (>= 1.0) - webrat (0.7.3) - nokogiri (>= 1.2.0) - rack (>= 1.0) - rack-test (>= 0.5.3) - -PLATFORMS - ruby - -DEPENDENCIES - activerecord-jdbc-adapter - activerecord-jdbcsqlite3-adapter - devise! - jruby-openssl - mocha (~> 1.1) - mongoid (~> 4.0) - omniauth - omniauth-facebook - omniauth-oauth2 - omniauth-openid - rails! - rdoc - sqlite3 - test_after_commit - webrat (= 0.7.3) - -BUNDLED WITH - 1.14.6 diff --git a/gemfiles/Gemfile.rails-4.2-stable b/gemfiles/Gemfile.rails-4.2-stable deleted file mode 100644 index 8165a9501..000000000 --- a/gemfiles/Gemfile.rails-4.2-stable +++ /dev/null @@ -1,30 +0,0 @@ -source "https://rubygems.org" - -gemspec path: ".." - -gem "rails", github: "rails/rails", branch: "4-2-stable" -gem "omniauth" -gem "omniauth-oauth2" -gem "rdoc" - -group :test do - gem "omniauth-facebook" - gem "omniauth-openid" - gem "webrat", "0.7.3", require: false - gem "mocha", "~> 1.1", require: false - gem 'test_after_commit', require: false -end - -platforms :jruby do - gem "activerecord-jdbc-adapter" - gem "activerecord-jdbcsqlite3-adapter" - gem "jruby-openssl" -end - -platforms :ruby do - gem "sqlite3" -end - -group :mongoid do - gem "mongoid", "~> 4.0" -end diff --git a/gemfiles/Gemfile.rails-4.2-stable.lock b/gemfiles/Gemfile.rails-4.2-stable.lock deleted file mode 100644 index 66a87d8de..000000000 --- a/gemfiles/Gemfile.rails-4.2-stable.lock +++ /dev/null @@ -1,192 +0,0 @@ -GIT - remote: git://github.com/rails/rails.git - revision: dc3ae21802c316e1639239d28202db7aa7fb7cac - branch: 4-2-stable - specs: - actionmailer (4.2.8) - actionpack (= 4.2.8) - actionview (= 4.2.8) - activejob (= 4.2.8) - mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 1.0, >= 1.0.5) - actionpack (4.2.8) - actionview (= 4.2.8) - activesupport (= 4.2.8) - rack (~> 1.6) - rack-test (~> 0.6.2) - rails-dom-testing (~> 1.0, >= 1.0.5) - rails-html-sanitizer (~> 1.0, >= 1.0.2) - actionview (4.2.8) - activesupport (= 4.2.8) - builder (~> 3.1) - erubis (~> 2.7.0) - rails-dom-testing (~> 1.0, >= 1.0.5) - rails-html-sanitizer (~> 1.0, >= 1.0.3) - activejob (4.2.8) - activesupport (= 4.2.8) - globalid (>= 0.3.0) - activemodel (4.2.8) - activesupport (= 4.2.8) - builder (~> 3.1) - activerecord (4.2.8) - activemodel (= 4.2.8) - activesupport (= 4.2.8) - arel (~> 6.0) - activesupport (4.2.8) - i18n (~> 0.7) - minitest (~> 5.1) - thread_safe (~> 0.3, >= 0.3.4) - tzinfo (~> 1.1) - rails (4.2.8) - actionmailer (= 4.2.8) - actionpack (= 4.2.8) - actionview (= 4.2.8) - activejob (= 4.2.8) - activemodel (= 4.2.8) - activerecord (= 4.2.8) - activesupport (= 4.2.8) - bundler (>= 1.3.0, < 2.0) - railties (= 4.2.8) - sprockets-rails - railties (4.2.8) - actionpack (= 4.2.8) - activesupport (= 4.2.8) - rake (>= 0.8.7) - thor (>= 0.18.1, < 2.0) - -PATH - remote: .. - specs: - devise (4.3.0) - bcrypt (~> 3.0) - orm_adapter (~> 0.1) - railties (>= 4.1.0, < 5.2) - responders - warden (~> 1.2.3) - -GEM - remote: https://rubygems.org/ - specs: - arel (6.0.4) - bcrypt (3.1.11) - bson (3.2.6) - builder (3.2.3) - concurrent-ruby (1.0.5) - connection_pool (2.2.1) - erubis (2.7.0) - faraday (0.11.0) - multipart-post (>= 1.2, < 3) - globalid (0.3.7) - activesupport (>= 4.1.0) - hashie (3.5.5) - i18n (0.8.1) - jwt (1.5.6) - loofah (2.0.3) - nokogiri (>= 1.5.9) - mail (2.6.4) - mime-types (>= 1.16, < 4) - metaclass (0.0.4) - mime-types (3.1) - mime-types-data (~> 3.2015) - mime-types-data (3.2016.0521) - mini_portile2 (2.1.0) - minitest (5.10.1) - mocha (1.2.1) - metaclass (~> 0.0.1) - mongoid (4.0.2) - activemodel (~> 4.0) - moped (~> 2.0.0) - origin (~> 2.1) - tzinfo (>= 0.3.37) - moped (2.0.7) - bson (~> 3.0) - connection_pool (~> 2.0) - optionable (~> 0.2.0) - multi_json (1.12.1) - multi_xml (0.6.0) - multipart-post (2.0.0) - nokogiri (1.7.0.1) - mini_portile2 (~> 2.1.0) - oauth2 (1.3.1) - faraday (>= 0.8, < 0.12) - jwt (~> 1.0) - multi_json (~> 1.3) - multi_xml (~> 0.5) - rack (>= 1.2, < 3) - omniauth (1.6.1) - hashie (>= 3.4.6, < 3.6.0) - rack (>= 1.6.2, < 3) - omniauth-facebook (4.0.0) - omniauth-oauth2 (~> 1.2) - omniauth-oauth2 (1.4.0) - oauth2 (~> 1.0) - omniauth (~> 1.2) - omniauth-openid (1.0.1) - omniauth (~> 1.0) - rack-openid (~> 1.3.1) - optionable (0.2.0) - origin (2.3.0) - orm_adapter (0.5.0) - rack (1.6.5) - rack-openid (1.3.1) - rack (>= 1.1.0) - ruby-openid (>= 2.1.8) - rack-test (0.6.3) - rack (>= 1.0) - rails-deprecated_sanitizer (1.0.3) - activesupport (>= 4.2.0.alpha) - rails-dom-testing (1.0.8) - activesupport (>= 4.2.0.beta, < 5.0) - nokogiri (~> 1.6) - rails-deprecated_sanitizer (>= 1.0.1) - rails-html-sanitizer (1.0.3) - loofah (~> 2.0) - rake (12.0.0) - rdoc (5.1.0) - responders (2.4.0) - actionpack (>= 4.2.0, < 5.3) - railties (>= 4.2.0, < 5.3) - ruby-openid (2.7.0) - sprockets (3.7.1) - concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (3.2.0) - actionpack (>= 4.0) - activesupport (>= 4.0) - sprockets (>= 3.0.0) - sqlite3 (1.3.13) - test_after_commit (1.1.0) - activerecord (>= 3.2) - thor (0.19.4) - thread_safe (0.3.6) - tzinfo (1.2.2) - thread_safe (~> 0.1) - warden (1.2.7) - rack (>= 1.0) - webrat (0.7.3) - nokogiri (>= 1.2.0) - rack (>= 1.0) - rack-test (>= 0.5.3) - -PLATFORMS - ruby - -DEPENDENCIES - activerecord-jdbc-adapter - activerecord-jdbcsqlite3-adapter - devise! - jruby-openssl - mocha (~> 1.1) - mongoid (~> 4.0) - omniauth - omniauth-facebook - omniauth-oauth2 - omniauth-openid - rails! - rdoc - sqlite3 - test_after_commit - webrat (= 0.7.3) - -BUNDLED WITH - 1.14.6 diff --git a/gemfiles/Gemfile.rails-5.0-stable b/gemfiles/Gemfile.rails-5.0-stable deleted file mode 100644 index f4acf8acf..000000000 --- a/gemfiles/Gemfile.rails-5.0-stable +++ /dev/null @@ -1,34 +0,0 @@ -source "https://rubygems.org" - -gemspec path: ".." - -gem "rails", '~> 5.0.0' -gem "omniauth" -gem "omniauth-oauth2" -gem "rdoc" - -gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml" - -gem "rails-controller-testing" - -gem "responders", "~> 2.1" - -# TODO: Remove this line when Rails 5.0.3 is released -gem "minitest", "< 5.10.2" - -group :test do - gem "omniauth-facebook" - gem "omniauth-openid" - gem "webrat", "0.7.3", require: false - gem "mocha", "~> 1.1", require: false - gem 'test_after_commit', require: false -end - -platforms :ruby do - gem "sqlite3" -end - -# TODO: -# group :mongoid do -# gem "mongoid", "~> 4.0.0" -# end diff --git a/gemfiles/Gemfile.rails-5.0-stable.lock b/gemfiles/Gemfile.rails-5.0-stable.lock deleted file mode 100644 index cd9331765..000000000 --- a/gemfiles/Gemfile.rails-5.0-stable.lock +++ /dev/null @@ -1,193 +0,0 @@ -GIT - remote: git://github.com/rails/activemodel-serializers-xml.git - revision: dd9c0acf26aab111ebc647cd8deb99ebc6946531 - specs: - activemodel-serializers-xml (1.0.1) - activemodel (> 5.x) - activesupport (> 5.x) - builder (~> 3.1) - -PATH - remote: .. - specs: - devise (4.3.0) - bcrypt (~> 3.0) - orm_adapter (~> 0.1) - railties (>= 4.1.0, < 5.2) - responders - warden (~> 1.2.3) - -GEM - remote: https://rubygems.org/ - specs: - actioncable (5.0.2) - actionpack (= 5.0.2) - nio4r (>= 1.2, < 3.0) - websocket-driver (~> 0.6.1) - actionmailer (5.0.2) - actionpack (= 5.0.2) - actionview (= 5.0.2) - activejob (= 5.0.2) - mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 2.0) - actionpack (5.0.2) - actionview (= 5.0.2) - activesupport (= 5.0.2) - rack (~> 2.0) - rack-test (~> 0.6.3) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.0.2) - actionview (5.0.2) - activesupport (= 5.0.2) - builder (~> 3.1) - erubis (~> 2.7.0) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.0.3) - activejob (5.0.2) - activesupport (= 5.0.2) - globalid (>= 0.3.6) - activemodel (5.0.2) - activesupport (= 5.0.2) - activerecord (5.0.2) - activemodel (= 5.0.2) - activesupport (= 5.0.2) - arel (~> 7.0) - activesupport (5.0.2) - concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (~> 0.7) - minitest (~> 5.1) - tzinfo (~> 1.1) - arel (7.1.4) - bcrypt (3.1.11) - builder (3.2.3) - concurrent-ruby (1.0.5) - erubis (2.7.0) - faraday (0.11.0) - multipart-post (>= 1.2, < 3) - globalid (0.4.0) - activesupport (>= 4.2.0) - hashie (3.5.5) - i18n (0.8.1) - jwt (1.5.6) - loofah (2.0.3) - nokogiri (>= 1.5.9) - mail (2.6.5) - mime-types (>= 1.16, < 4) - metaclass (0.0.4) - method_source (0.8.2) - mime-types (3.1) - mime-types-data (~> 3.2015) - mime-types-data (3.2016.0521) - mini_portile2 (2.1.0) - minitest (5.10.1) - mocha (1.2.1) - metaclass (~> 0.0.1) - multi_json (1.12.1) - multi_xml (0.6.0) - multipart-post (2.0.0) - nio4r (2.0.0) - nokogiri (1.7.2) - mini_portile2 (~> 2.1.0) - oauth2 (1.3.1) - faraday (>= 0.8, < 0.12) - jwt (~> 1.0) - multi_json (~> 1.3) - multi_xml (~> 0.5) - rack (>= 1.2, < 3) - omniauth (1.6.1) - hashie (>= 3.4.6, < 3.6.0) - rack (>= 1.6.2, < 3) - omniauth-facebook (4.0.0) - omniauth-oauth2 (~> 1.2) - omniauth-oauth2 (1.4.0) - oauth2 (~> 1.0) - omniauth (~> 1.2) - omniauth-openid (1.0.1) - omniauth (~> 1.0) - rack-openid (~> 1.3.1) - orm_adapter (0.5.0) - rack (2.0.2) - rack-openid (1.3.1) - rack (>= 1.1.0) - ruby-openid (>= 2.1.8) - rack-test (0.6.3) - rack (>= 1.0) - rails (5.0.2) - actioncable (= 5.0.2) - actionmailer (= 5.0.2) - actionpack (= 5.0.2) - actionview (= 5.0.2) - activejob (= 5.0.2) - activemodel (= 5.0.2) - activerecord (= 5.0.2) - activesupport (= 5.0.2) - bundler (>= 1.3.0, < 2.0) - railties (= 5.0.2) - sprockets-rails (>= 2.0.0) - rails-controller-testing (1.0.1) - actionpack (~> 5.x) - actionview (~> 5.x) - activesupport (~> 5.x) - rails-dom-testing (2.0.3) - activesupport (>= 4.2.0) - nokogiri (>= 1.6) - rails-html-sanitizer (1.0.3) - loofah (~> 2.0) - railties (5.0.2) - actionpack (= 5.0.2) - activesupport (= 5.0.2) - method_source - rake (>= 0.8.7) - thor (>= 0.18.1, < 2.0) - rake (12.0.0) - rdoc (5.1.0) - responders (2.4.0) - actionpack (>= 4.2.0, < 5.3) - railties (>= 4.2.0, < 5.3) - ruby-openid (2.7.0) - sprockets (3.7.1) - concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (3.2.0) - actionpack (>= 4.0) - activesupport (>= 4.0) - sprockets (>= 3.0.0) - sqlite3 (1.3.13) - test_after_commit (1.1.0) - activerecord (>= 3.2) - thor (0.19.4) - thread_safe (0.3.6) - tzinfo (1.2.3) - thread_safe (~> 0.1) - warden (1.2.7) - rack (>= 1.0) - webrat (0.7.3) - nokogiri (>= 1.2.0) - rack (>= 1.0) - rack-test (>= 0.5.3) - websocket-driver (0.6.5) - websocket-extensions (>= 0.1.0) - websocket-extensions (0.1.2) - -PLATFORMS - ruby - -DEPENDENCIES - activemodel-serializers-xml! - devise! - minitest (< 5.10.2) - mocha (~> 1.1) - omniauth - omniauth-facebook - omniauth-oauth2 - omniauth-openid - rails (~> 5.0.0) - rails-controller-testing - rdoc - responders (~> 2.1) - sqlite3 - test_after_commit - webrat (= 0.7.3) - -BUNDLED WITH - 1.14.6 diff --git a/guides/bug_report_templates/integration_test.rb b/guides/bug_report_templates/integration_test.rb index 6fea86bbb..08b340177 100644 --- a/guides/bug_report_templates/integration_test.rb +++ b/guides/bug_report_templates/integration_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + begin require 'bundler/inline' rescue LoadError => e @@ -74,7 +76,7 @@ class ApplicationController < ActionController::Base class TestController < ApplicationController include Rails.application.routes.url_helpers - before_filter :authenticate_user! + before_action :authenticate_user! def index render plain: 'Home' diff --git a/lib/devise.rb b/lib/devise.rb old mode 100755 new mode 100644 index debd342b7..8e0c85e77 --- a/lib/devise.rb +++ b/lib/devise.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails' require 'active_support/core_ext/numeric/time' require 'active_support/dependencies' @@ -11,15 +13,16 @@ module Devise autoload :Encryptor, 'devise/encryptor' autoload :FailureApp, 'devise/failure_app' autoload :OmniAuth, 'devise/omniauth' + autoload :Orm, 'devise/orm' autoload :ParameterFilter, 'devise/parameter_filter' autoload :ParameterSanitizer, 'devise/parameter_sanitizer' - autoload :TestHelpers, 'devise/test_helpers' autoload :TimeInflector, 'devise/time_inflector' autoload :TokenGenerator, 'devise/token_generator' module Controllers autoload :Helpers, 'devise/controllers/helpers' autoload :Rememberable, 'devise/controllers/rememberable' + autoload :Responder, 'devise/controllers/responder' autoload :ScopedViews, 'devise/controllers/scoped_views' autoload :SignInOut, 'devise/controllers/sign_in_out' autoload :StoreLocation, 'devise/controllers/store_location' @@ -56,7 +59,7 @@ module Test NO_INPUT = [] # True values used to check params - TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'] + TRUE_VALUES = [true, 1, '1', 'on', 'ON', 't', 'T', 'true', 'TRUE'] # Secret key used by the key generator mattr_accessor :secret_key @@ -68,7 +71,7 @@ module Test # The number of times to hash the password. mattr_accessor :stretches - @@stretches = 11 + @@stretches = 12 # The default key used when authenticating over http auth. mattr_accessor :http_authentication_key @@ -149,7 +152,7 @@ module Test mattr_accessor :timeout_in @@timeout_in = 30.minutes - # Used to hash the password. Please generate one with rake secret. + # Used to hash the password. Please generate one with rails secret. mattr_accessor :pepper @@pepper = nil @@ -214,7 +217,16 @@ module Test # Which formats should be treated as navigational. mattr_accessor :navigational_formats - @@navigational_formats = ["*/*", :html] + @@navigational_formats = ["*/*", :html, :turbo_stream] + + # The default responder used by Devise, used to customize status codes with: + # + # `config.responder.error_status` + # `config.responder.redirect_status` + # + # Can be replaced by a custom application responder. + mattr_accessor :responder + @@responder = Devise::Controllers::Responder # When set to true, signing out a user signs out all other scopes. mattr_accessor :sign_out_all_scopes @@ -261,8 +273,14 @@ module Test # PRIVATE CONFIGURATION # Store scopes mappings. - mattr_reader :mappings @@mappings = {} + def self.mappings + # 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. + Rails.application.try(:reload_routes_unless_loaded) + @@mappings + end # OmniAuth configurations. mattr_reader :omniauth_configs @@ -290,13 +308,9 @@ module Test mattr_accessor :token_generator @@token_generator = nil - def self.rails51? # :nodoc: - Rails.gem_version >= Gem::Version.new("5.1.x") - end - - def self.activerecord51? # :nodoc: - defined?(ActiveRecord) && ActiveRecord.gem_version >= Gem::Version.new("5.1.x") - end + # When set to false, changing a password does not automatically sign in a user + mattr_accessor :sign_in_after_change_password + @@sign_in_after_change_password = true # Default way to set up Devise. Run rails generate devise_install to create # a fresh initializer with all configuration values. @@ -310,12 +324,20 @@ def initialize(name) end def get - ActiveSupport::Dependencies.constantize(@name) + # TODO: Remove AS::Dependencies usage when dropping support to Rails < 7. + if ActiveSupport::Dependencies.respond_to?(:constantize) + ActiveSupport::Dependencies.constantize(@name) + else + @name.constantize + end end end def self.ref(arg) - ActiveSupport::Dependencies.reference(arg) + # TODO: Remove AS::Dependencies usage when dropping support to Rails < 7. + if ActiveSupport::Dependencies.respond_to?(:reference) + ActiveSupport::Dependencies.reference(arg) + end Getter.new(arg) end @@ -423,9 +445,9 @@ def self.add_module(module_name, options = {}) # Devise.setup do |config| # config.allow_unconfirmed_access_for = 2.days # - # config.warden do |manager| + # config.warden do |warden_config| # # Configure warden to use other strategies, like oauth. - # manager.oauth(:twitter) + # warden_config.oauth(:twitter) # end # end def self.warden(&block) @@ -495,12 +517,12 @@ def self.friendly_token(length = 20) # constant-time comparison algorithm to prevent timing attacks def self.secure_compare(a, b) - return false if a.blank? || b.blank? || a.bytesize != b.bytesize - l = a.unpack "C#{a.bytesize}" + return false if a.nil? || b.nil? + ActiveSupport::SecurityUtils.secure_compare(a, b) + end - res = 0 - b.each_byte { |byte| res |= byte ^ l.shift } - res == 0 + def self.deprecator + @deprecator ||= ActiveSupport::Deprecation.new("5.0", "Devise") end end diff --git a/lib/devise/controllers/helpers.rb b/lib/devise/controllers/helpers.rb index 3f7cc29ca..68e8e8d1d 100644 --- a/lib/devise/controllers/helpers.rb +++ b/lib/devise/controllers/helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Controllers # Those helpers are convenience methods added to ApplicationController. @@ -34,16 +36,17 @@ module ClassMethods # before_action ->{ authenticate_blogger! :admin } # Redirects to the admin login page # current_blogger :user # Preferably returns a User if one is signed in # - def devise_group(group_name, opts={}) + def devise_group(group_name, opts = {}) mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]" class_eval <<-METHODS, __FILE__, __LINE__ + 1 - def authenticate_#{group_name}!(favourite=nil, opts={}) + def authenticate_#{group_name}!(favorite = nil, opts = {}) unless #{group_name}_signed_in? mappings = #{mappings} - mappings.unshift mappings.delete(favourite.to_sym) if favourite + mappings.unshift mappings.delete(favorite.to_sym) if favorite mappings.each do |mapping| opts[:scope] = mapping + opts[:locale] = I18n.locale warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end end @@ -55,9 +58,9 @@ def #{group_name}_signed_in? end end - def current_#{group_name}(favourite=nil) + def current_#{group_name}(favorite = nil) mappings = #{mappings} - mappings.unshift mappings.delete(favourite.to_sym) if favourite + mappings.unshift mappings.delete(favorite.to_sym) if favorite mappings.each do |mapping| current = warden.authenticate(scope: mapping) return current if current @@ -111,8 +114,9 @@ def self.define_helpers(mapping) #:nodoc: mapping = mapping.name class_eval <<-METHODS, __FILE__, __LINE__ + 1 - def authenticate_#{mapping}!(opts={}) + def authenticate_#{mapping}!(opts = {}) opts[:scope] = :#{mapping} + opts[:locale] = I18n.locale warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end @@ -250,7 +254,7 @@ def sign_out_and_redirect(resource_or_scope) # Overwrite Rails' handle unverified request to sign out all scopes, # clear run strategies and remove cached variables. def handle_unverified_request - super # call the default behaviour which resets/nullifies/raises + super # call the default behavior which resets/nullifies/raises request.env["devise.skip_storage"] = true sign_out_all_scopes(false) end @@ -266,7 +270,7 @@ def is_navigational_format? # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? - is_navigational_format? + request.respond_to?(:flash) && is_navigational_format? end private diff --git a/lib/devise/controllers/rememberable.rb b/lib/devise/controllers/rememberable.rb index 02bdaf117..420a2f785 100644 --- a/lib/devise/controllers/rememberable.rb +++ b/lib/devise/controllers/rememberable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Controllers # A module that may be optionally included in a controller in order diff --git a/lib/devise/controllers/responder.rb b/lib/devise/controllers/responder.rb new file mode 100644 index 000000000..8e3858a13 --- /dev/null +++ b/lib/devise/controllers/responder.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +module Devise + module Controllers + # Custom Responder to configure default statuses that only apply to Devise, + # and allow to integrate more easily with Hotwire/Turbo. + class Responder < ActionController::Responder + if respond_to?(:error_status=) && respond_to?(:redirect_status=) + self.error_status = :ok + self.redirect_status = :found + else + # TODO: remove this support for older Rails versions, which aren't supported by Turbo + # and/or responders. It won't allow configuring a custom response, but it allows Devise + # to use these methods and defaults across the implementation more easily. + def self.error_status + :ok + end + + def self.redirect_status + :found + end + + def self.error_status=(*) + warn "[DEVISE] Setting the error status on the Devise responder has no effect with this " \ + "version of `responders`, please make sure you're using a newer version. Check the changelog for more info." + end + + def self.redirect_status=(*) + warn "[DEVISE] Setting the redirect status on the Devise responder has no effect with this " \ + "version of `responders`, please make sure you're using a newer version. Check the changelog for more info." + end + end + end + end +end diff --git a/lib/devise/controllers/scoped_views.rb b/lib/devise/controllers/scoped_views.rb index 7ba965e57..989d3879c 100644 --- a/lib/devise/controllers/scoped_views.rb +++ b/lib/devise/controllers/scoped_views.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Controllers module ScopedViews diff --git a/lib/devise/controllers/sign_in_out.rb b/lib/devise/controllers/sign_in_out.rb index 77c5987ba..7e053d112 100644 --- a/lib/devise/controllers/sign_in_out.rb +++ b/lib/devise/controllers/sign_in_out.rb @@ -1,11 +1,16 @@ +# frozen_string_literal: true + module Devise module Controllers # Provide sign in and sign out functionality. # Included by default in all controllers. module SignInOut # Return true if the given scope is signed in session. If no scope given, return - # true if any scope is signed in. Does not run authentication hooks. - def signed_in?(scope=nil) + # true if any scope is signed in. This will run authentication hooks, which may + # cause exceptions to be thrown from this method; if you simply want to check + # if a scope has already previously been authenticated without running + # authentication hooks, you can directly call `warden.authenticated?(scope: scope)` + def signed_in?(scope = nil) [scope || Devise.mappings.keys].flatten.any? do |_scope| warden.authenticate?(scope: _scope) end @@ -14,6 +19,9 @@ def signed_in?(scope=nil) # Sign in a user that already was authenticated. This helper is useful for logging # users in after sign up. All options given to sign_in is passed forward # to the set_user method in warden. + # If you are using a custom warden strategy and the timeoutable module, you have to + # set `env["devise.skip_timeout"] = true` in the request to use this method, like we do + # in the sessions controller: https://github.com/heartcombo/devise/blob/main/app/controllers/devise/sessions_controller.rb#L7 # # Examples: # @@ -29,16 +37,7 @@ def sign_in(resource_or_scope, *args) expire_data_after_sign_in! - if options[:bypass] - ActiveSupport::Deprecation.warn(<<-DEPRECATION.strip_heredoc, caller) - [Devise] bypass option is deprecated and it will be removed in future version of Devise. - Please use bypass_sign_in method instead. - Example: - - bypass_sign_in(user) - DEPRECATION - warden.session_serializer.store(resource, scope) - elsif warden.user(scope) == resource && !options.delete(:force) + if warden.user(scope) == resource && !options.delete(:force) # Do nothing. User already signed in and we are not forcing it. true else @@ -69,7 +68,7 @@ def bypass_sign_in(resource, scope: nil) # sign_out :user # sign_out(scope) # sign_out @user # sign_out(resource) # - def sign_out(resource_or_scope=nil) + def sign_out(resource_or_scope = nil) return sign_out_all_scopes unless resource_or_scope scope = Devise::Mapping.find_scope!(resource_or_scope) user = warden.user(scope: scope, run_callbacks: false) # If there is no user @@ -84,7 +83,7 @@ def sign_out(resource_or_scope=nil) # Sign out all active users or scopes. This helper is useful for signing out all roles # in one click. This signs out ALL scopes in warden. Returns true if there was at least one logout # and false if there was no user logged in on all scopes. - def sign_out_all_scopes(lock=true) + def sign_out_all_scopes(lock = true) users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) } warden.logout @@ -98,10 +97,6 @@ def sign_out_all_scopes(lock=true) private def expire_data_after_sign_in! - # session.keys will return an empty array if the session is not yet loaded. - # This is a bug in both Rack and Rails. - # A call to #empty? forces the session to be loaded. - session.empty? session.keys.grep(/^devise\./).each { |k| session.delete(k) } end diff --git a/lib/devise/controllers/store_location.rb b/lib/devise/controllers/store_location.rb index 91655a35c..1ae46f734 100644 --- a/lib/devise/controllers/store_location.rb +++ b/lib/devise/controllers/store_location.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "uri" module Devise @@ -33,12 +35,9 @@ def stored_location_for(resource_or_scope) # def store_location_for(resource_or_scope, location) session_key = stored_location_key_for(resource_or_scope) - uri = parse_uri(location) - if uri - path = [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?') - path = [path, uri.fragment].compact.join('#') - session[session_key] = path - end + + path = extract_path_from_location(location) + session[session_key] = path if path end private @@ -53,6 +52,25 @@ def stored_location_key_for(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) "#{scope}_return_to" end + + def extract_path_from_location(location) + uri = parse_uri(location) + + if uri && uri.path + path = remove_domain_from_uri(uri) + path = add_fragment_back_to_path(uri, path) + + path + end + end + + def remove_domain_from_uri(uri) + [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?') + end + + def add_fragment_back_to_path(uri, path) + [path, uri.fragment].compact.join('#') + end end end end diff --git a/lib/devise/controllers/url_helpers.rb b/lib/devise/controllers/url_helpers.rb index fed1383f2..2792a07c8 100644 --- a/lib/devise/controllers/url_helpers.rb +++ b/lib/devise/controllers/url_helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Controllers # Create url helpers to be used with resource/scope configuration. Acts as @@ -32,7 +34,7 @@ def self.remove_helpers! end end - def self.generate_helpers!(routes=nil) + def self.generate_helpers!(routes = nil) routes ||= begin mappings = Devise.mappings.values.map(&:used_helpers).flatten.uniq Devise::URL_HELPERS.slice(*mappings) diff --git a/lib/devise/delegator.rb b/lib/devise/delegator.rb index 361d4cffe..d04f15f19 100644 --- a/lib/devise/delegator.rb +++ b/lib/devise/delegator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise # Checks the scope in the given environment and returns the associated failure app. class Delegator diff --git a/lib/devise/encryptor.rb b/lib/devise/encryptor.rb index 19651d7b4..7a53bef30 100644 --- a/lib/devise/encryptor.rb +++ b/lib/devise/encryptor.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'bcrypt' module Devise diff --git a/lib/devise/failure_app.rb b/lib/devise/failure_app.rb index 4f7a3ddc8..70cf6d2f3 100644 --- a/lib/devise/failure_app.rb +++ b/lib/devise/failure_app.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "action_controller/metal" module Devise @@ -16,6 +18,11 @@ class FailureApp < ActionController::Metal delegate :flash, to: :request + include AbstractController::Callbacks + around_action do |failure_app, action| + I18n.with_locale(failure_app.i18n_locale, &action) + end + def self.call(env) @respond ||= action(:respond) @respond.call(env) @@ -69,8 +76,11 @@ def recall end flash.now[:alert] = i18n_message(:invalid) if is_flashing_format? - # self.response = recall_app(warden_options[:recall]).call(env) - self.response = recall_app(warden_options[:recall]).call(request.env) + self.response = recall_app(warden_options[:recall]).call(request.env).tap { |response| + status = response[0].in?(300..399) ? Devise.responder.redirect_status : Devise.responder.error_status + # Avoid warnings translating status to code using Rails if available (e.g. `unprocessable_entity` => `unprocessable_content`) + response[0] = ActionDispatch::Response.try(:rack_status_code, status) || Rack::Utils.status_code(status) + } end def redirect @@ -101,16 +111,27 @@ def i18n_message(default = nil) options[:scope] = "devise.failure" options[:default] = [message] auth_keys = scope_class.authentication_keys - keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key| scope_class.human_attribute_name(key) } - options[:authentication_keys] = keys.join(I18n.translate(:"support.array.words_connector")) + human_keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key| + # TODO: Remove the fallback and just use `downcase_first` once we drop support for Rails 7.0. + human_key = scope_class.human_attribute_name(key) + human_key.respond_to?(:downcase_first) ? human_key.downcase_first : human_key[0].downcase + human_key[1..] + } + options[:authentication_keys] = human_keys.join(I18n.t(:"support.array.words_connector")) options = i18n_options(options) - I18n.t(:"#{scope}.#{message}", options) + I18n.t(:"#{scope}.#{message}", **options).then { |msg| + # Ensure that auth keys at the start of the translated string are properly cased. + msg.start_with?(human_keys.first) ? msg.upcase_first : msg + } else message.to_s end end + def i18n_locale + warden_options[:locale] + end + def redirect_url if warden_message == :timeout flash[:timedout] = true if is_flashing_format? @@ -118,7 +139,7 @@ def redirect_url path = if request.get? attempted_path else - request.referrer + extract_path_from_location(request.referrer) end path || scope_url @@ -135,18 +156,20 @@ def scope_url opts = {} # Initialize script_name with nil to prevent infinite loops in - # authenticated mounted engines in rails 4.2 and 5.0 + # authenticated mounted engines opts[:script_name] = nil route = route(scope) opts[:format] = request_format unless skip_format? - opts[:script_name] = relative_url_root if relative_url_root? - router_name = Devise.mappings[scope].router_name || Devise.available_router_name context = send(router_name) + if relative_url_root? + opts[:script_name] = relative_url_root + end + if context.respond_to?(route) context.send(route, opts) elsif respond_to?(:root_url) @@ -157,7 +180,7 @@ def scope_url end def skip_format? - %w(html */*).include? request_format.to_s + %w(html */* turbo_stream).include? request_format.to_s end # Choose whether we should respond in an HTTP authentication fashion, @@ -240,7 +263,7 @@ def is_navigational_format? # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? - is_navigational_format? + request.respond_to?(:flash) && is_navigational_format? end def request_format @@ -258,5 +281,7 @@ def relative_url_root def relative_url_root? relative_url_root.present? end + + ActiveSupport.run_load_hooks(:devise_failure_app, self) end end diff --git a/lib/devise/hooks/activatable.rb b/lib/devise/hooks/activatable.rb index 805c2c575..9feb96307 100644 --- a/lib/devise/hooks/activatable.rb +++ b/lib/devise/hooks/activatable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Deny user access whenever their account is not active yet. # We need this as hook to validate the user activity on each request # and in case the user is using other strategies beside Devise ones. @@ -5,6 +7,6 @@ if record && record.respond_to?(:active_for_authentication?) && !record.active_for_authentication? scope = options[:scope] warden.logout(scope) - throw :warden, scope: scope, message: record.inactive_message + throw :warden, scope: scope, message: record.inactive_message, locale: options.fetch(:locale, I18n.locale) end end diff --git a/lib/devise/hooks/csrf_cleaner.rb b/lib/devise/hooks/csrf_cleaner.rb index 28d4aea8b..4a6473955 100644 --- a/lib/devise/hooks/csrf_cleaner.rb +++ b/lib/devise/hooks/csrf_cleaner.rb @@ -1,7 +1,14 @@ +# frozen_string_literal: true + Warden::Manager.after_authentication do |record, warden, options| clean_up_for_winning_strategy = !warden.winning_strategy.respond_to?(:clean_up_csrf?) || warden.winning_strategy.clean_up_csrf? if Devise.clean_up_csrf_token_on_authentication && clean_up_for_winning_strategy - warden.request.session.try(:delete, :_csrf_token) + if warden.request.respond_to?(:reset_csrf_token) + # Rails 7.1+ + warden.request.reset_csrf_token + else + warden.request.session.try(:delete, :_csrf_token) + end end end diff --git a/lib/devise/hooks/forgetable.rb b/lib/devise/hooks/forgetable.rb index 50e2062c2..317dc5474 100644 --- a/lib/devise/hooks/forgetable.rb +++ b/lib/devise/hooks/forgetable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Before logout hook to forget the user in the given scope, if it responds # to forget_me! Also clear remember token to ensure the user won't be # remembered again. Notice that we forget the user unless the record is not persisted. diff --git a/lib/devise/hooks/lockable.rb b/lib/devise/hooks/lockable.rb index c9d4df140..b11db1e87 100644 --- a/lib/devise/hooks/lockable.rb +++ b/lib/devise/hooks/lockable.rb @@ -1,10 +1,9 @@ +# frozen_string_literal: true + # After each sign in, if resource responds to failed_attempts, sets it to 0 # This is only triggered when the user is explicitly set (with set_user) Warden::Manager.after_set_user except: :fetch do |record, warden, options| - if record.respond_to?(:failed_attempts) && warden.authenticated?(options[:scope]) - unless record.failed_attempts.to_i.zero? - record.failed_attempts = 0 - record.save(validate: false) - end + if record.respond_to?(:reset_failed_attempts!) && warden.authenticated?(options[:scope]) + record.reset_failed_attempts! end end diff --git a/lib/devise/hooks/proxy.rb b/lib/devise/hooks/proxy.rb index 24de988ec..96b3a07e8 100644 --- a/lib/devise/hooks/proxy.rb +++ b/lib/devise/hooks/proxy.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Hooks # A small warden proxy so we can remember, forget and diff --git a/lib/devise/hooks/rememberable.rb b/lib/devise/hooks/rememberable.rb index 077be534e..345f2f240 100644 --- a/lib/devise/hooks/rememberable.rb +++ b/lib/devise/hooks/rememberable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Warden::Manager.after_set_user except: :fetch do |record, warden, options| scope = options[:scope] if record.respond_to?(:remember_me) && options[:store] != false && diff --git a/lib/devise/hooks/timeoutable.rb b/lib/devise/hooks/timeoutable.rb index 1bfa07d7a..f1e7f6d57 100644 --- a/lib/devise/hooks/timeoutable.rb +++ b/lib/devise/hooks/timeoutable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Each time a record is set we check whether its session has already timed out # or not, based on last request time. If so, the record is logged out and # redirected to the sign in page. Also, each time the request comes and the @@ -19,11 +21,11 @@ proxy = Devise::Hooks::Proxy.new(warden) - if record.timedout?(last_request_at) && - !env['devise.skip_timeout'] && + if !env['devise.skip_timeout'] && + record.timedout?(last_request_at) && !proxy.remember_me_is_active?(record) Devise.sign_out_all_scopes ? proxy.sign_out : proxy.sign_out(scope) - throw :warden, scope: scope, message: :timeout + throw :warden, scope: scope, message: :timeout, locale: options.fetch(:locale, I18n.locale) end unless env['devise.skip_trackable'] diff --git a/lib/devise/hooks/trackable.rb b/lib/devise/hooks/trackable.rb index 9bb212881..53ac30dd3 100644 --- a/lib/devise/hooks/trackable.rb +++ b/lib/devise/hooks/trackable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # After each sign in, update sign in time, sign in count and sign in IP. # This is only triggered when the user is explicitly set (with set_user) # and on authentication. Retrieving the user from session (:fetch) does diff --git a/lib/devise/mailers/helpers.rb b/lib/devise/mailers/helpers.rb index 12cac733e..29a491970 100644 --- a/lib/devise/mailers/helpers.rb +++ b/lib/devise/mailers/helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Mailers module Helpers @@ -31,28 +33,22 @@ def headers_for(action, opts) subject: subject_for(action), to: resource.email, from: mailer_sender(devise_mapping), - reply_to: mailer_reply_to(devise_mapping), + reply_to: mailer_sender(devise_mapping), template_path: template_paths, template_name: action - }.merge(opts) + } + # Give priority to the mailer's default if they exists. + headers.delete(:from) if default_params[:from] + headers.delete(:reply_to) if default_params[:reply_to] + + headers.merge!(opts) @email = headers[:to] headers end - def mailer_reply_to(mapping) - mailer_sender(mapping, :reply_to) - end - - def mailer_from(mapping) - mailer_sender(mapping, :from) - end - - def mailer_sender(mapping, sender = :from) - default_sender = default_params[sender] - if default_sender.present? - default_sender.respond_to?(:to_proc) ? instance_eval(&default_sender) : default_sender - elsif Devise.mailer_sender.is_a?(Proc) + def mailer_sender(mapping) + if Devise.mailer_sender.is_a?(Proc) Devise.mailer_sender.call(mapping.name) else Devise.mailer_sender diff --git a/lib/devise/mapping.rb b/lib/devise/mapping.rb index af4a14127..8b1f94ced 100644 --- a/lib/devise/mapping.rb +++ b/lib/devise/mapping.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise # Responsible for handling devise mappings and routes configuration. Each # resource configured by devise_for in routes is actually creating a mapping @@ -28,7 +30,7 @@ class Mapping #:nodoc: alias :name :singular - # Receives an object and find a scope for it. If a scope cannot be found, + # Receives an object and finds a scope for it. If a scope cannot be found, # raises an error. If a symbol is given, it's considered to be the scope. def self.find_scope!(obj) obj = obj.devise_scope if obj.respond_to?(:devise_scope) @@ -44,7 +46,7 @@ def self.find_scope!(obj) raise "Could not find a valid mapping for #{obj.inspect}" end - def self.find_by_path!(path, path_type=:fullpath) + def self.find_by_path!(path, path_type = :fullpath) Devise.mappings.each_value { |m| return m if path.include?(m.send(path_type)) } raise "Could not find a valid mapping for path #{path.inspect}" end diff --git a/lib/devise/models.rb b/lib/devise/models.rb index 6419814de..fb7dd89b0 100644 --- a/lib/devise/models.rb +++ b/lib/devise/models.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Models class MissingAttribute < StandardError @@ -82,6 +84,7 @@ def devise(*modules) end devise_modules_hook! do + include Devise::Orm include Devise::Models::Authenticatable selected_modules.each do |m| diff --git a/lib/devise/models/authenticatable.rb b/lib/devise/models/authenticatable.rb index 6f2f4fbb5..df964537e 100644 --- a/lib/devise/models/authenticatable.rb +++ b/lib/devise/models/authenticatable.rb @@ -1,4 +1,5 @@ -require 'active_model/version' +# frozen_string_literal: true + require 'devise/hooks/activatable' require 'devise/hooks/csrf_cleaner' @@ -8,7 +9,7 @@ module Models # # == Options # - # Authenticatable adds the following options to devise_for: + # Authenticatable adds the following options to +devise+: # # * +authentication_keys+: parameters used for authentication. By default [:email]. # @@ -54,7 +55,7 @@ module Models module Authenticatable extend ActiveSupport::Concern - BLACKLIST_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at, + UNSAFE_ATTRIBUTES_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at, :remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at, :remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at] @@ -102,13 +103,13 @@ def authenticatable_salt # and passing a new list of attributes you want to exempt. All attributes # given to :except will simply add names to exempt to Devise internal list. def serializable_hash(options = nil) - options ||= {} - options[:except] = Array(options[:except]) + options = options.try(:dup) || {} + options[:except] = Array(options[:except]).dup if options[:force_except] options[:except].concat Array(options[:force_except]) else - options[:except].concat BLACKLIST_FOR_SERIALIZATION + options[:except].concat UNSAFE_ATTRIBUTES_FOR_SERIALIZATION end super(options) @@ -132,16 +133,18 @@ def devise_mailer # This is an internal method called every time Devise needs # to send a notification/mail. This can be overridden if you # need to customize the e-mail delivery logic. For instance, - # if you are using a queue to deliver e-mails (delayed job, - # sidekiq, resque, etc), you must add the delivery to the queue + # if you are using a queue to deliver e-mails (active job, delayed + # job, sidekiq, resque, etc), you must add the delivery to the queue # just after the transaction was committed. To achieve this, # you can override send_devise_notification to store the - # deliveries until the after_commit callback is triggered: + # deliveries until the after_commit callback is triggered. + # + # The following example uses Active Job's `deliver_later` : # # class User # devise :database_authenticatable, :confirmable # - # after_commit :send_pending_notifications + # after_commit :send_pending_devise_notifications # # protected # @@ -149,49 +152,47 @@ def devise_mailer # # If the record is new or changed then delay the # # delivery until the after_commit callback otherwise # # send now because after_commit will not be called. - # if new_record? || changed? - # pending_notifications << [notification, args] + # # For Rails < 6 use `changed?` instead of `saved_changes?`. + # if new_record? || saved_changes? + # pending_devise_notifications << [notification, args] # else - # message = devise_mailer.send(notification, self, *args) - # Remove once we move to Rails 4.2+ only. - # if message.respond_to?(:deliver_now) - # message.deliver_now - # else - # message.deliver - # end + # render_and_send_devise_message(notification, *args) # end # end # - # def send_pending_notifications - # pending_notifications.each do |notification, args| - # message = devise_mailer.send(notification, self, *args) - # Remove once we move to Rails 4.2+ only. - # if message.respond_to?(:deliver_now) - # message.deliver_now - # else - # message.deliver - # end + # private + # + # def send_pending_devise_notifications + # pending_devise_notifications.each do |notification, args| + # render_and_send_devise_message(notification, *args) # end # # # Empty the pending notifications array because the # # after_commit hook can be called multiple times which # # could cause multiple emails to be sent. - # pending_notifications.clear + # pending_devise_notifications.clear # end # - # def pending_notifications - # @pending_notifications ||= [] + # def pending_devise_notifications + # @pending_devise_notifications ||= [] + # end + # + # def render_and_send_devise_message(notification, *args) + # message = devise_mailer.send(notification, self, *args) + # + # # Deliver later with Active Job's `deliver_later` + # if message.respond_to?(:deliver_later) + # message.deliver_later + # else + # message.deliver_now + # end # end + # # end # def send_devise_notification(notification, *args) message = devise_mailer.send(notification, self, *args) - # Remove once we move to Rails 4.2+ only. - if message.respond_to?(:deliver_now) - message.deliver_now - else - message.deliver - end + message.deliver_now end def downcase_keys @@ -256,46 +257,38 @@ def http_authenticatable?(strategy) # end # # Finally, notice that Devise also queries for users in other scenarios - # besides authentication, for example when retrieving an user to send + # besides authentication, for example when retrieving a user to send # an e-mail for password reset. In such cases, find_for_authentication # is not called. def find_for_authentication(tainted_conditions) find_first_by_auth_conditions(tainted_conditions) end - def find_first_by_auth_conditions(tainted_conditions, opts={}) + def find_first_by_auth_conditions(tainted_conditions, opts = {}) to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts)) end # Find or initialize a record setting an error if it can't be found. - def find_or_initialize_with_error_by(attribute, value, error=:invalid) #:nodoc: + def find_or_initialize_with_error_by(attribute, value, error = :invalid) #:nodoc: find_or_initialize_with_errors([attribute], { attribute => value }, error) end # Find or initialize a record with group of attributes based on a list of required attributes. - def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc: - attributes = if attributes.respond_to? :permit! - attributes.slice(*required_attributes).permit!.to_h.with_indifferent_access - else - attributes.with_indifferent_access.slice(*required_attributes) - end - attributes.delete_if { |key, value| value.blank? } + def find_or_initialize_with_errors(required_attributes, attributes, error = :invalid) #:nodoc: + attributes.try(:permit!) + attributes = attributes.to_h.with_indifferent_access + .slice(*required_attributes) + .delete_if { |key, value| value.blank? } if attributes.size == required_attributes.size - record = find_first_by_auth_conditions(attributes) + record = find_first_by_auth_conditions(attributes) and return record end - unless record - record = new - + new(devise_parameter_filter.filter(attributes)).tap do |record| required_attributes.each do |key| - value = attributes[key] - record.send("#{key}=", value) - record.errors.add(key, value.present? ? error : :blank) + record.errors.add(key, attributes[key].blank? ? :blank : error) end end - - record end protected diff --git a/lib/devise/models/confirmable.rb b/lib/devise/models/confirmable.rb index 726b8fa91..1930086aa 100644 --- a/lib/devise/models/confirmable.rb +++ b/lib/devise/models/confirmable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Models # Confirmable is responsible to verify if an account is already confirmed to @@ -46,7 +48,7 @@ module Confirmable included do before_create :generate_confirmation_token, if: :confirmation_required? after_create :skip_reconfirmation_in_callback!, if: :send_confirmation_notification? - if respond_to?(:after_commit) # ActiveRecord + if Devise::Orm.active_record?(self) # ActiveRecord after_commit :send_on_create_confirmation_instructions, on: :create, if: :send_confirmation_notification? after_commit :send_reconfirmation_instructions, on: :update, if: :reconfirmation_required? else # Mongoid @@ -74,7 +76,7 @@ def self.required_fields(klass) # Confirm a user by setting it's confirmed_at to actual time. If the user # is already confirmed, add an error to email field. If the user is invalid # add errors - def confirm(args={}) + def confirm(args = {}) pending_any_confirmation do if confirmation_period_expired? self.errors.add(:email, :confirmation_period_expired, @@ -209,7 +211,10 @@ def confirmation_required? # confirmation_period_valid? # will always return true # def confirmation_period_valid? - self.class.allow_unconfirmed_access_for.nil? || (confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago) + return true if self.class.allow_unconfirmed_access_for.nil? + return false if self.class.allow_unconfirmed_access_for == 0.days + + confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago end # Checks if the user confirmation happens before the token becomes invalid @@ -253,44 +258,25 @@ def generate_confirmation_token! generate_confirmation_token && save(validate: false) end - if Devise.activerecord51? - def postpone_email_change_until_confirmation_and_regenerate_confirmation_token - @reconfirmation_required = true - self.unconfirmed_email = self.email - self.email = self.email_in_database - self.confirmation_token = nil - generate_confirmation_token - end - else - def postpone_email_change_until_confirmation_and_regenerate_confirmation_token - @reconfirmation_required = true - self.unconfirmed_email = self.email - self.email = self.email_was - self.confirmation_token = nil - generate_confirmation_token - end + def postpone_email_change_until_confirmation_and_regenerate_confirmation_token + @reconfirmation_required = true + # Force unconfirmed_email to be updated, even if the value hasn't changed, to prevent a + # race condition which could allow an attacker to confirm an email they don't own. See #5783. + devise_unconfirmed_email_will_change! + self.unconfirmed_email = self.email + self.email = self.devise_email_in_database + self.confirmation_token = nil + generate_confirmation_token end - if Devise.activerecord51? - def postpone_email_change? - postpone = self.class.reconfirmable && - will_save_change_to_email? && - !@bypass_confirmation_postpone && - self.email.present? && - (!@skip_reconfirmation_in_callback || !self.email_in_database.nil?) - @bypass_confirmation_postpone = false - postpone - end - else - def postpone_email_change? - postpone = self.class.reconfirmable && - email_changed? && - !@bypass_confirmation_postpone && - self.email.present? && - (!@skip_reconfirmation_in_callback || !self.email_was.nil?) - @bypass_confirmation_postpone = false - postpone - end + def postpone_email_change? + postpone = self.class.reconfirmable && + devise_will_save_change_to_email? && + !@bypass_confirmation_postpone && + self.email.present? && + (!@skip_reconfirmation_in_callback || !self.devise_email_in_database.nil?) + @bypass_confirmation_postpone = false + postpone end def reconfirmation_required? @@ -329,7 +315,7 @@ module ClassMethods # confirmation instructions to it. If not, try searching for a user by unconfirmed_email # field. If no user is found, returns a new user with an email not found error. # Options must contain the user email - def send_confirmation_instructions(attributes={}) + def send_confirmation_instructions(attributes = {}) confirmable = find_by_unconfirmed_email_with_errors(attributes) if reconfirmable unless confirmable.try(:persisted?) confirmable = find_or_initialize_with_errors(confirmation_keys, attributes, :not_found) @@ -343,7 +329,19 @@ def send_confirmation_instructions(attributes={}) # If the user is already confirmed, create an error for the user # Options must have the confirmation_token def confirm_by_token(confirmation_token) + # When the `confirmation_token` parameter is blank, if there are any users with a blank + # `confirmation_token` in the database, the first one would be confirmed here. + # The error is being manually added here to ensure no users are confirmed by mistake. + # This was done in the model for convenience, since validation errors are automatically + # displayed in the view. + if confirmation_token.blank? + confirmable = new + confirmable.errors.add(:confirmation_token, :blank) + return confirmable + end + confirmable = find_first_by_auth_conditions(confirmation_token: confirmation_token) + unless confirmable confirmation_digest = Devise.token_generator.digest(self, :confirmation_token, confirmation_token) confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_digest) diff --git a/lib/devise/models/database_authenticatable.rb b/lib/devise/models/database_authenticatable.rb index a981b91a7..e16b7d845 100644 --- a/lib/devise/models/database_authenticatable.rb +++ b/lib/devise/models/database_authenticatable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/strategies/database_authenticatable' module Devise @@ -5,12 +7,16 @@ module Models # Authenticatable Module, responsible for hashing the password and # validating the authenticity of a user while signing in. # + # This module defines a `password=` method. This method will hash the argument + # and store it in the `encrypted_password` column, bypassing any pre-existing + # `password` column if it exists. + # # == Options # - # DatabaseAuthenticatable adds the following options to devise_for: + # DatabaseAuthenticatable adds the following options to +devise+: # # * +pepper+: a random string used to provide a more secure hash. Use - # `rake secret` to generate new keys. + # `rails secret` to generate new keys. # # * +stretches+: the cost given to bcrypt. # @@ -33,6 +39,22 @@ module DatabaseAuthenticatable attr_accessor :password_confirmation end + def initialize(*args, &block) + @skip_email_changed_notification = false + @skip_password_change_notification = false + super + end + + # Skips sending the email changed notification after_update + def skip_email_changed_notification! + @skip_email_changed_notification = true + end + + # Skips sending the password change notification after_update + def skip_password_change_notification! + @skip_password_change_notification = true + end + def self.required_fields(klass) [:encrypted_password] + klass.authentication_keys end @@ -62,7 +84,7 @@ def clean_up_passwords # users to change relevant information like the e-mail without changing # their password). In case the password field is rejected, the confirmation # is also rejected as long as it is also blank. - def update_with_password(params, *options) + def update_with_password(params) current_password = params.delete(:current_password) if params[:password].blank? @@ -71,11 +93,11 @@ def update_with_password(params, *options) end result = if valid_password?(current_password) - update_attributes(params, *options) + update(params) else - self.assign_attributes(params, *options) - self.valid? - self.errors.add(:current_password, current_password.blank? ? :blank : :invalid) + assign_attributes(params) + valid? + errors.add(:current_password, current_password.blank? ? :blank : :invalid) false end @@ -90,16 +112,16 @@ def update_with_password(params, *options) # # Example: # - # def update_without_password(params, *options) + # def update_without_password(params) # params.delete(:email) # super(params) # end # - def update_without_password(params, *options) + def update_without_password(params) params.delete(:password) params.delete(:password_confirmation) - result = update_attributes(params, *options) + result = update(params) clean_up_passwords result end @@ -111,8 +133,8 @@ def destroy_with_password(current_password) result = if valid_password?(current_password) destroy else - self.valid? - self.errors.add(:current_password, current_password.blank? ? :blank : :invalid) + valid? + errors.add(:current_password, current_password.blank? ? :blank : :invalid) false end @@ -137,16 +159,9 @@ def authenticatable_salt encrypted_password[0,29] if encrypted_password end - if Devise.activerecord51? - # Send notification to user when email changes. - def send_email_changed_notification - send_devise_notification(:email_changed, to: email_before_last_save) - end - else - # Send notification to user when email changes. - def send_email_changed_notification - send_devise_notification(:email_changed, to: email_was) - end + # Send notification to user when email changes. + def send_email_changed_notification + send_devise_notification(:email_changed, to: devise_email_before_last_save) end # Send notification to user when password changes. @@ -159,30 +174,18 @@ def send_password_change_notification # Hashes the password using bcrypt. Custom hash functions should override # this method to apply their own algorithm. # - # See https://github.com/plataformatec/devise-encryptable for examples + # See https://github.com/heartcombo/devise-encryptable for examples # of other hashing engines. def password_digest(password) Devise::Encryptor.digest(self.class, password) end - if Devise.activerecord51? - def send_email_changed_notification? - self.class.send_email_changed_notification && saved_change_to_email? - end - else - def send_email_changed_notification? - self.class.send_email_changed_notification && email_changed? - end + def send_email_changed_notification? + self.class.send_email_changed_notification && devise_saved_change_to_email? && !@skip_email_changed_notification end - if Devise.activerecord51? - def send_password_change_notification? - self.class.send_password_change_notification && saved_change_to_encrypted_password? - end - else - def send_password_change_notification? - self.class.send_password_change_notification && encrypted_password_changed? - end + def send_password_change_notification? + self.class.send_password_change_notification && devise_saved_change_to_encrypted_password? && !@skip_password_change_notification end module ClassMethods diff --git a/lib/devise/models/lockable.rb b/lib/devise/models/lockable.rb index fe05b255a..6ab0ce747 100644 --- a/lib/devise/models/lockable.rb +++ b/lib/devise/models/lockable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "devise/hooks/lockable" module Devise @@ -16,7 +18,7 @@ module Models # * +maximum_attempts+: how many attempts should be accepted before blocking the user. # * +lock_strategy+: lock the user account by :failed_attempts or :none. # * +unlock_strategy+: unlock the user account by :time, :email, :both or :none. - # * +unlock_in+: the time you want to lock the user after to lock happens. Only available when unlock_strategy is :time or :both. + # * +unlock_in+: the time you want to unlock the user after lock happens. Only available when unlock_strategy is :time or :both. # * +unlock_keys+: the keys you want to use when locking and unlocking an account # module Lockable @@ -55,6 +57,14 @@ def unlock_access! save(validate: false) end + # Resets failed attempts counter to 0. + def reset_failed_attempts! + if respond_to?(:failed_attempts) && !failed_attempts.to_i.zero? + self.failed_attempts = 0 + save(validate: false) + end + end + # Verifies whether a user is locked or not. def access_locked? !!locked_at && !lock_expired? @@ -74,7 +84,7 @@ def resend_unlock_instructions if_access_locked { send_unlock_instructions } end - # Overwrites active_for_authentication? from Devise::Models::Activatable for locking purposes + # Overwrites active_for_authentication? from Devise::Models::Authenticatable for locking purposes # by verifying whether a user is active to sign in or not based on locked? def active_for_authentication? super && !access_locked? @@ -99,8 +109,7 @@ def valid_for_authentication? if super && !access_locked? true else - self.failed_attempts ||= 0 - self.failed_attempts += 1 + increment_failed_attempts if attempts_exceeded? lock_access! unless access_locked? else @@ -110,6 +119,11 @@ def valid_for_authentication? end end + def increment_failed_attempts + self.class.increment_counter(:failed_attempts, id) + reload + end + def unauthenticated_message # If set to paranoid mode, do not show the locked message because it # leaks the existence of an account. @@ -162,7 +176,7 @@ module ClassMethods # unlock instructions to it. If not user is found, returns a new user # with an email not found error. # Options must contain the user's unlock keys - def send_unlock_instructions(attributes={}) + def send_unlock_instructions(attributes = {}) lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found) lockable.resend_unlock_instructions if lockable.persisted? lockable diff --git a/lib/devise/models/omniauthable.rb b/lib/devise/models/omniauthable.rb index c1faf37a9..6f4c8976d 100644 --- a/lib/devise/models/omniauthable.rb +++ b/lib/devise/models/omniauthable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/omniauth' module Devise @@ -6,11 +8,11 @@ module Models # # == Options # - # Oauthable adds the following options to devise_for: + # Oauthable adds the following options to +devise+: # # * +omniauth_providers+: Which providers are available to this model. It expects an array: # - # devise_for :database_authenticatable, :omniauthable, omniauth_providers: [:twitter] + # devise :database_authenticatable, :omniauthable, omniauth_providers: [:twitter] # module Omniauthable extend ActiveSupport::Concern diff --git a/lib/devise/models/recoverable.rb b/lib/devise/models/recoverable.rb index 7857b6868..b17c42aae 100644 --- a/lib/devise/models/recoverable.rb +++ b/lib/devise/models/recoverable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Models @@ -5,7 +7,7 @@ module Models # # ==Options # - # Recoverable adds the following options to devise_for: + # Recoverable adds the following options to +devise+: # # * +reset_password_keys+: the keys you want to use when recovering the password for an account # * +reset_password_within+: the time period within which the password must be reset or the token expires. @@ -97,24 +99,13 @@ def send_reset_password_instructions_notification(token) send_devise_notification(:reset_password_instructions, token, {}) end - if Devise.activerecord51? - def clear_reset_password_token? - encrypted_password_changed = respond_to?(:will_save_change_to_encrypted_password?) && will_save_change_to_encrypted_password? - authentication_keys_changed = self.class.authentication_keys.any? do |attribute| - respond_to?("will_save_change_to_#{attribute}?") && send("will_save_change_to_#{attribute}?") - end - - authentication_keys_changed || encrypted_password_changed + def clear_reset_password_token? + encrypted_password_changed = devise_respond_to_and_will_save_change_to_attribute?(:encrypted_password) + authentication_keys_changed = self.class.authentication_keys.any? do |attribute| + devise_respond_to_and_will_save_change_to_attribute?(attribute) end - else - def clear_reset_password_token? - encrypted_password_changed = respond_to?(:encrypted_password_changed?) && encrypted_password_changed? - authentication_keys_changed = self.class.authentication_keys.any? do |attribute| - respond_to?("#{attribute}_changed?") && send("#{attribute}_changed?") - end - authentication_keys_changed || encrypted_password_changed - end + authentication_keys_changed || encrypted_password_changed end module ClassMethods @@ -129,7 +120,7 @@ def with_reset_password_token(token) # password instructions to it. If user is not found, returns a new user # with an email not found error. # Attributes must contain the user's email - def send_reset_password_instructions(attributes={}) + def send_reset_password_instructions(attributes = {}) recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found) recoverable.send_reset_password_instructions if recoverable.persisted? recoverable @@ -140,7 +131,7 @@ def send_reset_password_instructions(attributes={}) # try saving the record. If not user is found, returns a new user # containing an error in reset_password_token attribute. # Attributes must contain reset_password_token, password and confirmation - def reset_password_by_token(attributes={}) + def reset_password_by_token(attributes = {}) original_token = attributes[:reset_password_token] reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token) diff --git a/lib/devise/models/registerable.rb b/lib/devise/models/registerable.rb index 1f10dd2e6..e55dac272 100644 --- a/lib/devise/models/registerable.rb +++ b/lib/devise/models/registerable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Models # Registerable is responsible for everything related to registering a new @@ -19,6 +21,8 @@ module ClassMethods def new_with_session(params, session) new(params) end + + Devise::Models.config(self, :sign_in_after_change_password) end end end diff --git a/lib/devise/models/rememberable.rb b/lib/devise/models/rememberable.rb index 8f3203111..a66979ad5 100644 --- a/lib/devise/models/rememberable.rb +++ b/lib/devise/models/rememberable.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'devise/strategies/rememberable' require 'devise/hooks/rememberable' require 'devise/hooks/forgetable' module Devise module Models - # Rememberable manages generating and clearing token for remember the user + # Rememberable manages generating and clearing token for remembering the user # from a saved cookie. Rememberable also has utility methods for dealing # with serializing the user into the cookie and back from the cookie, trying # to lookup the record based on the saved information. @@ -13,7 +15,7 @@ module Models # # == Options # - # Rememberable adds the following options in devise_for: + # Rememberable adds the following options to +devise+: # # * +remember_for+: the time you want the user will be remembered without # asking for credentials. After this time the user will be blocked and @@ -100,7 +102,7 @@ def after_remembered def remember_me?(token, generated_at) # TODO: Normalize the JSON type coercion along with the Timeoutable hook - # in a single place https://github.com/plataformatec/devise/blob/ffe9d6d406e79108cf32a2c6a1d0b3828849c40b/lib/devise/hooks/timeoutable.rb#L14-L18 + # in a single place https://github.com/heartcombo/devise/blob/ffe9d6d406e79108cf32a2c6a1d0b3828849c40b/lib/devise/hooks/timeoutable.rb#L14-L18 if generated_at.is_a?(String) generated_at = time_from_json(generated_at) end diff --git a/lib/devise/models/timeoutable.rb b/lib/devise/models/timeoutable.rb index d589e24a4..1d3ce2ae9 100644 --- a/lib/devise/models/timeoutable.rb +++ b/lib/devise/models/timeoutable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/hooks/timeoutable' module Devise @@ -9,7 +11,7 @@ module Models # # == Options # - # Timeoutable adds the following options to devise_for: + # Timeoutable adds the following options to +devise+: # # * +timeout_in+: the interval to timeout the user session without activity. # diff --git a/lib/devise/models/trackable.rb b/lib/devise/models/trackable.rb index a59652350..2328597c3 100644 --- a/lib/devise/models/trackable.rb +++ b/lib/devise/models/trackable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/hooks/trackable' module Devise @@ -20,7 +22,7 @@ def update_tracked_fields(request) self.last_sign_in_at = old_current || new_current self.current_sign_in_at = new_current - old_current, new_current = self.current_sign_in_ip, request.remote_ip + old_current, new_current = self.current_sign_in_ip, extract_ip_from(request) self.last_sign_in_ip = old_current || new_current self.current_sign_in_ip = new_current @@ -29,9 +31,21 @@ def update_tracked_fields(request) end def update_tracked_fields!(request) + # We have to check if the user is already persisted before running + # `save` here because invalid users can be saved if we don't. + # See https://github.com/heartcombo/devise/issues/4673 for more details. + return if new_record? + update_tracked_fields(request) save(validate: false) end + + protected + + def extract_ip_from(request) + request.remote_ip + end + end end end diff --git a/lib/devise/models/validatable.rb b/lib/devise/models/validatable.rb index 7a3973783..62486cfbe 100644 --- a/lib/devise/models/validatable.rb +++ b/lib/devise/models/validatable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Models # Validatable creates all needed validations for a user email and password. @@ -7,11 +9,13 @@ module Models # # == Options # - # Validatable adds the following options to devise_for: + # Validatable adds the following options to +devise+: # # * +email_regexp+: the regular expression used to validate e-mails; - # * +password_length+: a range expressing password length. Defaults to 8..72. + # * +password_length+: a range expressing password length. Defaults to 6..128. # + # Since +password_length+ is applied in a proc within `validates_length_of` it can be overridden + # at runtime. module Validatable # All validations used by this module. VALIDATIONS = [:validates_presence_of, :validates_uniqueness_of, :validates_format_of, @@ -27,17 +31,12 @@ def self.included(base) base.class_eval do validates_presence_of :email, if: :email_required? - if Devise.activerecord51? - validates_uniqueness_of :email, allow_blank: true, if: :will_save_change_to_email? - validates_format_of :email, with: email_regexp, allow_blank: true, if: :will_save_change_to_email? - else - validates_uniqueness_of :email, allow_blank: true, if: :email_changed? - validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? - end + validates_uniqueness_of :email, allow_blank: true, case_sensitive: true, if: :devise_will_save_change_to_email? + validates_format_of :email, with: email_regexp, allow_blank: true, if: :devise_will_save_change_to_email? validates_presence_of :password, if: :password_required? validates_confirmation_of :password, if: :password_required? - validates_length_of :password, within: password_length, allow_blank: true + validates_length_of :password, minimum: proc { password_length.min }, maximum: proc { password_length.max }, allow_blank: true end end @@ -45,7 +44,7 @@ def self.assert_validations_api!(base) #:nodoc: unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) } unless unavailable_validations.empty? - raise "Could not use :validatable module since #{base} does not respond " << + raise "Could not use :validatable module since #{base} does not respond " \ "to the following methods: #{unavailable_validations.to_sentence}." end end diff --git a/lib/devise/modules.rb b/lib/devise/modules.rb index 2af8820bd..d8cde834c 100644 --- a/lib/devise/modules.rb +++ b/lib/devise/modules.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'active_support/core_ext/object/with_options' Devise.with_options model: true do |d| diff --git a/lib/devise/omniauth.rb b/lib/devise/omniauth.rb index ff342fd73..f18df3053 100644 --- a/lib/devise/omniauth.rb +++ b/lib/devise/omniauth.rb @@ -1,15 +1,14 @@ +# frozen_string_literal: true + begin + gem "omniauth", ">= 1.0.0" + require "omniauth" - require "omniauth/version" rescue LoadError warn "Could not load 'omniauth'. Please ensure you have the omniauth gem >= 1.0.0 installed and listed in your Gemfile." raise end -unless OmniAuth::VERSION =~ /^1\./ - raise "You are using an old OmniAuth version, please ensure you have 1.0.0.pr2 version or later installed." -end - # Clean up the default path_prefix. It will be automatically set by Devise. OmniAuth.config.path_prefix = nil diff --git a/lib/devise/omniauth/config.rb b/lib/devise/omniauth/config.rb index e22d701ce..2d3749ffd 100644 --- a/lib/devise/omniauth/config.rb +++ b/lib/devise/omniauth/config.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module OmniAuth class StrategyNotFound < NameError diff --git a/lib/devise/omniauth/url_helpers.rb b/lib/devise/omniauth/url_helpers.rb index f2cc3dbcd..72eac65ed 100644 --- a/lib/devise/omniauth/url_helpers.rb +++ b/lib/devise/omniauth/url_helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module OmniAuth module UrlHelpers diff --git a/lib/devise/orm.rb b/lib/devise/orm.rb new file mode 100644 index 000000000..f00f397f0 --- /dev/null +++ b/lib/devise/orm.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +module Devise + module Orm # :nodoc: + def self.active_record?(model) + defined?(ActiveRecord) && model < ActiveRecord::Base + end + + def self.included(model) + if Devise::Orm.active_record?(model) + model.include DirtyTrackingActiveRecordMethods + else + model.include DirtyTrackingMongoidMethods + end + end + + module DirtyTrackingActiveRecordMethods + def devise_email_before_last_save + email_before_last_save + end + + def devise_email_in_database + email_in_database + end + + def devise_saved_change_to_email? + saved_change_to_email? + end + + def devise_saved_change_to_encrypted_password? + saved_change_to_encrypted_password? + end + + def devise_will_save_change_to_email? + will_save_change_to_email? + end + + def devise_unconfirmed_email_will_change! + unconfirmed_email_will_change! + end + + def devise_respond_to_and_will_save_change_to_attribute?(attribute) + respond_to?("will_save_change_to_#{attribute}?") && send("will_save_change_to_#{attribute}?") + end + end + + module DirtyTrackingMongoidMethods + def devise_email_before_last_save + respond_to?(:email_previously_was) ? email_previously_was : email_was + end + + def devise_email_in_database + email_was + end + + def devise_saved_change_to_email? + respond_to?(:email_previously_changed?) ? email_previously_changed? : email_changed? + end + + def devise_saved_change_to_encrypted_password? + respond_to?(:encrypted_password_previously_changed?) ? encrypted_password_previously_changed? : encrypted_password_changed? + end + + def devise_will_save_change_to_email? + email_changed? + end + + def devise_unconfirmed_email_will_change! + # Mongoid's will_change! doesn't force unchanged attributes into updates, + # so we override changed_attributes to make it see a difference. + unconfirmed_email_will_change! + changed_attributes["unconfirmed_email"] = nil + end + + def devise_respond_to_and_will_save_change_to_attribute?(attribute) + respond_to?("#{attribute}_changed?") && send("#{attribute}_changed?") + end + end + end +end diff --git a/lib/devise/orm/active_record.rb b/lib/devise/orm/active_record.rb index de1148258..0fecf64e3 100644 --- a/lib/devise/orm/active_record.rb +++ b/lib/devise/orm/active_record.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'orm_adapter/adapters/active_record' ActiveSupport.on_load(:active_record) do diff --git a/lib/devise/orm/mongoid.rb b/lib/devise/orm/mongoid.rb index cc2f1c55c..034501eff 100644 --- a/lib/devise/orm/mongoid.rb +++ b/lib/devise/orm/mongoid.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + ActiveSupport.on_load(:mongoid) do require 'orm_adapter/adapters/mongoid' diff --git a/lib/devise/parameter_filter.rb b/lib/devise/parameter_filter.rb index 63d06f903..11e6f9c05 100644 --- a/lib/devise/parameter_filter.rb +++ b/lib/devise/parameter_filter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise class ParameterFilter def initialize(case_insensitive_keys, strip_whitespace_keys) @@ -16,6 +18,8 @@ def filter(conditions) def filtered_hash_by_method_for_given_keys(conditions, method, condition_keys) condition_keys.each do |k| + next unless conditions.key?(k) + value = conditions[k] conditions[k] = value.send(method) if value.respond_to?(method) end diff --git a/lib/devise/parameter_sanitizer.rb b/lib/devise/parameter_sanitizer.rb index 0f6faee68..6d9523a4f 100644 --- a/lib/devise/parameter_sanitizer.rb +++ b/lib/devise/parameter_sanitizer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise # The +ParameterSanitizer+ deals with permitting specific parameters values # for each +Devise+ scope in the application. @@ -128,12 +130,23 @@ def permit(action, keys: nil, except: nil, &block) # # Returns an +ActiveSupport::HashWithIndifferentAccess+. def cast_to_hash(params) - # TODO: Remove the `with_indifferent_access` method call when we only support Rails 5+. - params && params.to_h.with_indifferent_access + params && params.to_h end def default_params - @params.fetch(@resource_name, {}) + if hashable_resource_params? + @params.fetch(@resource_name) + else + empty_params + end + end + + def hashable_resource_params? + @params[@resource_name].respond_to?(:permit) + end + + def empty_params + ActionController::Parameters.new({}) end def permit_keys(parameters, keys) diff --git a/lib/devise/rails.rb b/lib/devise/rails.rb index 6321c71d7..b5738853f 100644 --- a/lib/devise/rails.rb +++ b/lib/devise/rails.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/rails/routes' require 'devise/rails/warden_compat' @@ -15,6 +17,10 @@ class Engine < ::Rails::Engine app.reload_routes! if Devise.reload_routes end + initializer "devise.deprecator" do |app| + app.deprecators[:devise] = Devise.deprecator if app.respond_to?(:deprecators) + end + initializer "devise.url_helpers" do Devise.include_helpers(Devise::Controllers) end @@ -32,11 +38,7 @@ class Engine < ::Rails::Engine end initializer "devise.secret_key" do |app| - if app.respond_to?(:secrets) - Devise.secret_key ||= app.secrets.secret_key_base - elsif app.config.respond_to?(:secret_key_base) - Devise.secret_key ||= app.config.secret_key_base - end + Devise.secret_key ||= app.secret_key_base Devise.token_generator ||= if secret_key = Devise.secret_key @@ -45,5 +47,11 @@ class Engine < ::Rails::Engine ) end end + + initializer "devise.configure_zeitwerk" do + if Rails.autoloaders.zeitwerk_enabled? && !defined?(ActionMailer) + Rails.autoloaders.main.ignore("#{root}/app/mailers/devise/mailer.rb") + end + end end end diff --git a/lib/devise/rails/routes.rb b/lib/devise/rails/routes.rb index 9a02363e9..f43e62fea 100644 --- a/lib/devise/rails/routes.rb +++ b/lib/devise/rails/routes.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_support/core_ext/object/try" require "active_support/core_ext/hash/slice" @@ -133,10 +135,10 @@ class Mapper # * failure_app: a rack app which is invoked whenever there is a failure. Strings representing a given # are also allowed as parameter. # - # * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :get), + # * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :delete), # if you wish to restrict this to accept only :post or :delete requests you should do: # - # devise_for :users, sign_out_via: [:post, :delete] + # devise_for :users, sign_out_via: [:get, :post] # # You need to make sure that your sign_out controls trigger a request with a matching HTTP method. # @@ -233,7 +235,6 @@ def devise_for(*resources) options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {}) options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {}) options[:options] = @scope[:options] || {} - options[:options][:format] = false if options[:format] == false resources.map!(&:to_sym) @@ -285,7 +286,7 @@ def devise_for(*resources) # root to: "admin/dashboard#show", as: :user_root # end # - def authenticate(scope=nil, block=nil) + def authenticate(scope = nil, block = nil) constraints_for(:authenticate!, scope, block) do yield end @@ -309,7 +310,7 @@ def authenticate(scope=nil, block=nil) # # root to: 'landing#show' # - def authenticated(scope=nil, block=nil) + def authenticated(scope = nil, block = nil) constraints_for(:authenticate?, scope, block) do yield end @@ -326,7 +327,7 @@ def authenticated(scope=nil, block=nil) # # root to: 'dashboard#show' # - def unauthenticated(scope=nil) + def unauthenticated(scope = nil) constraint = lambda do |request| not request.env["warden"].authenticate? scope: scope end @@ -411,7 +412,7 @@ def devise_registration(mapping, controllers) #:nodoc: controller: controllers[:registrations] } - resource :registration, options do + resource :registration, **options do get :cancel end end @@ -445,7 +446,7 @@ def devise_omniauth_callback(mapping, controllers) #:nodoc: match "#{path_prefix}/#{provider}", to: "#{controllers[:omniauth_callbacks]}#passthru", as: "#{provider}_omniauth_authorize", - via: [:get, :post] + via: OmniAuth.config.allowed_request_methods match "#{path_prefix}/#{provider}/callback", to: "#{controllers[:omniauth_callbacks]}##{provider}", @@ -460,7 +461,7 @@ def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc: current_scope = @scope.dup exclusive = { as: new_as, path: new_path, module: nil } - exclusive.merge!(options.slice(:constraints, :defaults, :options)) + exclusive.merge!(options.slice(:constraints, :format, :defaults, :options)) if @scope.respond_to? :new @scope = @scope.new exclusive @@ -472,7 +473,7 @@ def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc: @scope = current_scope end - def constraints_for(method_to_apply, scope=nil, block=nil) + def constraints_for(method_to_apply, scope = nil, block = nil) constraint = lambda do |request| request.env['warden'].send(method_to_apply, scope: scope) && (block.nil? || block.call(request.env["warden"].user(scope))) diff --git a/lib/devise/rails/warden_compat.rb b/lib/devise/rails/warden_compat.rb index 553e8e44a..3db7ecaea 100644 --- a/lib/devise/rails/warden_compat.rb +++ b/lib/devise/rails/warden_compat.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Warden::Mixins::Common def request @request ||= ActionDispatch::Request.new(env) diff --git a/lib/devise/strategies/authenticatable.rb b/lib/devise/strategies/authenticatable.rb index 13249e825..2af7a741c 100644 --- a/lib/devise/strategies/authenticatable.rb +++ b/lib/devise/strategies/authenticatable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/strategies/base' module Devise @@ -26,7 +28,7 @@ def clean_up_csrf? private # Receives a resource and check if it is valid by calling valid_for_authentication? - # An optional block that will be triggered while validating can be optionally + # A block that will be triggered while validating can be optionally # given as parameter. Check Devise::Models::Authenticatable.valid_for_authentication? # for more information. # diff --git a/lib/devise/strategies/base.rb b/lib/devise/strategies/base.rb index ee5c8c7f4..998e6a367 100644 --- a/lib/devise/strategies/base.rb +++ b/lib/devise/strategies/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Strategies # Base strategy for Devise. Responsible for verifying correct scope and mapping. diff --git a/lib/devise/strategies/database_authenticatable.rb b/lib/devise/strategies/database_authenticatable.rb index 3d8f40726..f7e007d14 100644 --- a/lib/devise/strategies/database_authenticatable.rb +++ b/lib/devise/strategies/database_authenticatable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/strategies/authenticatable' module Devise @@ -14,8 +16,13 @@ def authenticate! success!(resource) end + # In paranoid mode, hash the password even when a resource doesn't exist for the given authentication key. + # This is necessary to prevent enumeration attacks - e.g. the request is faster when a resource doesn't + # exist in the database if the password hashing algorithm is not called. mapping.to.new.password = password if !hashed && Devise.paranoid - fail(:not_found_in_database) unless resource + unless resource + Devise.paranoid ? fail(:invalid) : fail(:not_found_in_database) + end end end end diff --git a/lib/devise/strategies/rememberable.rb b/lib/devise/strategies/rememberable.rb index 3a09a6b4e..fe20804f6 100644 --- a/lib/devise/strategies/rememberable.rb +++ b/lib/devise/strategies/rememberable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'devise/strategies/authenticatable' module Devise diff --git a/lib/devise/test/controller_helpers.rb b/lib/devise/test/controller_helpers.rb index 89060e572..d3522a346 100644 --- a/lib/devise/test/controller_helpers.rb +++ b/lib/devise/test/controller_helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise module Test # `Devise::Test::ControllerHelpers` provides a facility to test controllers @@ -35,6 +37,8 @@ def process(*) @response end + ruby2_keywords(:process) if respond_to?(:ruby2_keywords, true) + # We need to set up the environment variables and the response in the controller. def setup_controller_for_warden #:nodoc: @request.env['action_controller.instance'] = @controller @@ -60,17 +64,7 @@ def warden #:nodoc: # # sign_in users(:alice) # sign_in users(:alice), scope: :admin - def sign_in(resource, deprecated = nil, scope: nil) - if deprecated.present? - scope = resource - resource = deprecated - - ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc - [Devise] sign_in(:#{scope}, resource) on controller tests is deprecated and will be removed from Devise. - Please use sign_in(resource, scope: :#{scope}) instead. - DEPRECATION - end - + def sign_in(resource, scope: nil) scope ||= Devise::Mapping.find_scope!(resource) warden.instance_variable_get(:@users).delete(scope) @@ -138,7 +132,7 @@ def _process_unauthenticated(env, options = {}) status, headers, response = Devise.warden_config[:failure_app].call(env).to_a @controller.response.headers.merge!(headers) @controller.status = status - @controller.response.body = response.body + @controller.response_body = response.body nil # causes process return @response end diff --git a/lib/devise/test/integration_helpers.rb b/lib/devise/test/integration_helpers.rb index e39b67924..0c7c910a7 100644 --- a/lib/devise/test/integration_helpers.rb +++ b/lib/devise/test/integration_helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise # Devise::Test::IntegrationHelpers is a helper module for facilitating # authentication on Rails integration tests to bypass the required steps for @@ -26,7 +28,7 @@ def self.included(base) end end - # Signs in a specific resource, mimicking a successfull sign in + # Signs in a specific resource, mimicking a successful sign in # operation through +Devise::SessionsController#create+. # # * +resource+ - The resource that should be authenticated diff --git a/lib/devise/test_helpers.rb b/lib/devise/test_helpers.rb deleted file mode 100644 index fbaed4cd8..000000000 --- a/lib/devise/test_helpers.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Devise - module TestHelpers - def self.included(base) - base.class_eval do - ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc - [Devise] including `Devise::TestHelpers` is deprecated and will be removed from Devise. - For controller tests, please include `Devise::Test::ControllerHelpers` instead. - DEPRECATION - include Devise::Test::ControllerHelpers - end - end - end -end diff --git a/lib/devise/time_inflector.rb b/lib/devise/time_inflector.rb index 94795afdb..db3f65580 100644 --- a/lib/devise/time_inflector.rb +++ b/lib/devise/time_inflector.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_support/core_ext/module/delegation" module Devise diff --git a/lib/devise/token_generator.rb b/lib/devise/token_generator.rb index 636a1e788..9eb74a046 100644 --- a/lib/devise/token_generator.rb +++ b/lib/devise/token_generator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'openssl' module Devise diff --git a/lib/devise/version.rb b/lib/devise/version.rb index ac983193b..6576edddf 100644 --- a/lib/devise/version.rb +++ b/lib/devise/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise - VERSION = "4.3.0".freeze + VERSION = "5.0.4".freeze end diff --git a/lib/generators/active_record/devise_generator.rb b/lib/generators/active_record/devise_generator.rb index ffcca8705..89b2f94dd 100644 --- a/lib/generators/active_record/devise_generator.rb +++ b/lib/generators/active_record/devise_generator.rb @@ -1,19 +1,23 @@ +# frozen_string_literal: true + require 'rails/generators/active_record' require 'generators/devise/orm_helpers' module ActiveRecord module Generators - class DeviseGenerator < ActiveRecord::Generators::Base + class DeviseGenerator < Base argument :attributes, type: :array, default: [], banner: "field:type field:type" + class_option :primary_key_type, type: :string, desc: "The type for primary key" + include Devise::Generators::OrmHelpers source_root File.expand_path("../templates", __FILE__) def copy_devise_migration if (behavior == :invoke && model_exists?) || (behavior == :revoke && migration_exists?(table_name)) - migration_template "migration_existing.rb", "db/migrate/add_devise_to_#{table_name}.rb", migration_version: migration_version + migration_template "migration_existing.rb", "#{migration_path}/add_devise_to_#{table_name}.rb", migration_version: migration_version else - migration_template "migration.rb", "db/migrate/devise_create_#{table_name}.rb", migration_version: migration_version + migration_template "migration.rb", "#{migration_path}/devise_create_#{table_name}.rb", migration_version: migration_version end end @@ -50,11 +54,11 @@ def migration_data t.datetime :remember_created_at ## Trackable - t.integer :sign_in_count, default: 0, null: false - t.datetime :current_sign_in_at - t.datetime :last_sign_in_at - t.#{ip_column} :current_sign_in_ip - t.#{ip_column} :last_sign_in_ip + # t.integer :sign_in_count, default: 0, null: false + # t.datetime :current_sign_in_at + # t.datetime :last_sign_in_at + # t.#{ip_column} :current_sign_in_ip + # t.#{ip_column} :last_sign_in_ip ## Confirmable # t.string :confirmation_token @@ -78,19 +82,37 @@ def inet? postgresql? end - def rails5? - Rails.version.start_with? '5' + def rails61_and_up? + Rails::VERSION::MAJOR > 6 || (Rails::VERSION::MAJOR == 6 && Rails::VERSION::MINOR >= 1) end def postgresql? - config = ActiveRecord::Base.configurations[Rails.env] - config && config['adapter'] == 'postgresql' + ar_config && ar_config['adapter'] == 'postgresql' + end + + def ar_config + if ActiveRecord::Base.configurations.respond_to?(:configs_for) + if rails61_and_up? + ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, name: "primary").configuration_hash + else + ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: "primary").config + end + else + ActiveRecord::Base.configurations[Rails.env] + end + end + + def migration_version + "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" end - def migration_version - if rails5? - "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" - end + def primary_key_type + primary_key_string + end + + def primary_key_string + key_string = options[:primary_key_type] + ", id: :#{key_string}" if key_string end end end diff --git a/lib/generators/active_record/templates/migration.rb b/lib/generators/active_record/templates/migration.rb index 2df528a99..ad8512497 100644 --- a/lib/generators/active_record/templates/migration.rb +++ b/lib/generators/active_record/templates/migration.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> def change - create_table :<%= table_name %> do |t| + create_table :<%= table_name %><%= primary_key_type %> do |t| <%= migration_data -%> <% attributes.each do |attribute| -%> diff --git a/lib/generators/active_record/templates/migration_existing.rb b/lib/generators/active_record/templates/migration_existing.rb index d7893343e..a44e5413e 100644 --- a/lib/generators/active_record/templates/migration_existing.rb +++ b/lib/generators/active_record/templates/migration_existing.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> def self.up change_table :<%= table_name %> do |t| diff --git a/lib/generators/devise/controllers_generator.rb b/lib/generators/devise/controllers_generator.rb index 803ba0412..d96d3d33e 100644 --- a/lib/generators/devise/controllers_generator.rb +++ b/lib/generators/devise/controllers_generator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails/generators/base' module Devise @@ -9,14 +11,14 @@ class ControllersGenerator < Rails::Generators::Base Create inherited Devise controllers in your app/controllers folder. Use -c to specify which controller you want to overwrite. - If you do no specify a controller, all controllers will be created. + If you do not specify a controller, all controllers will be created. For example: rails generate devise:controllers users -c=sessions This will create a controller class at app/controllers/users/sessions_controller.rb like this: - class Users::ConfirmationsController < Devise::ConfirmationsController + class Users::SessionsController < Devise::SessionsController content... end DESC diff --git a/lib/generators/devise/devise_generator.rb b/lib/generators/devise/devise_generator.rb index 80503951d..560d0da77 100644 --- a/lib/generators/devise/devise_generator.rb +++ b/lib/generators/devise/devise_generator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails/generators/named_base' module Devise @@ -8,15 +10,15 @@ class DeviseGenerator < Rails::Generators::NamedBase namespace "devise" source_root File.expand_path("../templates", __FILE__) - desc "Generates a model with the given NAME (if one does not exist) with devise " << + desc "Generates a model with the given NAME (if one does not exist) with devise " \ "configuration plus a migration file and devise routes." - hook_for :orm + hook_for :orm, required: true class_option :routes, desc: "Generate routes", type: :boolean, default: true def add_devise_routes - devise_route = "devise_for :#{plural_name}" + devise_route = "devise_for :#{plural_name}".dup devise_route << %Q(, class_name: "#{class_name}") if class_name.include?("::") devise_route << %Q(, skip: :all) unless options.routes? route devise_route diff --git a/lib/generators/devise/install_generator.rb b/lib/generators/devise/install_generator.rb index 6c6626b1a..78f3303d6 100644 --- a/lib/generators/devise/install_generator.rb +++ b/lib/generators/devise/install_generator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails/generators/base' require 'securerandom' @@ -9,7 +11,7 @@ class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../../templates", __FILE__) desc "Creates a Devise initializer and copy locale files to your application." - class_option :orm + class_option :orm, required: true def copy_initializer unless options[:orm] @@ -35,10 +37,6 @@ def copy_locale def show_readme readme "README" if behavior == :invoke end - - def rails_4? - Rails::VERSION::MAJOR == 4 - end end end end diff --git a/lib/generators/devise/orm_helpers.rb b/lib/generators/devise/orm_helpers.rb index f67204b37..18c8526a5 100644 --- a/lib/generators/devise/orm_helpers.rb +++ b/lib/generators/devise/orm_helpers.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + module Devise module Generators module OrmHelpers def model_contents buffer = <<-CONTENT # Include default devise modules. Others available are: - # :confirmable, :lockable, :timeoutable and :omniauthable + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, - :recoverable, :rememberable, :trackable, :validatable + :recoverable, :rememberable, :validatable CONTENT buffer @@ -23,7 +25,7 @@ def migration_exists?(table_name) end def migration_path - @migration_path ||= File.join("db", "migrate") + db_migrate_path end def model_path diff --git a/lib/generators/devise/views_generator.rb b/lib/generators/devise/views_generator.rb index d5d831f1d..bc271743c 100644 --- a/lib/generators/devise/views_generator.rb +++ b/lib/generators/devise/views_generator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails/generators/base' module Devise @@ -21,13 +23,6 @@ module ViewPathTemplates #:nodoc: public_task :copy_views end - # TODO: Add this to Rails itself - module ClassMethods - def hide! - Rails::Generators.hide_namespace self.namespace - end - end - def copy_views if options[:views] options[:views].each do |directory| @@ -47,7 +42,7 @@ def copy_views def view_directory(name, _target_path = nil) directory name.to_s, _target_path || "#{target_path}/#{name}" do |content| if scope - content.gsub "devise/shared/links", "#{plural_scope}/shared/links" + content.gsub("devise/shared", "#{plural_scope}/shared") else content end @@ -139,7 +134,11 @@ class ViewsGenerator < Rails::Generators::Base default: defined?(SimpleForm) ? "simple_form_for" : "form_for" hook_for :markerb, desc: "Generate markerb instead of erb mail views", - default: defined?(Markerb) ? :markerb : :erb, + default: defined?(Markerb), + type: :boolean + + hook_for :erb, desc: "Generate erb mail views", + default: !defined?(Markerb), type: :boolean end end diff --git a/lib/generators/mongoid/devise_generator.rb b/lib/generators/mongoid/devise_generator.rb index 4ff57f06a..777f3d6bc 100644 --- a/lib/generators/mongoid/devise_generator.rb +++ b/lib/generators/mongoid/devise_generator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails/generators/named_base' require 'generators/devise/orm_helpers' @@ -32,11 +34,11 @@ def migration_data field :remember_created_at, type: Time ## Trackable - field :sign_in_count, type: Integer, default: 0 - field :current_sign_in_at, type: Time - field :last_sign_in_at, type: Time - field :current_sign_in_ip, type: String - field :last_sign_in_ip, type: String + # field :sign_in_count, type: Integer, default: 0 + # field :current_sign_in_at, type: Time + # field :last_sign_in_at, type: Time + # field :current_sign_in_ip, type: String + # field :last_sign_in_ip, type: String ## Confirmable # field :confirmation_token, type: String diff --git a/lib/generators/templates/README b/lib/generators/templates/README index b76482806..c89920b0c 100644 --- a/lib/generators/templates/README +++ b/lib/generators/templates/README @@ -1,6 +1,6 @@ =============================================================================== -Some setup you must do manually if you haven't yet: +Depending on your application's configuration some manual setup may be required: 1. Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment @@ -10,10 +10,14 @@ Some setup you must do manually if you haven't yet: In production, :host should be set to the actual host of your application. + * Required for all applications. * + 2. Ensure you have defined root_url to *something* in your config/routes.rb. For example: root to: "home#index" + + * Not required for API-only Applications * 3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example: @@ -21,8 +25,12 @@ Some setup you must do manually if you haven't yet:

<%= notice %>

<%= alert %>

+ * Not required for API-only Applications * + 4. You can copy Devise views (for customization) to your app by running: rails g devise:views + + * Not required * =============================================================================== diff --git a/lib/generators/templates/controllers/confirmations_controller.rb b/lib/generators/templates/controllers/confirmations_controller.rb index 480ee9a07..e0466111c 100644 --- a/lib/generators/templates/controllers/confirmations_controller.rb +++ b/lib/generators/templates/controllers/confirmations_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class <%= @scope_prefix %>ConfirmationsController < Devise::ConfirmationsController # GET /resource/confirmation/new # def new diff --git a/lib/generators/templates/controllers/omniauth_callbacks_controller.rb b/lib/generators/templates/controllers/omniauth_callbacks_controller.rb index cc122dc4f..29556cf6e 100644 --- a/lib/generators/templates/controllers/omniauth_callbacks_controller.rb +++ b/lib/generators/templates/controllers/omniauth_callbacks_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class <%= @scope_prefix %>OmniauthCallbacksController < Devise::OmniauthCallbacksController # You should configure your model like this: # devise :omniauthable, omniauth_providers: [:twitter] @@ -7,7 +9,7 @@ class <%= @scope_prefix %>OmniauthCallbacksController < Devise::OmniauthCallback # end # More info at: - # https://github.com/plataformatec/devise#omniauth + # https://github.com/heartcombo/devise#omniauth # GET|POST /resource/auth/twitter # def passthru diff --git a/lib/generators/templates/controllers/passwords_controller.rb b/lib/generators/templates/controllers/passwords_controller.rb index 3409d4359..afd468cc1 100644 --- a/lib/generators/templates/controllers/passwords_controller.rb +++ b/lib/generators/templates/controllers/passwords_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class <%= @scope_prefix %>PasswordsController < Devise::PasswordsController # GET /resource/password/new # def new diff --git a/lib/generators/templates/controllers/registrations_controller.rb b/lib/generators/templates/controllers/registrations_controller.rb index 3ffd29e91..cdd91acc1 100644 --- a/lib/generators/templates/controllers/registrations_controller.rb +++ b/lib/generators/templates/controllers/registrations_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class <%= @scope_prefix %>RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :configure_account_update_params, only: [:update] diff --git a/lib/generators/templates/controllers/sessions_controller.rb b/lib/generators/templates/controllers/sessions_controller.rb index 69afe4b4b..f229c9b4a 100644 --- a/lib/generators/templates/controllers/sessions_controller.rb +++ b/lib/generators/templates/controllers/sessions_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class <%= @scope_prefix %>SessionsController < Devise::SessionsController # before_action :configure_sign_in_params, only: [:create] diff --git a/lib/generators/templates/controllers/unlocks_controller.rb b/lib/generators/templates/controllers/unlocks_controller.rb index 0e2cced59..0eadbbf65 100644 --- a/lib/generators/templates/controllers/unlocks_controller.rb +++ b/lib/generators/templates/controllers/unlocks_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class <%= @scope_prefix %>UnlocksController < Devise::UnlocksController # GET /resource/unlock/new # def new diff --git a/lib/generators/templates/devise.rb b/lib/generators/templates/devise.rb old mode 100755 new mode 100644 index e3d9ede77..b36f281f2 --- a/lib/generators/templates/devise.rb +++ b/lib/generators/templates/devise.rb @@ -1,3 +1,11 @@ +# frozen_string_literal: true + +# Assuming you have not yet modified this file, each configuration option below +# is set to its default value. Note that some are commented out while others +# are not: uncommented lines are intended to protect your configuration from +# breaking changes in upgrades (i.e., in the event that future versions of +# Devise change the default values for those options). +# # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| @@ -8,6 +16,10 @@ # by default. You can change it below and use your own secret key. # config.secret_key = '<%= SecureRandom.hex(64) %>' + # ==> Controller configuration + # Configure the parent class to the devise controllers. + # config.parent_controller = 'DeviseController' + # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class @@ -62,7 +74,10 @@ # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will - # enable it only for database authentication. The supported strategies are: + # enable it only for database authentication. + # For API-only applications to support authentication "out-of-the-box", you will likely want to + # enable this with :database unless you are using a custom strategy. + # The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false @@ -97,15 +112,18 @@ # config.reload_routes = true # ==> Configuration for :database_authenticatable - # For bcrypt, this is the cost for hashing the password and defaults to 11. If + # For bcrypt, this is the cost for hashing the password and defaults to 12. If # using other algorithms, it sets how many times you want the password to be hashed. + # The number of stretches used for generating the hashed password are stored + # with the hashed password. This allows you to change the stretches without + # invalidating existing passwords. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # algorithm), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). - config.stretches = Rails.env.test? ? 1 : 11 + config.stretches = Rails.env.test? ? 1 : 12 # Set up a pepper to generate the hashed password. # config.pepper = '<%= SecureRandom.hex(64) %>' @@ -120,8 +138,11 @@ # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, - # access will be blocked just in the third day. Default is 0.days, meaning - # the user cannot access the website without confirming their account. + # access will be blocked just in the third day. + # You can also set it to nil, which will allow the user to access the website + # without confirming their account. + # Default is 0.days, meaning the user cannot access the website without + # confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their @@ -136,6 +157,9 @@ # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. + # Also, when used in conjunction with `send_email_changed_notification`, + # the notification is sent to the original email when the change is requested, + # not when the unconfirmed email is confirmed. config.reconfirmable = true # Defines which key will be used when confirming an account @@ -235,14 +259,14 @@ # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like - # :html, should redirect to the sign in page when the user does not have + # :html should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. - # config.navigational_formats = ['*/*', :html] + # config.navigational_formats = ['*/*', :html, :turbo_stream] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete @@ -256,9 +280,9 @@ # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # - # config.warden do |manager| - # manager.intercept_401 = false - # manager.default_strategies(scope: :user).unshift :some_external_strategy + # config.warden do |warden_config| + # warden_config.intercept_401 = false + # warden_config.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations @@ -274,4 +298,19 @@ # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' + + # ==> Hotwire/Turbo configuration + # 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 = <%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %> + config.responder.redirect_status = :see_other + + # ==> Configuration for :registerable + + # When set to false, does not sign a user in automatically after their password is + # changed. Defaults to true, so a user is signed in automatically after changing a password. + # config.sign_in_after_change_password = true end diff --git a/lib/generators/templates/simple_form_for/confirmations/new.html.erb b/lib/generators/templates/simple_form_for/confirmations/new.html.erb index 949b17277..f7b4a65c5 100644 --- a/lib/generators/templates/simple_form_for/confirmations/new.html.erb +++ b/lib/generators/templates/simple_form_for/confirmations/new.html.erb @@ -5,7 +5,11 @@ <%= f.full_error :confirmation_token %>
- <%= f.input :email, required: true, autofocus: true %> + <%= f.input :email, + required: true, + autofocus: true, + value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email), + input_html: { autocomplete: "email" } %>
diff --git a/lib/generators/templates/simple_form_for/passwords/edit.html.erb b/lib/generators/templates/simple_form_for/passwords/edit.html.erb index a938930bf..591cd8c85 100644 --- a/lib/generators/templates/simple_form_for/passwords/edit.html.erb +++ b/lib/generators/templates/simple_form_for/passwords/edit.html.erb @@ -7,8 +7,16 @@ <%= f.full_error :reset_password_token %>
- <%= f.input :password, label: "New password", required: true, autofocus: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %> - <%= f.input :password_confirmation, label: "Confirm your new password", required: true %> + <%= f.input :password, + label: "New password", + required: true, + autofocus: true, + hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), + input_html: { autocomplete: "new-password" } %> + <%= f.input :password_confirmation, + label: "Confirm your new password", + required: true, + input_html: { autocomplete: "new-password" } %>
diff --git a/lib/generators/templates/simple_form_for/passwords/new.html.erb b/lib/generators/templates/simple_form_for/passwords/new.html.erb index d1503e764..9a2c7d39f 100644 --- a/lib/generators/templates/simple_form_for/passwords/new.html.erb +++ b/lib/generators/templates/simple_form_for/passwords/new.html.erb @@ -4,11 +4,14 @@ <%= f.error_notification %>
- <%= f.input :email, required: true, autofocus: true %> + <%= f.input :email, + required: true, + autofocus: true, + input_html: { autocomplete: "email" } %>
- <%= f.button :submit, "Send me reset password instructions" %> + <%= f.button :submit, "Send me password reset instructions" %>
<% end %> diff --git a/lib/generators/templates/simple_form_for/registrations/edit.html.erb b/lib/generators/templates/simple_form_for/registrations/edit.html.erb index 5db350b5c..b3c0089ad 100644 --- a/lib/generators/templates/simple_form_for/registrations/edit.html.erb +++ b/lib/generators/templates/simple_form_for/registrations/edit.html.erb @@ -10,9 +10,17 @@

Currently waiting confirmation for: <%= resource.unconfirmed_email %>

<% end %> - <%= f.input :password, autocomplete: "off", hint: "leave it blank if you don't want to change it", required: false %> - <%= f.input :password_confirmation, required: false %> - <%= f.input :current_password, hint: "we need your current password to confirm your changes", required: true %> + <%= f.input :password, + hint: "leave it blank if you don't want to change it", + required: false, + input_html: { autocomplete: "new-password" } %> + <%= f.input :password_confirmation, + required: false, + input_html: { autocomplete: "new-password" } %> + <%= f.input :current_password, + hint: "we need your current password to confirm your changes", + required: true, + input_html: { autocomplete: "current-password" } %>
@@ -22,6 +30,6 @@

Cancel my account

-

Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

+
Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?", turbo_confirm: "Are you sure?" }, method: :delete %>
<%= link_to "Back", :back %> diff --git a/lib/generators/templates/simple_form_for/registrations/new.html.erb b/lib/generators/templates/simple_form_for/registrations/new.html.erb index 34b4279e5..5dafdd760 100644 --- a/lib/generators/templates/simple_form_for/registrations/new.html.erb +++ b/lib/generators/templates/simple_form_for/registrations/new.html.erb @@ -4,9 +4,17 @@ <%= f.error_notification %>
- <%= f.input :email, required: true, autofocus: true %> - <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %> - <%= f.input :password_confirmation, required: true %> + <%= f.input :email, + required: true, + autofocus: true, + input_html: { autocomplete: "email" }%> + <%= f.input :password, + required: true, + hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), + input_html: { autocomplete: "new-password" } %> + <%= f.input :password_confirmation, + required: true, + input_html: { autocomplete: "new-password" } %>
diff --git a/lib/generators/templates/simple_form_for/sessions/new.html.erb b/lib/generators/templates/simple_form_for/sessions/new.html.erb index 31f8a4d42..e542e6182 100644 --- a/lib/generators/templates/simple_form_for/sessions/new.html.erb +++ b/lib/generators/templates/simple_form_for/sessions/new.html.erb @@ -2,8 +2,13 @@ <%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
- <%= f.input :email, required: false, autofocus: true %> - <%= f.input :password, required: false %> + <%= f.input :email, + required: false, + autofocus: true, + input_html: { autocomplete: "email" } %> + <%= f.input :password, + required: false, + input_html: { autocomplete: "current-password" } %> <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
diff --git a/lib/generators/templates/simple_form_for/unlocks/new.html.erb b/lib/generators/templates/simple_form_for/unlocks/new.html.erb index 788f62e9e..c42de1738 100644 --- a/lib/generators/templates/simple_form_for/unlocks/new.html.erb +++ b/lib/generators/templates/simple_form_for/unlocks/new.html.erb @@ -5,7 +5,10 @@ <%= f.full_error :unlock_token %>
- <%= f.input :email, required: true, autofocus: true %> + <%= f.input :email, + required: true, + autofocus: true, + input_html: { autocomplete: "email" } %>
diff --git a/test/controllers/custom_registrations_controller_test.rb b/test/controllers/custom_registrations_controller_test.rb index 13e4eef28..683322ebf 100644 --- a/test/controllers/custom_registrations_controller_test.rb +++ b/test/controllers/custom_registrations_controller_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class CustomRegistrationsControllerTest < Devise::ControllerTestCase diff --git a/test/controllers/custom_strategy_test.rb b/test/controllers/custom_strategy_test.rb index b63bead68..1c9681264 100644 --- a/test/controllers/custom_strategy_test.rb +++ b/test/controllers/custom_strategy_test.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'test_helper' require 'ostruct' require 'warden/strategies/base' -require 'devise/test_helpers' +require 'devise/test/controller_helpers' class CustomStrategyController < ActionController::Base def new @@ -40,9 +42,7 @@ class CustomStrategyTest < Devise::ControllerTestCase test "custom strategy can return its own status code" do ret = get :new - # check the returned rack array - # assert ret.is_a?(Array) - # assert_equal 400, ret.first + # check the returned response assert ret.is_a?(ActionDispatch::TestResponse) # check the saved response as well. This is purely so that the response is available to the testing framework @@ -53,12 +53,10 @@ class CustomStrategyTest < Devise::ControllerTestCase test "custom strategy can return custom headers" do ret = get :new - # check the returned rack array - # assert ret.is_a?(Array) - # assert_equal ret.third['X-FOO'], 'BAR' + # check the returned response assert ret.is_a?(ActionDispatch::TestResponse) # check the saved response headers as well. - assert_equal response.headers['X-FOO'], 'BAR' + assert_equal 'BAR', response.headers['X-FOO'] end end diff --git a/test/controllers/helper_methods_test.rb b/test/controllers/helper_methods_test.rb index 59f913fdf..998cab6fb 100644 --- a/test/controllers/helper_methods_test.rb +++ b/test/controllers/helper_methods_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class ApiController < ActionController::Metal @@ -12,8 +14,8 @@ class HelperMethodsTest < Devise::ControllerTestCase end test 'does not respond_to helper or helper_method' do - refute_respond_to @controller.class, :helper - refute_respond_to @controller.class, :helper_method + assert_not_respond_to @controller.class, :helper + assert_not_respond_to @controller.class, :helper_method end test 'defines methods like current_user' do diff --git a/test/controllers/helpers_test.rb b/test/controllers/helpers_test.rb index acbfe4042..536b282c2 100644 --- a/test/controllers/helpers_test.rb +++ b/test/controllers/helpers_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' require 'ostruct' @@ -62,30 +64,30 @@ def setup end test 'proxy authenticate_user! to authenticate with user scope' do - @mock_warden.expects(:authenticate!).with(scope: :user) + @mock_warden.expects(:authenticate!).with({ scope: :user, locale: :en }) @controller.authenticate_user! end test 'proxy authenticate_user! options to authenticate with user scope' do - @mock_warden.expects(:authenticate!).with(scope: :user, recall: "foo") + @mock_warden.expects(:authenticate!).with({ scope: :user, recall: "foo", locale: :en }) @controller.authenticate_user!(recall: "foo") end test 'proxy authenticate_admin! to authenticate with admin scope' do - @mock_warden.expects(:authenticate!).with(scope: :admin) + @mock_warden.expects(:authenticate!).with({ scope: :admin, locale: :en }) @controller.authenticate_admin! end test 'proxy authenticate_[group]! to authenticate!? with each scope' do [:user, :admin].each do |scope| - @mock_warden.expects(:authenticate!).with(scope: scope) + @mock_warden.expects(:authenticate!).with({ scope: scope, locale: :en }) @mock_warden.expects(:authenticate?).with(scope: scope).returns(false) end @controller.authenticate_commenter! end test 'proxy authenticate_publisher_account! to authenticate with namespaced publisher account scope' do - @mock_warden.expects(:authenticate!).with(scope: :publisher_account) + @mock_warden.expects(:authenticate!).with({ scope: :publisher_account, locale: :en }) @controller.authenticate_publisher_account! end @@ -96,7 +98,7 @@ def setup test 'proxy admin_signed_in? to authenticatewith admin scope' do @mock_warden.expects(:authenticate).with(scope: :admin) - refute @controller.admin_signed_in? + assert_not @controller.admin_signed_in? end test 'proxy publisher_account_signed_in? to authenticate with namespaced publisher account scope' do @@ -125,14 +127,14 @@ def setup test 'sign in proxy to set_user on warden' do user = User.new @mock_warden.expects(:user).returns(nil) - @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) + @mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true) @controller.sign_in(:user, user) end test 'sign in accepts a resource as argument' do user = User.new @mock_warden.expects(:user).returns(nil) - @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) + @mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true) @controller.sign_in(user) end @@ -146,7 +148,7 @@ def setup test 'sign in again when the user is already in only if force is given' do user = User.new @mock_warden.expects(:user).returns(user) - @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) + @mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true) @controller.sign_in(user, force: true) end @@ -222,10 +224,20 @@ def setup assert_equal "/foo.bar", @controller.stored_location_for(:user) end - test 'store bad location for stores a location to redirect back to' do - assert_nil @controller.stored_location_for(:user) - @controller.store_location_for(:user, "/foo.bar\">Carry") - assert_nil @controller.stored_location_for(:user) + test 'store bad location for does not store a location to redirect back to' do + bad_locations = [ + "/foo.bar\">Carry", # unparseable + "http://[invalid", # unparseable + "javascript:alert(1)", # opaque URI, no path + "mailto:foo@example.com", # opaque URI, no path + nil, + ] + + bad_locations.each do |location| + @controller.store_location_for(:user, location) + assert_nil @controller.stored_location_for(:user), + "expected bad location #{location.inspect} to not be stored" + end end test 'store location for accepts a resource as argument' do @@ -267,7 +279,7 @@ def setup user = User.new @controller.session[:user_return_to] = "/foo.bar" @mock_warden.expects(:user).with(:user).returns(nil) - @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) + @mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true) @controller.expects(:redirect_to).with("/foo.bar") @controller.sign_in_and_redirect(user) end @@ -275,7 +287,7 @@ def setup test 'sign in and redirect uses the configured after sign in path' do admin = Admin.new @mock_warden.expects(:user).with(:admin).returns(nil) - @mock_warden.expects(:set_user).with(admin, scope: :admin).returns(true) + @mock_warden.expects(:set_user).with(admin, { scope: :admin }).returns(true) @controller.expects(:redirect_to).with(admin_root_path) @controller.sign_in_and_redirect(admin) end @@ -310,7 +322,17 @@ def setup end end + test 'is_flashing_format? depends on is_navigation_format?' do + @controller.expects(:is_navigational_format?).returns(true) + assert @controller.is_flashing_format? + end + + test 'is_flashing_format? is guarded against flash (middleware) not being loaded' do + @controller.request.expects(:respond_to?).with(:flash).returns(false) + assert_not @controller.is_flashing_format? + end + test 'is not a devise controller' do - refute @controller.devise_controller? + assert_not @controller.devise_controller? end end diff --git a/test/controllers/inherited_controller_i18n_messages_test.rb b/test/controllers/inherited_controller_i18n_messages_test.rb index 677ce30fd..f5d142d21 100644 --- a/test/controllers/inherited_controller_i18n_messages_test.rb +++ b/test/controllers/inherited_controller_i18n_messages_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class SessionsInheritedController < Devise::SessionsController diff --git a/test/controllers/internal_helpers_test.rb b/test/controllers/internal_helpers_test.rb index d2a96119c..124c8df06 100644 --- a/test/controllers/internal_helpers_test.rb +++ b/test/controllers/internal_helpers_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class MyController < DeviseController @@ -49,11 +51,11 @@ def setup end test 'resources methods are not controller actions' do - assert @controller.class.action_methods.delete_if { |m| m.include? 'commenter' }.empty? + assert_empty @controller.class.action_methods.delete_if { |m| m.include? 'commenter' } end test 'require no authentication tests current mapping' do - @mock_warden.expects(:authenticate?).with(:rememberable, scope: :user).returns(true) + @mock_warden.expects(:authenticate?).with(:rememberable, { scope: :user }).returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication @@ -69,7 +71,7 @@ def setup end test 'require no authentication sets a flash message' do - @mock_warden.expects(:authenticate?).with(:rememberable, scope: :user).returns(true) + @mock_warden.expects(:authenticate?).with(:rememberable, { scope: :user }).returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication @@ -119,7 +121,7 @@ def setup MyController.send(:public, :navigational_formats) swap Devise, navigational_formats: ['*/*', :html] do - refute @controller.navigational_formats.include?("*/*") + assert_not @controller.navigational_formats.include?("*/*") end MyController.send(:protected, :navigational_formats) diff --git a/test/controllers/load_hooks_controller_test.rb b/test/controllers/load_hooks_controller_test.rb index cf8f45446..63720c2e2 100644 --- a/test/controllers/load_hooks_controller_test.rb +++ b/test/controllers/load_hooks_controller_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class LoadHooksControllerTest < Devise::ControllerTestCase @@ -14,6 +16,6 @@ class LoadHooksControllerTest < Devise::ControllerTestCase end test 'load hook called when controller is loaded' do - assert DeviseController.instance_methods.include? :defined_by_load_hook + assert_includes DeviseController.instance_methods, :defined_by_load_hook end -end \ No newline at end of file +end diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb index 5c359eed5..8561027d9 100644 --- a/test/controllers/passwords_controller_test.rb +++ b/test/controllers/passwords_controller_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class PasswordsControllerTest < Devise::ControllerTestCase @@ -29,4 +31,9 @@ def put_update_with_params put_update_with_params assert_redirected_to custom_path end + + test 'calls after_database_authentication callback after sign_in immediately after password update' do + User.any_instance.expects :after_database_authentication + put_update_with_params + end end diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb index 69b65f379..9c970ab5d 100644 --- a/test/controllers/sessions_controller_test.rb +++ b/test/controllers/sessions_controller_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class SessionsControllerTest < Devise::ControllerTestCase @@ -72,7 +74,7 @@ class SessionsControllerTest < Devise::ControllerTestCase assert_template "devise/sessions/new" end - test "#destroy doesn't set the flash if the requested format is not navigational" do + test "#destroy doesn't set the flash and returns 204 status if the requested format is not navigational" do request.env["devise.mapping"] = Devise.mappings[:user] user = create_user user.confirm @@ -86,21 +88,15 @@ class SessionsControllerTest < Devise::ControllerTestCase assert_equal 204, @response.status end - if defined?(ActiveRecord) && ActiveRecord::Base.respond_to?(:mass_assignment_sanitizer) - test "#new doesn't raise mass-assignment exception even if sign-in key is attr_protected" do - request.env["devise.mapping"] = Devise.mappings[:user] - - ActiveRecord::Base.mass_assignment_sanitizer = :strict - User.class_eval { attr_protected :email } + test "#destroy returns 401 status if user is not signed in and the requested format is not navigational" do + request.env["devise.mapping"] = Devise.mappings[:user] + delete :destroy, format: 'json' + assert_equal 401, @response.status + end - begin - assert_nothing_raised do - get :new, user: { email: "allez viens!" } - end - ensure - ActiveRecord::Base.mass_assignment_sanitizer = :logger - User.class_eval { attr_accessible :email } - end - end + test "#destroy returns 302 status if user is not signed in and the requested format is navigational" do + request.env["devise.mapping"] = Devise.mappings[:user] + delete :destroy + assert_equal 302, @response.status end end diff --git a/test/controllers/url_helpers_test.rb b/test/controllers/url_helpers_test.rb index a4db09010..e4b6a3093 100644 --- a/test/controllers/url_helpers_test.rb +++ b/test/controllers/url_helpers_test.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'test_helper' class RoutesTest < Devise::ControllerTestCase tests ApplicationController - def assert_path_and_url(name, prepend_path=nil) + def assert_path_and_url(name, prepend_path = nil) @request.path = '/users/session' prepend_path = "#{prepend_path}_" if prepend_path diff --git a/test/delegator_test.rb b/test/delegator_test.rb index 65dda06e9..851afbca0 100644 --- a/test/delegator_test.rb +++ b/test/delegator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class DelegatorTest < ActiveSupport::TestCase diff --git a/test/devise_test.rb b/test/devise_test.rb old mode 100755 new mode 100644 index 07377cc62..a46be0d52 --- a/test/devise_test.rb +++ b/test/devise_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' module Devise @@ -69,8 +71,8 @@ class DeviseTest < ActiveSupport::TestCase test 'add new module using the helper method' do Devise.add_module(:coconut) assert_equal 1, Devise::ALL.select { |v| v == :coconut }.size - refute Devise::STRATEGIES.include?(:coconut) - refute defined?(Devise::Models::Coconut) + assert_not Devise::STRATEGIES.include?(:coconut) + assert_not defined?(Devise::Models::Coconut) Devise::ALL.delete(:coconut) Devise.add_module(:banana, strategy: :fruits) @@ -84,13 +86,18 @@ class DeviseTest < ActiveSupport::TestCase Devise::CONTROLLERS.delete(:kivi) end - test 'should complain when comparing empty or different sized passes' do + test 'Devise.secure_compare fails when comparing different strings or nil' do [nil, ""].each do |empty| - refute Devise.secure_compare(empty, "something") - refute Devise.secure_compare("something", empty) - refute Devise.secure_compare(empty, empty) + assert_not Devise.secure_compare(empty, "something") + assert_not Devise.secure_compare("something", empty) end - refute Devise.secure_compare("size_1", "size_four") + assert_not Devise.secure_compare(nil, nil) + assert_not Devise.secure_compare("size_1", "size_four") + end + + test 'Devise.secure_compare passes when strings are the same, even two empty strings' do + assert Devise.secure_compare("", "") + assert Devise.secure_compare("something", "something") end test 'Devise.email_regexp should match valid email addresses' do diff --git a/test/failure_app_test.rb b/test/failure_app_test.rb index ee6d19fbe..c9e4a56ce 100644 --- a/test/failure_app_test.rb +++ b/test/failure_app_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' require 'ostruct' @@ -26,6 +28,27 @@ def i18n_options(options) end end + class FailureWithoutRootPath < Devise::FailureApp + class FakeURLHelpers + end + + class FakeRoutesWithoutRoot + def url_helpers + FakeURLHelpers.new + end + end + + class FakeAppWithoutRootPath + def routes + FakeRoutesWithoutRoot.new + end + end + + def main_app + FakeAppWithoutRootPath.new + end + end + class FakeEngineApp < Devise::FailureApp class FakeEngine def new_user_on_engine_session_url _ @@ -42,17 +65,20 @@ def fake_engine end end + class RequestWithoutFlashSupport < ActionDispatch::Request + undef_method :flash + end + def self.context(name, &block) instance_eval(&block) end - def call_failure(env_params={}) + def call_failure(env_params = {}) env = { 'REQUEST_URI' => 'http://test.host/', 'HTTP_HOST' => 'test.host', 'REQUEST_METHOD' => 'GET', 'warden.options' => { scope: :user }, - 'rack.session' => {}, 'action_dispatch.request.formats' => Array(env_params.delete('formats') || Mime[:html]), 'rack.input' => "", 'warden' => OpenStruct.new(message: nil) @@ -64,7 +90,7 @@ def call_failure(env_params={}) end @response = (env.delete(:app) || Devise::FailureApp).call(env).to_a - @request = ActionDispatch::Request.new(env) + @request = (env.delete(:request_klass) || ActionDispatch::Request).new(env) end context 'When redirecting' do @@ -97,6 +123,13 @@ def call_failure(env_params={}) end end + test 'returns to the root path even when it\'s not defined' do + call_failure app: FailureWithoutRootPath + assert_equal 302, @response.first + assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] + assert_equal 'http://test.host/', @response.second['Location'] + end + test 'returns to the root path considering subdomain if no session path is available' do swap Devise, router_name: :fake_app do call_failure app: FailureWithSubdomain @@ -151,22 +184,44 @@ def call_failure(env_params={}) test 'uses the proxy failure message as symbol' do call_failure('warden' => OpenStruct.new(message: :invalid)) - assert_equal 'Invalid Email or password.', @request.flash[:alert] + assert_equal 'Invalid email or password.', @request.flash[:alert] assert_equal 'http://test.host/users/sign_in', @response.second["Location"] end test 'supports authentication_keys as a Hash for the flash message' do swap Devise, authentication_keys: { email: true, login: true } do call_failure('warden' => OpenStruct.new(message: :invalid)) - assert_equal 'Invalid Email, Login or password.', @request.flash[:alert] + assert_equal 'Invalid email, login or password.', @request.flash[:alert] end end + test 'downcases authentication_keys for the flash message' do + call_failure('warden' => OpenStruct.new(message: :invalid)) + assert_equal 'Invalid email or password.', @request.flash[:alert] + end + + test 'humanizes the flash message' do + call_failure('warden' => OpenStruct.new(message: :invalid)) + assert_equal @request.flash[:alert], @request.flash[:alert].humanize + end + test 'uses custom i18n options' do call_failure('warden' => OpenStruct.new(message: :does_not_exist), app: FailureWithI18nOptions) assert_equal 'User Steve does not exist', @request.flash[:alert] end + test 'respects the i18n locale passed via warden options when redirecting' do + call_failure('warden' => OpenStruct.new(message: :invalid), 'warden.options' => { locale: :"pt-BR" }) + + assert_equal 'Email ou senha inválidos.', @request.flash[:alert] + assert_equal 'http://test.host/users/sign_in', @response.second["Location"] + + call_failure('warden' => OpenStruct.new(message: :invalid), 'warden.options' => { locale: :de }) + + assert_equal 'E-Mail oder Passwort ist ungültig.', @request.flash[:alert] + assert_equal 'http://test.host/users/sign_in', @response.second["Location"] + end + test 'uses the proxy failure message as string' do call_failure('warden' => OpenStruct.new(message: 'Hello world')) assert_equal 'Hello world', @request.flash[:alert] @@ -180,14 +235,18 @@ def call_failure(env_params={}) test 'set up a default message' do call_failure - assert_match(/You are being/, @response.last.body) - assert_match(/redirected/, @response.last.body) - assert_match(/users\/sign_in/, @response.last.body) + if Devise::Test.rails71_and_up? + assert_empty @response.last.body + else + assert_match(/You are being/, @response.last.body) + assert_match(/redirected/, @response.last.body) + assert_match(/users\/sign_in/, @response.last.body) + end end test 'works for any navigational format' do - swap Devise, navigational_formats: [:xml] do - call_failure('formats' => Mime[:xml]) + swap Devise, navigational_formats: [:json] do + call_failure('formats' => Mime[:json]) assert_equal 302, @response.first end end @@ -202,7 +261,7 @@ def call_failure(env_params={}) context 'For HTTP request' do test 'return 401 status' do - call_failure('formats' => Mime[:xml]) + call_failure('formats' => Mime[:json]) assert_equal 401, @response.first end @@ -224,13 +283,13 @@ def call_failure(env_params={}) end test 'return WWW-authenticate headers if model allows' do - call_failure('formats' => Mime[:xml]) + call_failure('formats' => Mime[:json]) assert_equal 'Basic realm="Application"', @response.second["WWW-Authenticate"] end test 'does not return WWW-authenticate headers if model does not allow' do swap Devise, http_authenticatable: false do - call_failure('formats' => Mime[:xml]) + call_failure('formats' => Mime[:json]) assert_nil @response.second["WWW-Authenticate"] end end @@ -244,7 +303,13 @@ def call_failure(env_params={}) test 'uses the failure message as response body' do call_failure('formats' => Mime[:xml], 'warden' => OpenStruct.new(message: :invalid)) - assert_match 'Invalid Email or password.', @response.third.body + assert_match 'Invalid email or password.', @response.third.body + end + + test 'respects the i18n locale passed via warden options when responding to HTTP request' do + call_failure('formats' => Mime[:json], 'warden' => OpenStruct.new(message: :invalid), 'warden.options' => { locale: :"pt-BR" }) + + assert_equal %({"error":"Email ou senha inválidos."}), @response.third.body end context 'on ajax call' do @@ -292,8 +357,8 @@ def call_failure(env_params={}) "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Log in

') - assert @response.third.body.include?('Invalid Email or password.') + assert_includes @response.third.body, '

Log in

' + assert_includes @response.third.body, 'Invalid email or password.' end test 'calls the original controller if not confirmed email' do @@ -303,8 +368,8 @@ def call_failure(env_params={}) "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Log in

') - assert @response.third.body.include?('You have to confirm your email address before continuing.') + assert_includes @response.third.body, '

Log in

' + assert_includes @response.third.body, 'You have to confirm your email address before continuing.' end test 'calls the original controller if inactive account' do @@ -314,8 +379,8 @@ def call_failure(env_params={}) "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Log in

') - assert @response.third.body.include?('Your account is not activated yet.') + assert_includes @response.third.body, '

Log in

' + assert_includes @response.third.body, 'Your account is not activated yet.' end if Rails.application.config.respond_to?(:relative_url_root) @@ -327,12 +392,91 @@ def call_failure(env_params={}) "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Log in

') - assert @response.third.body.include?('Invalid Email or password.') - assert_equal @request.env["SCRIPT_NAME"], '/sample' - assert_equal @request.env["PATH_INFO"], '/users/sign_in' + assert_includes @response.third.body, '

Log in

' + assert_includes @response.third.body, 'Invalid email or password.' + assert_equal '/sample', @request.env["SCRIPT_NAME"] + assert_equal '/users/sign_in', @request.env["PATH_INFO"] end end end + + test 'respects the i18n locale passed via warden options when recalling original controller' do + env = { + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", locale: :"pt-BR" }, + "devise.mapping" => Devise.mappings[:user], + "warden" => stub_everything + } + call_failure(env) + + assert_includes @response.third.body, '

Log in

' + assert_includes @response.third.body, 'Email ou senha inválidos.' + end + + # TODO: remove conditional/else when supporting only responders 3.1+ + if ActionController::Responder.respond_to?(:error_status=) + test 'respects the configured responder `error_status` for the status code' do + swap Devise.responder, error_status: :unprocessable_entity do + env = { + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" }, + "devise.mapping" => Devise.mappings[:user], + "warden" => stub_everything + } + call_failure(env) + + assert_equal 422, @response.first + assert_includes @response.third.body, 'Invalid email or password.' + end + end + + test 'respects the configured responder `redirect_status` if the recall app returns a redirect status code' do + swap Devise.responder, redirect_status: :see_other do + env = { + "warden.options" => { recall: "devise/registrations#cancel", attempted_path: "/users/cancel" }, + "devise.mapping" => Devise.mappings[:user], + "warden" => stub_everything + } + call_failure(env) + + assert_equal 303, @response.first + end + end + else + test 'uses default hardcoded responder `error_status` for the status code since responders version does not support configuring it' do + env = { + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" }, + "devise.mapping" => Devise.mappings[:user], + "warden" => stub_everything + } + call_failure(env) + + assert_equal 200, @response.first + assert_includes @response.third.body, 'Invalid email or password.' + end + + test 'users default hardcoded responder `redirect_status` for the status code since responders version does not support configuring it' do + env = { + "warden.options" => { recall: "devise/registrations#cancel", attempted_path: "/users/cancel" }, + "devise.mapping" => Devise.mappings[:user], + "warden" => stub_everything + } + call_failure(env) + + assert_equal 302, @response.first + end + end + end + + context "Lazy loading" do + test "loads" do + assert_equal "yes it does", Devise::FailureApp.new.lazy_loading_works? + end + end + + context "Without Flash Support" do + test "returns to the default redirect location without a flash message" do + call_failure request_klass: RequestWithoutFlashSupport + assert_equal 302, @response.first + assert_equal 'http://test.host/users/sign_in', @response.second['Location'] + end end end diff --git a/test/generators/active_record_generator_test.rb b/test/generators/active_record_generator_test.rb index 79fab2b18..1c7d8219f 100644 --- a/test/generators/active_record_generator_test.rb +++ b/test/generators/active_record_generator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" if DEVISE_ORM == :active_record @@ -13,6 +15,16 @@ class ActiveRecordGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/devise_create_monsters.rb", /def change/ end + test "all files are properly created with changed db/migrate path in application configuration" do + old_paths = Rails.application.config.paths["db/migrate"] + Rails.application.config.paths.add "db/migrate", with: "db2/migrate" + + run_generator %w(monster) + assert_migration "db2/migrate/devise_create_monsters.rb", /def change/ + + Rails.application.config.paths["db/migrate"] = old_paths + end + test "all files for namespaced model are properly created" do run_generator %w(admin/monster) assert_migration "db/migrate/devise_create_admin_monsters.rb", /def change/ @@ -25,6 +37,19 @@ class ActiveRecordGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/add_devise_to_monsters.rb" end + test "update model migration when model exists with changed db/migrate path in application configuration" do + old_paths = Rails.application.config.paths["db/migrate"] + Rails.application.config.paths.add "db/migrate", with: "db2/migrate" + + run_generator %w(monster) + assert_file "app/models/monster.rb" + run_generator %w(monster) + + assert_migration "db2/migrate/add_devise_to_monsters.rb" + + Rails.application.config.paths["db/migrate"] = old_paths + end + test "all files are properly deleted" do run_generator %w(monster) run_generator %w(monster) @@ -43,6 +68,16 @@ class ActiveRecordGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/devise_create_monsters.rb", /t.string :current_sign_in_ip/ assert_migration "db/migrate/devise_create_monsters.rb", /t.string :last_sign_in_ip/ end + + test "do NOT add primary key type when NOT specified in rails generator" do + run_generator %w(monster) + assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters do/ + end + + test "add primary key type with rails 5 when specified in rails generator" do + run_generator ["monster", "--primary_key_type=uuid"] + assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters, id: :uuid do/ + end end module RailsEngine diff --git a/test/generators/controllers_generator_test.rb b/test/generators/controllers_generator_test.rb index 6df0f0c27..01bf970ec 100644 --- a/test/generators/controllers_generator_test.rb +++ b/test/generators/controllers_generator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class ControllersGeneratorTest < Rails::Generators::TestCase diff --git a/test/generators/devise_generator_test.rb b/test/generators/devise_generator_test.rb index b88246801..22112c69c 100644 --- a/test/generators/devise_generator_test.rb +++ b/test/generators/devise_generator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' require "generators/devise/devise_generator" @@ -35,5 +37,4 @@ def copy_routes FileUtils.mkdir_p(destination) FileUtils.cp routes, destination end - end diff --git a/test/generators/install_generator_test.rb b/test/generators/install_generator_test.rb index daf386d9c..3bb1b00f5 100644 --- a/test/generators/install_generator_test.rb +++ b/test/generators/install_generator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class InstallGeneratorTest < Rails::Generators::TestCase @@ -21,4 +23,12 @@ class InstallGeneratorTest < Rails::Generators::TestCase assert_no_file "config/initializers/devise.rb" assert_no_file "config/locales/devise.en.yml" end + + test "responder error_status based on rack version" do + run_generator(["--orm=active_record"]) + + error_status = Rack::RELEASE >= "3.1" ? :unprocessable_content : :unprocessable_entity + + assert_file "config/initializers/devise.rb", /config\.responder\.error_status = #{error_status.inspect}/ + end end diff --git a/test/generators/mongoid_generator_test.rb b/test/generators/mongoid_generator_test.rb index 51802e8e1..ea20b4cad 100644 --- a/test/generators/mongoid_generator_test.rb +++ b/test/generators/mongoid_generator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" if DEVISE_ORM == :mongoid diff --git a/test/generators/views_generator_test.rb b/test/generators/views_generator_test.rb index 7fcdff0d2..1f8f90f3c 100644 --- a/test/generators/views_generator_test.rb +++ b/test/generators/views_generator_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class ViewsGeneratorTest < Rails::Generators::TestCase @@ -9,16 +11,19 @@ class ViewsGeneratorTest < Rails::Generators::TestCase run_generator assert_files assert_shared_links + assert_error_messages end test "Assert all views are properly created with scope param" do run_generator %w(users) assert_files "users" assert_shared_links "users" + assert_error_messages "users" run_generator %w(admins) assert_files "admins" assert_shared_links "admins" + assert_error_messages "admins" end test "Assert views with simple form" do @@ -72,7 +77,7 @@ class ViewsGeneratorTest < Rails::Generators::TestCase assert_file "app/views/devise/mailer/reset_password_instructions.markerb" end - def assert_files(scope = nil, options={}) + def assert_files(scope = nil, options = {}) scope = "devise" if scope.nil? mail_template_engine = options[:mail_template_engine] || "html.erb" @@ -86,6 +91,7 @@ def assert_files(scope = nil, options={}) assert_file "app/views/#{scope}/registrations/edit.html.erb" assert_file "app/views/#{scope}/sessions/new.html.erb" assert_file "app/views/#{scope}/shared/_links.html.erb" + assert_file "app/views/#{scope}/shared/_error_messages.html.erb" assert_file "app/views/#{scope}/unlocks/new.html.erb" end @@ -100,4 +106,16 @@ def assert_shared_links(scope = nil) assert_file "app/views/#{scope}/sessions/new.html.erb", link assert_file "app/views/#{scope}/unlocks/new.html.erb", link end + + def assert_error_messages(scope = nil) + scope = "devise" if scope.nil? + link = /<%= render \"#{scope}\/shared\/error_messages\", resource: resource %>/ + + assert_file "app/views/#{scope}/passwords/edit.html.erb", link + assert_file "app/views/#{scope}/passwords/new.html.erb", link + assert_file "app/views/#{scope}/confirmations/new.html.erb", link + assert_file "app/views/#{scope}/registrations/new.html.erb", link + assert_file "app/views/#{scope}/registrations/edit.html.erb", link + assert_file "app/views/#{scope}/unlocks/new.html.erb", link + end end diff --git a/test/helpers/devise_helper_test.rb b/test/helpers/devise_helper_test.rb index 816d54267..b9fac7da3 100644 --- a/test/helpers/devise_helper_test.rb +++ b/test/helpers/devise_helper_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class DeviseHelperTest < Devise::IntegrationTest @@ -32,10 +34,6 @@ class DeviseHelperTest < Devise::IntegrationTest end test 'test errors.messages.not_saved with multiple errors from i18n' do - # Dirty tracking behavior prevents email validations from being applied: - # https://github.com/mongoid/mongoid/issues/756 - (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1 - get new_user_registration_path fill_in 'email', with: 'invalid_email' diff --git a/test/integration/authenticatable_test.rb b/test/integration/authenticatable_test.rb index 57b29aa9b..28d00399b 100644 --- a/test/integration/authenticatable_test.rb +++ b/test/integration/authenticatable_test.rb @@ -1,6 +1,14 @@ +# frozen_string_literal: true + require 'test_helper' class AuthenticationSanityTest < Devise::IntegrationTest + test 'sign in should not run model validations' do + sign_in_as_user + + assert_not User.validations_performed + end + test 'home should be accessible without sign in' do visit '/' assert_response :success @@ -10,13 +18,13 @@ class AuthenticationSanityTest < Devise::IntegrationTest test 'sign in as user should not authenticate admin scope' do sign_in_as_user assert warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) end test 'sign in as admin should not authenticate user scope' do sign_in_as_admin assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'sign in as both user and admin at same time' do @@ -31,7 +39,7 @@ class AuthenticationSanityTest < Devise::IntegrationTest sign_in_as_user sign_in_as_admin delete destroy_user_session_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert warden.authenticated?(:admin) end end @@ -42,7 +50,7 @@ class AuthenticationSanityTest < Devise::IntegrationTest sign_in_as_admin delete destroy_admin_session_path - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) assert warden.authenticated?(:user) end end @@ -53,8 +61,8 @@ class AuthenticationSanityTest < Devise::IntegrationTest sign_in_as_admin delete destroy_user_session_path - refute warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:user) + assert_not warden.authenticated?(:admin) end end @@ -64,21 +72,21 @@ class AuthenticationSanityTest < Devise::IntegrationTest sign_in_as_admin delete destroy_admin_session_path - refute warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:admin) + assert_not warden.authenticated?(:user) end end test 'not signed in as admin should not be able to access admins actions' do get admins_path assert_redirected_to new_admin_session_path - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) end test 'signed in as user should not be able to access admins actions' do sign_in_as_user assert warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) get admins_path assert_redirected_to new_admin_session_path @@ -87,7 +95,7 @@ class AuthenticationSanityTest < Devise::IntegrationTest test 'signed in as admin should be able to access admin actions' do sign_in_as_admin assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) get admins_path @@ -115,7 +123,7 @@ class AuthenticationSanityTest < Devise::IntegrationTest get root_path assert_contain 'Signed out successfully' - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) end test 'unauthenticated admin set message on sign out' do @@ -138,13 +146,13 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'not signed in should not be able to access private route (authenticate denied)' do get private_path assert_redirected_to new_admin_session_path - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) end test 'signed in as user should not be able to access private route restricted to admins (authenticate denied)' do sign_in_as_user assert warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) get private_path assert_redirected_to new_admin_session_path end @@ -152,7 +160,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as admin should be able to access private route restricted to admins (authenticate accepted)' do sign_in_as_admin assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) get private_path @@ -164,7 +172,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as inactive admin should not be able to access private/active route restricted to active admins (authenticate denied)' do sign_in_as_admin(active: false) assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert_raises ActionController::RoutingError do get "/private/active" @@ -174,7 +182,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as active admin should be able to access private/active route restricted to active admins (authenticate accepted)' do sign_in_as_admin(active: true) assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) get private_active_path @@ -186,7 +194,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as admin should get admin dashboard (authenticated accepted)' do sign_in_as_admin assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) get dashboard_path @@ -198,7 +206,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as user should get user dashboard (authenticated accepted)' do sign_in_as_user assert warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) get dashboard_path @@ -216,7 +224,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as inactive admin should not be able to access dashboard/active route restricted to active admins (authenticated denied)' do sign_in_as_admin(active: false) assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert_raises ActionController::RoutingError do get "/dashboard/active" @@ -226,7 +234,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in as active admin should be able to access dashboard/active route restricted to active admins (authenticated accepted)' do sign_in_as_admin(active: true) assert warden.authenticated?(:admin) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) get dashboard_active_path @@ -238,7 +246,7 @@ class AuthenticationRoutesRestrictions < Devise::IntegrationTest test 'signed in user should not see unauthenticated page (unauthenticated denied)' do sign_in_as_user assert warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) assert_raises ActionController::RoutingError do get join_path @@ -265,6 +273,15 @@ class AuthenticationRedirectTest < Devise::IntegrationTest assert_contain 'You need to sign in or sign up before continuing.' end + test 'redirect from warden respects i18n locale set at the controller' do + get admins_path(locale: "pt-BR") + + assert_redirected_to new_admin_session_path + follow_redirect! + + assert_contain 'Para continuar, faça login ou registre-se.' + end + test 'redirect to default url if no other was configured' do sign_in_as_user assert_template 'home/index' @@ -313,7 +330,15 @@ class AuthenticationRedirectTest < Devise::IntegrationTest test 'require_no_authentication should set the already_authenticated flash message' do sign_in_as_user visit new_user_session_path - assert_equal flash[:alert], I18n.t("devise.failure.already_authenticated") + assert_equal I18n.t("devise.failure.already_authenticated"), flash[:alert] + end + + test 'require_no_authentication should set the already_authenticated flash message as admin' do + store_translations :en, devise: { failure: { admin: { already_authenticated: 'You are already signed in as admin.' } } } do + sign_in_as_admin + visit new_admin_session_path + assert_equal "You are already signed in as admin.", flash[:alert] + end end end @@ -328,16 +353,20 @@ class AuthenticationSessionTest < Devise::IntegrationTest end test 'refreshes _csrf_token' do - ApplicationController.allow_forgery_protection = true - - begin + swap ApplicationController, allow_forgery_protection: true do get new_user_session_path - token = request.session[:_csrf_token] + token_from_session = request.session[:_csrf_token] + + if Devise::Test.rails71_and_up? + token_from_env = request.env["action_controller.csrf_token"] + end sign_in_as_user - assert_not_equal request.session[:_csrf_token], token - ensure - ApplicationController.allow_forgery_protection = false + assert_not_equal request.session[:_csrf_token], token_from_session + + if Devise::Test.rails71_and_up? + assert_not_equal request.env["action_controller.csrf_token"], token_from_env + end end end @@ -369,7 +398,7 @@ class AuthenticationWithScopedViewsTest < Devise::IntegrationTest end end - test 'renders the scoped view if turned on in an specific controller' do + test 'renders the scoped view if turned on in a specific controller' do begin Devise::SessionsController.scoped_views = true assert_raise Webrat::NotFoundError do @@ -377,7 +406,7 @@ class AuthenticationWithScopedViewsTest < Devise::IntegrationTest end assert_match %r{Special user view}, response.body - assert !Devise::PasswordsController.scoped_views? + assert_not Devise::PasswordsController.scoped_views? ensure Devise::SessionsController.send :remove_instance_variable, :@scoped_views end @@ -404,13 +433,13 @@ class AuthenticationOthersTest < Devise::IntegrationTest test 'handles unverified requests gets rid of caches' do swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) sign_in_as_user assert warden.authenticated?(:user) post exhibit_user_url(1) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert_equal "User is not authenticated", response.body end end @@ -446,14 +475,6 @@ class AuthenticationOthersTest < Devise::IntegrationTest end end - test 'sign in stub in xml format' do - get new_user_session_path(format: 'xml') - assert_match '', response.body - assert_match %r{.*}m, response.body - assert_match '', response.body - assert_match '\n) + assert_includes response.body, '{"user":{' end - test 'sign in with xml format is idempotent' do - get new_user_session_path(format: 'xml') + test 'sign in with json format is idempotent' do + get new_user_session_path(format: 'json') assert_response :success create_user - post user_session_path(format: 'xml'), params: { user: {email: "user@test.com", password: '12345678'} } + post user_session_path(format: 'json'), params: { user: {email: "user@test.com", password: '12345678'} } assert_response :success - get new_user_session_path(format: 'xml') + get new_user_session_path(format: 'json') assert_response :success - post user_session_path(format: 'xml'), params: { user: {email: "user@test.com", password: '12345678'} } + post user_session_path(format: 'json'), params: { user: {email: "user@test.com", password: '12345678'} } assert_response :success - assert response.body.include? %(\n) + assert_includes response.body, '{"user":{' end test 'sign out with html redirects' do @@ -511,18 +532,11 @@ class AuthenticationOthersTest < Devise::IntegrationTest assert_current_url '/' end - test 'sign out with xml format returns no content' do - sign_in_as_user - delete destroy_user_session_path(format: 'xml') - assert_response :no_content - refute warden.authenticated?(:user) - end - test 'sign out with json format returns no content' do sign_in_as_user delete destroy_user_session_path(format: 'json') assert_response :no_content - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'sign out with non-navigational format via XHR does not redirect' do @@ -530,7 +544,7 @@ class AuthenticationOthersTest < Devise::IntegrationTest sign_in_as_admin get destroy_sign_out_via_get_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "application/json,text/javascript,*/*" } # NOTE: Bug is triggered by combination of XHR and */*. assert_response :no_content - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end @@ -540,7 +554,7 @@ class AuthenticationOthersTest < Devise::IntegrationTest sign_in_as_user delete destroy_user_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "text/html,*/*" } assert_response :redirect - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end end @@ -549,8 +563,8 @@ class AuthenticationKeysTest < Devise::IntegrationTest test 'missing authentication keys cause authentication to abort' do swap Devise, authentication_keys: [:subdomain] do sign_in_as_user - assert_contain "Invalid Subdomain or password." - refute warden.authenticated?(:user) + assert_contain "Invalid subdomain or password." + assert_not warden.authenticated?(:user) end end @@ -567,7 +581,7 @@ class AuthenticationRequestKeysTest < Devise::IntegrationTest host! 'foo.bar.baz' swap Devise, request_keys: [:subdomain] do - User.expects(:find_for_authentication).with(subdomain: 'foo', email: 'user@test.com').returns(create_user) + User.expects(:find_for_authentication).with({ subdomain: 'foo', email: 'user@test.com' }).returns(create_user) sign_in_as_user assert warden.authenticated?(:user) end @@ -579,7 +593,7 @@ class AuthenticationRequestKeysTest < Devise::IntegrationTest sign_in_as_user end - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end @@ -588,8 +602,8 @@ class AuthenticationRequestKeysTest < Devise::IntegrationTest swap Devise, request_keys: [:subdomain] do sign_in_as_user - assert_contain "Invalid Email or password." - refute warden.authenticated?(:user) + assert_contain "Invalid email or password." + assert_not warden.authenticated?(:user) end end @@ -612,7 +626,7 @@ def sign_in!(scope) test 'allow sign out via delete when sign_out_via provides only delete' do sign_in!(:sign_out_via_delete) delete destroy_sign_out_via_delete_session_path - refute warden.authenticated?(:sign_out_via_delete) + assert_not warden.authenticated?(:sign_out_via_delete) end test 'do not allow sign out via get when sign_out_via provides only delete' do @@ -626,7 +640,7 @@ def sign_in!(scope) test 'allow sign out via post when sign_out_via provides only post' do sign_in!(:sign_out_via_post) post destroy_sign_out_via_post_session_path - refute warden.authenticated?(:sign_out_via_post) + assert_not warden.authenticated?(:sign_out_via_post) end test 'do not allow sign out via get when sign_out_via provides only post' do @@ -640,13 +654,13 @@ def sign_in!(scope) test 'allow sign out via delete when sign_out_via provides delete and post' do sign_in!(:sign_out_via_delete_or_post) delete destroy_sign_out_via_delete_or_post_session_path - refute warden.authenticated?(:sign_out_via_delete_or_post) + assert_not warden.authenticated?(:sign_out_via_delete_or_post) end test 'allow sign out via post when sign_out_via provides delete and post' do sign_in!(:sign_out_via_delete_or_post) post destroy_sign_out_via_delete_or_post_session_path - refute warden.authenticated?(:sign_out_via_delete_or_post) + assert_not warden.authenticated?(:sign_out_via_delete_or_post) end test 'do not allow sign out via get when sign_out_via provides delete and post' do diff --git a/test/integration/confirmable_test.rb b/test/integration/confirmable_test.rb index 02730d589..f9185e87f 100644 --- a/test/integration/confirmable_test.rb +++ b/test/integration/confirmable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class ConfirmationTest < Devise::IntegrationTest @@ -41,12 +43,12 @@ def resend_confirmation test 'user with valid confirmation token should not be able to confirm an account after the token has expired' do swap Devise, confirm_within: 3.days do user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) - refute user.confirmed? + assert_not user.confirmed? visit_user_confirmation_with_token(user.raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain %r{needs to be confirmed within 3 days} - refute user.reload.confirmed? + assert_not user.reload.confirmed? assert_current_url "/users/confirmation?confirmation_token=#{user.raw_confirmation_token}" end end @@ -84,7 +86,7 @@ def resend_confirmation test 'user with valid confirmation token should be able to confirm an account before the token has expired' do swap Devise, confirm_within: 3.days do user = create_user(confirm: false, confirmation_sent_at: 2.days.ago) - refute user.confirmed? + assert_not user.confirmed? visit_user_confirmation_with_token(user.raw_confirmation_token) assert_contain 'Your email address has been successfully confirmed.' @@ -130,7 +132,16 @@ def resend_confirmation sign_in_as_user(confirm: false) assert_contain 'You have to confirm your email address before continuing' - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) + end + end + + test 'not confirmed user redirect respects i18n locale set' do + swap Devise, allow_unconfirmed_access_for: 0.days do + sign_in_as_user(confirm: false, visit: new_user_session_path(locale: "pt-BR")) + + assert_contain 'Você precisa confirmar seu email para continuar' + assert_not warden.authenticated?(:user) end end @@ -140,8 +151,8 @@ def resend_confirmation fill_in 'password', with: 'invalid' end - assert_contain 'Invalid Email or password' - refute warden.authenticated?(:user) + assert_contain 'Invalid email or password' + assert_not warden.authenticated?(:user) end end @@ -173,6 +184,36 @@ def resend_confirmation assert_current_url '/users/sign_in' end + test "should not be able to confirm an email with a blank confirmation token" do + visit_user_confirmation_with_token("") + + assert_contain %r{Confirmation token can['’]t be blank} + end + + test "should not be able to confirm an email with a nil confirmation token" do + visit_user_confirmation_with_token(nil) + + assert_contain %r{Confirmation token can['’]t be blank} + end + + test "should not be able to confirm user with blank confirmation token" do + user = create_user(confirm: false) + user.update_attribute(:confirmation_token, "") + + visit_user_confirmation_with_token("") + + assert_contain %r{Confirmation token can['’]t be blank} + end + + test "should not be able to confirm user with nil confirmation token" do + user = create_user(confirm: false) + user.update_attribute(:confirmation_token, nil) + + visit_user_confirmation_with_token(nil) + + assert_contain %r{Confirmation token can['’]t be blank} + end + test 'error message is configurable by resource name' do store_translations :en, devise: { failure: { user: { unconfirmed: "Not confirmed user" } } @@ -182,40 +223,32 @@ def resend_confirmation end end - test 'resent confirmation token with valid E-Mail in XML format should return valid response' do + test 'resent confirmation token with valid e-mail in JSON format should return empty and valid response' do user = create_user(confirm: false) - post user_confirmation_path(format: 'xml'), params: { user: { email: user.email } } + post user_confirmation_path(format: 'json'), params: { user: { email: user.email } } assert_response :success - assert_equal response.body, {}.to_xml + assert_equal({}.to_json, response.body) end - test 'resent confirmation token with invalid E-Mail in XML format should return invalid response' do + test 'resent confirmation token with invalid e-mail in JSON format should return invalid response' do create_user(confirm: false) - post user_confirmation_path(format: 'xml'), params: { user: { email: 'invalid.test@test.com' } } + post user_confirmation_path(format: 'json'), params: { user: { email: 'invalid.test@test.com' } } assert_response :unprocessable_entity - assert response.body.include? %(\n) + assert_includes response.body, '{"errors":{' end - test 'confirm account with valid confirmation token in XML format should return valid response' do + test 'confirm account with valid confirmation token in JSON format should return valid response' do user = create_user(confirm: false) - get user_confirmation_path(confirmation_token: user.raw_confirmation_token, format: 'xml') + get user_confirmation_path(confirmation_token: user.raw_confirmation_token, format: 'json') assert_response :success - assert response.body.include? %(\n) + assert_includes response.body, '{"user":{' end - test 'confirm account with invalid confirmation token in XML format should return invalid response' do + test 'confirm account with invalid confirmation token in JSON format should return invalid response' do create_user(confirm: false) - get user_confirmation_path(confirmation_token: 'invalid_confirmation', format: 'xml') + get user_confirmation_path(confirmation_token: 'invalid_confirmation', format: 'json') assert_response :unprocessable_entity - assert response.body.include? %(\n) - end - - test 'request an account confirmation account with JSON, should return an empty JSON' do - user = create_user(confirm: false) - - post user_confirmation_path, params: { user: { email: user.email }, format: :json } - assert_response :success - assert_equal response.body, {}.to_json + assert_includes response.body, '{"confirmation_token":[' end test "when in paranoid mode and with a valid e-mail, should not say that the e-mail is valid" do @@ -250,7 +283,7 @@ def resend_confirmation end class ConfirmationOnChangeTest < Devise::IntegrationTest - def create_second_admin(options={}) + def create_second_admin(options = {}) @admin = nil create_admin(options) end @@ -261,7 +294,7 @@ def visit_admin_confirmation_with_token(confirmation_token) test 'admin should be able to request a new confirmation after email changed' do admin = create_admin - admin.update_attributes(email: 'new_test@example.com') + admin.update(email: 'new_test@example.com') visit new_admin_session_path click_link "Didn't receive confirmation instructions?" @@ -277,25 +310,25 @@ def visit_admin_confirmation_with_token(confirmation_token) test 'admin with valid confirmation token should be able to confirm email after email changed' do admin = create_admin - admin.update_attributes(email: 'new_test@example.com') + admin.update(email: 'new_test@example.com') assert_equal 'new_test@example.com', admin.unconfirmed_email visit_admin_confirmation_with_token(admin.raw_confirmation_token) assert_contain 'Your email address has been successfully confirmed.' assert_current_url '/admin_area/sign_in' assert admin.reload.confirmed? - refute admin.reload.pending_reconfirmation? + assert_not admin.reload.pending_reconfirmation? end test 'admin with previously valid confirmation token should not be able to confirm email after email changed again' do admin = create_admin - admin.update_attributes(email: 'first_test@example.com') + admin.update(email: 'first_test@example.com') assert_equal 'first_test@example.com', admin.unconfirmed_email raw_confirmation_token = admin.raw_confirmation_token admin = Admin.find(admin.id) - admin.update_attributes(email: 'second_test@example.com') + admin.update(email: 'second_test@example.com') assert_equal 'second_test@example.com', admin.unconfirmed_email visit_admin_confirmation_with_token(raw_confirmation_token) @@ -306,12 +339,12 @@ def visit_admin_confirmation_with_token(confirmation_token) assert_contain 'Your email address has been successfully confirmed.' assert_current_url '/admin_area/sign_in' assert admin.reload.confirmed? - refute admin.reload.pending_reconfirmation? + assert_not admin.reload.pending_reconfirmation? end test 'admin email should be unique also within unconfirmed_email' do admin = create_admin - admin.update_attributes(email: 'new_admin_test@example.com') + admin.update(email: 'new_admin_test@example.com') assert_equal 'new_admin_test@example.com', admin.unconfirmed_email create_second_admin(email: "new_admin_test@example.com") @@ -321,4 +354,32 @@ def visit_admin_confirmation_with_token(confirmation_token) assert_contain(/Email.*already.*taken/) assert admin.reload.pending_reconfirmation? end + + test 'concurrent "update email" requests should not allow confirming a victim email address' do + attacker_email = "attacker@example.com" + victim_email = "victim@example.com" + + attacker = create_admin + # update the email address of the attacker, but do not confirm it yet + attacker.update!(email: attacker_email) + + # A new request starts, to update the unconfirmed email again. + attacker = Admin.find_by(id: attacker.id) + + # A concurrent request also updates the email address to the victim, while the `attacker` request's model is in memory + Admin.where(id: attacker.id).update_all( + unconfirmed_email: victim_email, + confirmation_token: "different token" + ) + + # Now the attacker updates to the same prior unconfirmed email address, and confirm. + # This should update the `unconfirmed_email` in the database, even though it is unchanged from the models point of view. + attacker.update!(email: attacker_email) + attacker_token = attacker.raw_confirmation_token + visit_admin_confirmation_with_token(attacker_token) + + attacker.reload + assert attacker.confirmed? + assert_equal attacker_email, attacker.email + end end diff --git a/test/integration/database_authenticatable_test.rb b/test/integration/database_authenticatable_test.rb index 135f113b0..08011fe28 100644 --- a/test/integration/database_authenticatable_test.rb +++ b/test/integration/database_authenticatable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class DatabaseAuthenticationTest < Devise::IntegrationTest @@ -19,7 +21,7 @@ class DatabaseAuthenticationTest < Devise::IntegrationTest fill_in 'email', with: 'foo@bar.com' end - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end @@ -41,14 +43,14 @@ class DatabaseAuthenticationTest < Devise::IntegrationTest fill_in 'email', with: ' foo@bar.com ' end - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end test 'sign in should not authenticate if not using proper authentication keys' do swap Devise, authentication_keys: [:username] do sign_in_as_user - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end @@ -59,17 +61,30 @@ class DatabaseAuthenticationTest < Devise::IntegrationTest end assert_contain 'Invalid email address' - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) end end - test 'sign in with invalid pasword should return to sign in form with error message' do + test 'sign in with invalid password should return to sign in form with error message' do sign_in_as_admin do fill_in 'password', with: 'abcdef' end - assert_contain 'Invalid Email or password' - refute warden.authenticated?(:admin) + assert_contain 'Invalid email or password' + assert_not warden.authenticated?(:admin) + end + + test 'when in paranoid mode and without a valid e-mail' do + swap Devise, paranoid: true do + store_translations :en, devise: { failure: { not_found_in_database: 'Not found in database' } } do + sign_in_as_user do + fill_in 'email', with: 'wrongemail@test.com' + end + + assert_not_contain 'Not found in database' + assert_contain 'Invalid email or password.' + end + end end test 'error message is configurable by resource name' do diff --git a/test/integration/http_authenticatable_test.rb b/test/integration/http_authenticatable_test.rb index 56ea541c2..11e373320 100644 --- a/test/integration/http_authenticatable_test.rb +++ b/test/integration/http_authenticatable_test.rb @@ -1,6 +1,14 @@ +# frozen_string_literal: true + require 'test_helper' class HttpAuthenticationTest < Devise::IntegrationTest + test 'sign in with HTTP should not run model validations' do + sign_in_as_new_user_with_http + + assert_not User.validations_performed + end + test 'handles unverified requests gets rid of caches but continues signed in' do swap ApplicationController, allow_forgery_protection: true do create_user @@ -14,10 +22,10 @@ class HttpAuthenticationTest < Devise::IntegrationTest swap Devise, skip_session_storage: [] do sign_in_as_new_user_with_http assert_response 200 - assert_match 'user@test.com', response.body + assert_match '"email":"user@test.com"', response.body assert warden.authenticated?(:user) - get users_path(format: :xml) + get users_path(format: :json) assert_response 200 end end @@ -26,10 +34,10 @@ class HttpAuthenticationTest < Devise::IntegrationTest swap Devise, skip_session_storage: [:http_auth] do sign_in_as_new_user_with_http assert_response 200 - assert_match 'user@test.com', response.body + assert_match '"email":"user@test.com"', response.body assert warden.authenticated?(:user) - get users_path(format: :xml) + get users_path(format: :json) assert_response 401 end end @@ -43,8 +51,8 @@ class HttpAuthenticationTest < Devise::IntegrationTest test 'uses the request format as response content type' do sign_in_as_new_user_with_http("unknown") assert_equal 401, status - assert_equal "application/xml; charset=utf-8", headers["Content-Type"] - assert_match "Invalid Email or password.", response.body + assert_equal "application/json; charset=utf-8", headers["Content-Type"] + assert_match '"error":"Invalid email or password."', response.body end test 'returns a custom response with www-authenticate and chosen realm' do @@ -59,7 +67,7 @@ class HttpAuthenticationTest < Devise::IntegrationTest swap Devise, authentication_keys: [:username] do sign_in_as_new_user_with_http("usertest") assert_response :success - assert_match 'user@test.com', response.body + assert_match '"email":"user@test.com"', response.body assert warden.authenticated?(:user) end end @@ -68,7 +76,7 @@ class HttpAuthenticationTest < Devise::IntegrationTest swap Devise, authentication_keys: { username: false, email: false } do sign_in_as_new_user_with_http("usertest") assert_response :success - assert_match 'user@test.com', response.body + assert_match '"email":"user@test.com"', response.body assert warden.authenticated?(:user) end end @@ -77,7 +85,7 @@ class HttpAuthenticationTest < Devise::IntegrationTest swap Devise, authentication_keys: { email: false, username: false }, http_authentication_key: :username do sign_in_as_new_user_with_http("usertest") assert_response :success - assert_match 'user@test.com', response.body + assert_match '"email":"user@test.com"', response.body assert warden.authenticated?(:user) end end @@ -91,16 +99,15 @@ class HttpAuthenticationTest < Devise::IntegrationTest end private - def sign_in_as_new_user_with_http(username="user@test.com", password="12345678") + def sign_in_as_new_user_with_http(username = "user@test.com", password = "12345678") user = create_user - get users_path(format: :xml), headers: { "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("#{username}:#{password}")}" } + get users_path(format: :json), headers: { "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("#{username}:#{password}")}" } user end # Sign in with oauth2 token. This is just to test that it isn't misinterpreted as basic authentication def add_oauth2_header user = create_user - get users_path(format: :xml), headers: { "HTTP_AUTHORIZATION" => "OAuth #{Base64.encode64("#{user.email}:12345678")}" } + get users_path(format: :json), headers: { "HTTP_AUTHORIZATION" => "OAuth #{Base64.encode64("#{user.email}:12345678")}" } end - end diff --git a/test/integration/lockable_test.rb b/test/integration/lockable_test.rb index 5602bb9fd..e5dd5ee08 100644 --- a/test/integration/lockable_test.rb +++ b/test/integration/lockable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class LockTest < Devise::IntegrationTest @@ -85,7 +87,7 @@ def send_unlock_request assert_current_url "/users/sign_in" assert_contain 'Your account has been unlocked successfully. Please sign in to continue.' - refute user.reload.access_locked? + assert_not user.reload.access_locked? end test "user should not send a new e-mail if already locked" do @@ -97,7 +99,7 @@ def send_unlock_request sign_in_as_user(password: "invalid") assert_contain 'Your account is locked.' - assert ActionMailer::Base.deliveries.empty? + assert_empty ActionMailer::Base.deliveries end test 'error message is configurable by resource name' do @@ -128,51 +130,42 @@ def send_unlock_request end end - test 'user should be able to request a new unlock token via XML request' do + test 'user should be able to request a new unlock token via JSON request and should return empty and valid response' do user = create_user(locked: true) ActionMailer::Base.deliveries.clear - post user_unlock_path(format: 'xml'), params: { user: {email: user.email} } + post user_unlock_path(format: 'json'), params: { user: {email: user.email} } assert_response :success - assert_equal response.body, {}.to_xml - + assert_equal({}.to_json, response.body) assert_equal 1, ActionMailer::Base.deliveries.size end - test 'unlocked user should not be able to request a unlock token via XML request' do + test 'unlocked user should not be able to request a unlock token via JSON request' do user = create_user(locked: false) ActionMailer::Base.deliveries.clear - post user_unlock_path(format: 'xml'), params: { user: {email: user.email} } + post user_unlock_path(format: 'json'), params: { user: {email: user.email} } assert_response :unprocessable_entity - assert response.body.include? %(\n) + assert_includes response.body, '{"errors":{' assert_equal 0, ActionMailer::Base.deliveries.size end - test 'user with valid unlock token should be able to unlock account via XML request' do + test 'user with valid unlock token should be able to unlock account via JSON request' do user = create_user() raw = user.lock_access! assert user.access_locked? - get user_unlock_path(format: 'xml', unlock_token: raw) + get user_unlock_path(format: 'json', unlock_token: raw) assert_response :success - assert response.body.include? %(\n) + assert_includes response.body, '{"user":{' end - - test 'user with invalid unlock token should not be able to unlock the account via XML request' do - get user_unlock_path(format: 'xml', unlock_token: 'invalid_token') + test 'user with invalid unlock token should not be able to unlock the account via JSON request' do + get user_unlock_path(format: 'json', unlock_token: 'invalid_token') assert_response :unprocessable_entity - assert response.body.include? %(\n) - end - - test "when using json to ask a unlock request, should not return the user" do - user = create_user(locked: true) - post user_unlock_path(format: "json", user: {email: user.email}) - assert_response :success - assert_equal response.body, {}.to_json + assert_includes response.body, '{"unlock_token":[' end - test "in paranoid mode, when trying to unlock an user that exists it should not say that it exists if it is locked" do + test "in paranoid mode, when trying to unlock a user that exists it should not say that it exists if it is locked" do swap Devise, paranoid: true do user = create_user(locked: true) @@ -187,7 +180,7 @@ def send_unlock_request end end - test "in paranoid mode, when trying to unlock an user that exists it should not say that it exists if it is not locked" do + test "in paranoid mode, when trying to unlock a user that exists it should not say that it exists if it is not locked" do swap Devise, paranoid: true do user = create_user(locked: false) @@ -202,7 +195,7 @@ def send_unlock_request end end - test "in paranoid mode, when trying to unlock an user that does not exists it should not say that it does not exists" do + test "in paranoid mode, when trying to unlock a user that does not exists it should not say that it does not exists" do swap Devise, paranoid: true do visit new_user_session_path click_link "Didn't receive unlock instructions?" diff --git a/test/integration/mounted_engine_test.rb b/test/integration/mounted_engine_test.rb index 98dcf4759..0ac47e335 100644 --- a/test/integration/mounted_engine_test.rb +++ b/test/integration/mounted_engine_test.rb @@ -1,11 +1,26 @@ +# frozen_string_literal: true + require 'test_helper' -class MyMountableEngine - def self.call(env) - ['200', { 'Content-Type' => 'text/html' }, ['Rendered content of MyMountableEngine']] +module MyMountableEngine + class Engine < ::Rails::Engine + isolate_namespace MyMountableEngine + end + class TestsController < ActionController::Base + def index + render plain: 'Root test successful' + end + def inner_route + render plain: 'Inner route test successful' + end end end +MyMountableEngine::Engine.routes.draw do + get 'test', to: 'tests#inner_route' + root to: 'tests#index' +end + # If disable_clear_and_finalize is set to true, Rails will not clear other routes when calling # again the draw method. Look at the source code at: # http://www.rubydoc.info/docs/rails/ActionDispatch/Routing/RouteSet:draw @@ -13,7 +28,7 @@ def self.call(env) Rails.application.routes.draw do authenticate(:user) do - mount MyMountableEngine, at: '/mountable_engine' + mount MyMountableEngine::Engine, at: '/mountable_engine' end end @@ -31,6 +46,23 @@ class AuthenticatedMountedEngineTest < Devise::IntegrationTest get '/mountable_engine' assert_response :success - assert_contain 'Rendered content of MyMountableEngine' + assert_contain 'Root test successful' + end + + + test 'renders a inner route of the mounted engine when authenticated' do + sign_in_as_user + get '/mountable_engine/test' + + assert_response :success + assert_contain 'Inner route test successful' + end + + test 'respond properly to a non existing route of the mounted engine' do + sign_in_as_user + + assert_raise ActionController::RoutingError do + get '/mountable_engine/non-existing-route' + end end end diff --git a/test/integration/omniauthable_test.rb b/test/integration/omniauthable_test.rb index 6af884200..72a59dbfb 100644 --- a/test/integration/omniauthable_test.rb +++ b/test/integration/omniauthable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' @@ -21,6 +23,9 @@ class OmniauthableIntegrationTest < Devise::IntegrationTest "extra" => {"user_hash" => FACEBOOK_INFO} } OmniAuth.config.add_camelization 'facebook', 'FaceBook' + if OmniAuth.config.respond_to?(:request_validation_phase) + OmniAuth.config.request_validation_phase = ->(env) {} + end end teardown do @@ -40,9 +45,20 @@ def stub_action!(name) end end + test "omniauth sign in should not run model validations" do + stub_action!(:sign_in_facebook) do + create_user + post "/users/auth/facebook" + follow_redirect! + assert warden.authenticated?(:user) + + assert_not User.validations_performed + end + end + test "can access omniauth.auth in the env hash" do - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! json = ActiveSupport::JSON.decode(response.body) @@ -55,8 +71,8 @@ def stub_action!(name) test "cleans up session on sign up" do assert_no_difference "User.count" do - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! end assert session["devise.facebook_data"] @@ -71,49 +87,80 @@ def stub_action!(name) assert_current_url "/" assert_contain "You have signed up successfully." assert_contain "Hello User user@example.com" - refute session["devise.facebook_data"] + assert_not session["devise.facebook_data"] end test "cleans up session on cancel" do assert_no_difference "User.count" do - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! end assert session["devise.facebook_data"] visit "/users/cancel" - assert !session["devise.facebook_data"] + assert_not session["devise.facebook_data"] end test "cleans up session on sign in" do assert_no_difference "User.count" do - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! end assert session["devise.facebook_data"] sign_in_as_user - assert !session["devise.facebook_data"] + assert_not session["devise.facebook_data"] end test "sign in and send remember token if configured" do - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! assert_nil warden.cookies["remember_user_token"] stub_action!(:sign_in_facebook) do create_user - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! assert warden.authenticated?(:user) assert warden.cookies["remember_user_token"] end end + test "authorization path via GET when Omniauth allowed_request_methods includes GET" do + original_allowed = OmniAuth.config.allowed_request_methods + OmniAuth.config.allowed_request_methods = [:get, :post] + + get "/users/auth/facebook" + + assert_response(:redirect) + ensure + OmniAuth.config.allowed_request_methods = original_allowed + end + + test "authorization path via GET when Omniauth allowed_request_methods doesn't include GET" do + original_allowed = OmniAuth.config.allowed_request_methods + OmniAuth.config.allowed_request_methods = [:post] + + assert_raises(ActionController::RoutingError) do + get "/users/auth/facebook" + end + ensure + OmniAuth.config.allowed_request_methods = original_allowed + end + + test "generates a link to authenticate with provider" do + visit "/users/sign_in" + assert_select "form[action=?][method=post]", "/users/auth/facebook" do + assert_select "input[type=submit][value=?]", "Sign in with FaceBook" + end + end + test "generates a proper link when SCRIPT_NAME is set" do header 'SCRIPT_NAME', '/q' visit "/users/sign_in" - assert_select "a", href: "/q/users/auth/facebook" + assert_select "form[action=?][method=post]", "/q/users/auth/facebook" do + assert_select "input[type=submit][value=?]", "Sign in with FaceBook" + end end test "handles callback error parameter according to the specification" do @@ -126,10 +173,10 @@ def stub_action!(name) test "handles other exceptions from OmniAuth" do OmniAuth.config.mock_auth[:facebook] = :invalid_credentials - visit "/users/sign_in" - click_link "Sign in with FaceBook" + post "/users/auth/facebook" + follow_redirect! + follow_redirect! - assert_current_url "/users/sign_in" assert_contain 'Could not authenticate you from FaceBook because "Invalid credentials".' end end diff --git a/test/integration/recoverable_test.rb b/test/integration/recoverable_test.rb index f35a46b7b..c391b0b2e 100644 --- a/test/integration/recoverable_test.rb +++ b/test/integration/recoverable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class PasswordTest < Devise::IntegrationTest @@ -10,16 +12,16 @@ def visit_new_password_path def request_forgot_password(&block) visit_new_password_path assert_response :success - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) fill_in 'email', with: 'user@test.com' yield if block_given? Devise.stubs(:friendly_token).returns("abcdef") - click_button 'Send me reset password instructions' + click_button 'Send me password reset instructions' end - def reset_password(options={}, &block) + def reset_password(options = {}, &block) unless options[:visit] == false visit edit_user_password_path(reset_password_token: options[:reset_password_token] || "abcdef") assert_response :success @@ -31,6 +33,17 @@ def reset_password(options={}, &block) click_button 'Change my password' end + test 'reset password should send to user record email and avoid case mapping collisions' do + create_user(email: 'user@github.com') + + request_forgot_password do + fill_in 'email', with: 'user@gıthub.com' + end + + mail = ActionMailer::Base.deliveries.last + assert_equal ['user@github.com'], mail.to + end + test 'reset password with email of different case should succeed when email is in the list of case insensitive keys' do create_user(email: 'Foo@Bar.com') @@ -147,7 +160,7 @@ def reset_password(options={}, &block) assert_current_url '/users/password' assert_have_selector '#error_explanation' assert_contain %r{Reset password token(.*)invalid} - refute user.reload.valid_password?('987654321') + assert_not user.reload.valid_password?('987654321') end test 'not authenticated user with valid reset password token but invalid password should not be able to change their password' do @@ -160,8 +173,8 @@ def reset_password(options={}, &block) assert_response :success assert_current_url '/users/password' assert_have_selector '#error_explanation' - assert_contain "Password confirmation doesn't match Password" - refute user.reload.valid_password?('987654321') + assert_contain %r{Password confirmation doesn['’]t match Password} + assert_not user.reload.valid_password?('987654321') end test 'not authenticated user with valid data should be able to change their password' do @@ -181,7 +194,7 @@ def reset_password(options={}, &block) reset_password { fill_in 'Confirm new password', with: 'other_password' } assert_response :success assert_have_selector '#error_explanation' - refute user.reload.valid_password?('987654321') + assert_not user.reload.valid_password?('987654321') reset_password visit: false assert_contain 'Your password has been changed successfully.' @@ -205,7 +218,32 @@ def reset_password(options={}, &block) assert_contain 'Your password has been changed successfully.' assert_not_contain 'You are now signed in.' assert_equal new_user_session_path, @request.path - assert !warden.authenticated?(:user) + assert_not warden.authenticated?(:user) + end + end + + test 'does not sign in user automatically after changing its password if resource_class.sign_in_after_reset_password is false' do + swap_model_config User, sign_in_after_reset_password: false do + create_user + request_forgot_password + reset_password + + assert_contain 'Your password has been changed successfully' + assert_not_contain 'You are now signed in.' + assert_equal new_user_session_path, @request.path + assert_not warden.authenticated?(:user) + end + end + + test 'sign in user automatically after changing its password if resource_class.sign_in_after_reset_password is true' do + swap Devise, sign_in_after_reset_password: false do + swap_model_config User, sign_in_after_reset_password: true do + create_user + request_forgot_password + reset_password + + assert warden.authenticated?(:user) + end end end @@ -219,7 +257,7 @@ def reset_password(options={}, &block) assert_contain 'Your password has been changed successfully.' assert_not_contain 'You are now signed in.' assert_equal new_user_session_path, @request.path - assert !warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end end @@ -231,7 +269,7 @@ def reset_password(options={}, &block) reset_password assert_contain 'Your password has been changed successfully.' - assert !user.reload.access_locked? + assert_not user.reload.access_locked? assert warden.authenticated?(:user) end end @@ -243,75 +281,65 @@ def reset_password(options={}, &block) reset_password assert_contain 'Your password has been changed successfully.' - assert !user.reload.access_locked? + assert_not user.reload.access_locked? assert warden.authenticated?(:user) end end - test 'reset password request with valid E-Mail in XML format should return valid response' do + test 'reset password request with valid e-mail in JSON format should return empty and valid response' do create_user - post user_password_path(format: 'xml'), params: { user: {email: "user@test.com"} } + post user_password_path(format: 'json'), params: { user: {email: "user@test.com"} } assert_response :success - assert_equal response.body, { }.to_xml + assert_equal({}.to_json, response.body) end - test 'reset password request with invalid E-Mail in XML format should return valid response' do + test 'reset password request with invalid e-mail in JSON format should return valid response' do create_user - post user_password_path(format: 'xml'), params: { user: {email: "invalid.test@test.com"} } + post user_password_path(format: 'json'), params: { user: {email: "invalid.test@test.com"} } assert_response :unprocessable_entity - assert response.body.include? %(\n) + assert_includes response.body, '{"errors":{' end - test 'reset password request with invalid E-Mail in XML format should return empty and valid response' do + test 'reset password request with invalid e-mail in JSON format should return empty and valid response in paranoid mode' do swap Devise, paranoid: true do create_user - post user_password_path(format: 'xml'), params: { user: {email: "invalid@test.com"} } + post user_password_path(format: 'json'), params: { user: {email: "invalid@test.com"} } assert_response :success - assert_equal response.body, { }.to_xml + assert_equal({}.to_json, response.body) end end - test 'change password with valid parameters in XML format should return valid response' do + test 'change password with valid parameters in JSON format should return valid response' do create_user request_forgot_password - put user_password_path(format: 'xml'), params: { user: { + put user_password_path(format: 'json'), params: { user: { reset_password_token: 'abcdef', password: '987654321', password_confirmation: '987654321' - } - } + } } assert_response :success assert warden.authenticated?(:user) end - test 'change password with invalid token in XML format should return invalid response' do + test 'change password with invalid token in JSON format should return invalid response' do create_user request_forgot_password - put user_password_path(format: 'xml'), params: { user: {reset_password_token: 'invalid.token', password: '987654321', password_confirmation: '987654321'} } + put user_password_path(format: 'json'), params: { user: {reset_password_token: 'invalid.token', password: '987654321', password_confirmation: '987654321'} } assert_response :unprocessable_entity - assert response.body.include? %(\n) + assert_includes response.body, '{"errors":{' end - test 'change password with invalid new password in XML format should return invalid response' do + test 'change password with invalid new password in JSON format should return invalid response' do user = create_user request_forgot_password - put user_password_path(format: 'xml'), params: { user: {reset_password_token: user.reload.reset_password_token, password: '', password_confirmation: '987654321'} } + put user_password_path(format: 'json'), params: { user: {reset_password_token: user.reload.reset_password_token, password: '', password_confirmation: '987654321'} } assert_response :unprocessable_entity - assert response.body.include? %(\n) - end - - test "when using json requests to ask a confirmable request, should not return the object" do - user = create_user(confirm: false) - - post user_password_path(format: :json), params: { user: { email: user.email } } - - assert_response :success - assert_equal response.body, "{}" + assert_includes response.body, '{"errors":{' end test "when in paranoid mode and with an invalid e-mail, asking to reset a password should display a message that does not indicates that the e-mail does not exists in the database" do swap Devise, paranoid: true do visit_new_password_path fill_in "email", with: "arandomemail@test.com" - click_button 'Send me reset password instructions' + click_button 'Send me password reset instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" @@ -325,7 +353,7 @@ def reset_password(options={}, &block) user = create_user visit_new_password_path fill_in 'email', with: user.email - click_button 'Send me reset password instructions' + click_button 'Send me password reset instructions' assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." assert_current_url "/users/sign_in" diff --git a/test/integration/registerable_test.rb b/test/integration/registerable_test.rb index 4fa361b7c..9289ac6af 100644 --- a/test/integration/registerable_test.rb +++ b/test/integration/registerable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class RegistrationTest < Devise::IntegrationTest @@ -18,7 +20,7 @@ class RegistrationTest < Devise::IntegrationTest assert_current_url "/admin_area/home" admin = Admin.to_adapter.find_first(order: [:id, :desc]) - assert_equal admin.email, 'new_user@test.com' + assert_equal 'new_user@test.com', admin.email end test 'a guest admin should be able to sign in and be redirected to a custom location' do @@ -64,11 +66,11 @@ def user_sign_up assert_not_contain 'You have to confirm your account before continuing' assert_current_url "/" - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) user = User.to_adapter.find_first(order: [:id, :desc]) - assert_equal user.email, 'new_user@test.com' - refute user.confirmed? + assert_equal 'new_user@test.com', user.email + assert_not user.confirmed? end test 'a guest user should receive the confirmation instructions from the default mailer' do @@ -92,14 +94,10 @@ def user_sign_up click_button 'Sign up' assert_current_url "/?custom=1" - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'a guest user cannot sign up with invalid information' do - # Dirty tracking behavior prevents email validations from being applied: - # https://github.com/mongoid/mongoid/issues/756 - (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1 - get new_user_registration_path fill_in 'email', with: 'invalid_email' @@ -110,18 +108,14 @@ def user_sign_up assert_template 'registrations/new' assert_have_selector '#error_explanation' assert_contain "Email is invalid" - assert_contain "Password confirmation doesn't match Password" + assert_contain %r{Password confirmation doesn['’]t match Password} assert_contain "2 errors prohibited" assert_nil User.to_adapter.find_first - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'a guest should not sign up with email/password that already exists' do - # Dirty tracking behavior prevents email validations from being applied: - # https://github.com/mongoid/mongoid/issues/756 - (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1 - create_user get new_user_registration_path @@ -133,7 +127,7 @@ def user_sign_up assert_current_url '/users' assert_contain(/Email.*already.*taken/) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'a guest should not be able to change account' do @@ -177,6 +171,55 @@ def user_sign_up assert warden.authenticated?(:user) end + test 'a signed in user should not be able to use the website after changing their password if config.sign_in_after_change_password is false' do + swap Devise, sign_in_after_change_password: false do + sign_in_as_user + get edit_user_registration_path + + fill_in 'password', with: '1234567890' + fill_in 'password confirmation', with: '1234567890' + fill_in 'current password', with: '12345678' + click_button 'Update' + + assert_contain 'Your account has been updated successfully, but since your password was changed, you need to sign in again.' + assert_equal new_user_session_path, @request.path + assert_not warden.authenticated?(:user) + end + end + + test 'a signed in user should not be able to use the website after changing their password if resource_class.sign_in_after_change_password is false' do + swap_model_config User, sign_in_after_change_password: false do + sign_in_as_user + get edit_user_registration_path + + fill_in 'password', with: '1234567890' + fill_in 'password confirmation', with: '1234567890' + fill_in 'current password', with: '12345678' + click_button 'Update' + + assert_contain 'Your account has been updated successfully, but since your password was changed, you need to sign in again.' + assert_equal new_user_session_path, @request.path + assert_not warden.authenticated?(:user) + end + end + + test 'a signed in user should be able to use the website after changing its email with config.sign_in_after_change_password is false' do + swap Devise, sign_in_after_change_password: false do + sign_in_as_user + get edit_user_registration_path + + fill_in 'email', with: 'user.new@example.com' + fill_in 'current password', with: '12345678' + click_button 'Update' + + assert_current_url '/' + assert_contain 'Your account has been updated successfully.' + + assert warden.authenticated?(:user) + assert_equal "user.new@example.com", User.to_adapter.find_first.email + end + end + test 'a signed in user should not change their current user with invalid password' do sign_in_as_user get edit_user_registration_path @@ -216,10 +259,10 @@ def user_sign_up fill_in 'current password', with: '12345678' click_button 'Update' - assert_contain "Password confirmation doesn't match Password" - refute User.to_adapter.find_first.valid_password?('pas123') + assert_contain %r{Password confirmation doesn['’]t match Password} + assert_not User.to_adapter.find_first.valid_password?('pas123') end - + test 'a signed in user should see a warning about minimum password length' do sign_in_as_user get edit_user_registration_path @@ -233,7 +276,7 @@ def user_sign_up click_button "Cancel my account" assert_contain "Bye! Your account has been successfully cancelled. We hope to see you again soon." - assert User.to_adapter.find_all.empty? + assert_empty User.to_adapter.find_all end test 'a user should be able to cancel sign up by deleting data in the session' do @@ -248,13 +291,6 @@ def user_sign_up assert_redirected_to new_user_registration_path end - test 'a user with XML sign up stub' do - get new_user_registration_path(format: 'xml') - assert_response :success - assert_match %(\n), response.body - assert_no_match(/\n) + assert_includes response.body, '{"admin":{' admin = Admin.to_adapter.find_first(order: [:id, :desc]) - assert_equal admin.email, 'new_user@test.com' + assert_equal 'new_user@test.com', admin.email end - test 'a user sign up with valid information in XML format should return valid response' do - post user_registration_path(format: 'xml'), params: { user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'new_user123' } } + test 'a user sign up with valid information in JSON format should return valid response' do + post user_registration_path(format: 'json'), params: { user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'new_user123' } } assert_response :success - assert response.body.include? %(\n) + assert_includes response.body, '{"user":{' user = User.to_adapter.find_first(order: [:id, :desc]) - assert_equal user.email, 'new_user@test.com' + assert_equal 'new_user@test.com', user.email end - test 'a user sign up with invalid information in XML format should return invalid response' do - post user_registration_path(format: 'xml'), params: { user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'invalid' } } + test 'a user sign up with invalid information in JSON format should return invalid response' do + post user_registration_path(format: 'json'), params: { user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'invalid' } } assert_response :unprocessable_entity - assert response.body.include? %(\n) + assert_includes response.body, '{"errors":{' end - test 'a user update information with valid data in XML format should return valid response' do + test 'a user update information with valid data in JSON format should return valid response' do user = sign_in_as_user - put user_registration_path(format: 'xml'), params: { user: { current_password: '12345678', email: 'user.new@test.com' } } + put user_registration_path(format: 'json'), params: { user: { current_password: '12345678', email: 'user.new@test.com' } } assert_response :success - assert_equal user.reload.email, 'user.new@test.com' + assert_equal 'user.new@test.com', user.reload.email end - test 'a user update information with invalid data in XML format should return invalid response' do + test 'a user update information with invalid data in JSON format should return invalid response' do user = sign_in_as_user - put user_registration_path(format: 'xml'), params: { user: { current_password: 'invalid', email: 'user.new@test.com' } } + put user_registration_path(format: 'json'), params: { user: { current_password: 'invalid', email: 'user.new@test.com' } } assert_response :unprocessable_entity - assert_equal user.reload.email, 'user@test.com' + assert_equal 'user@test.com', user.reload.email end - test 'a user cancel their account in XML format should return valid response' do + test 'a user cancel their account in JSON format should return valid response' do sign_in_as_user - delete user_registration_path(format: 'xml') + delete user_registration_path(format: 'json') assert_response :success - assert_equal User.to_adapter.find_all.size, 0 + assert_equal 0, User.to_adapter.find_all.size end end diff --git a/test/integration/rememberable_test.rb b/test/integration/rememberable_test.rb index 1dfd07d6e..1fc4e4d58 100644 --- a/test/integration/rememberable_test.rb +++ b/test/integration/rememberable_test.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'test_helper' class RememberMeTest < Devise::IntegrationTest - def create_user_and_remember(add_to_token='') + def create_user_and_remember(add_to_token = '') user = create_user user.remember_me! raw_cookie = User.serialize_into_cookie(user).tap { |a| a[1] << add_to_token } @@ -10,13 +12,7 @@ def create_user_and_remember(add_to_token='') end def generate_signed_cookie(raw_cookie) - request = if Devise::Test.rails51? - ActionController::TestRequest.create(Class.new) # needs a "controller class" - elsif Devise::Test.rails5? - ActionController::TestRequest.create - else - ActionController::TestRequest.new - end + request = ActionController::TestRequest.create(Class.new) # needs a "controller class" request.cookie_jar.signed['raw_cookie'] = raw_cookie request.cookie_jar['raw_cookie'] end @@ -39,12 +35,12 @@ def cookie_expires(key) test 'handle unverified requests gets rid of caches' do swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) create_user_and_remember post exhibit_user_url(1) assert_equal "User is not authenticated", response.body - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end @@ -57,8 +53,8 @@ def cookie_expires(key) authenticity_token: "oops", user: { email: "jose.valim@gmail.com", password: "123456", remember_me: "1" } } - refute warden.authenticated?(:user) - refute request.cookies['remember_user_token'] + assert_not warden.authenticated?(:user) + assert_not request.cookies['remember_user_token'] end end @@ -138,7 +134,7 @@ def cookie_expires(key) get root_path current_remember_token = request.cookies['remember_user_token'] - refute_equal old_remember_token, current_remember_token + assert_not_equal old_remember_token, current_remember_token end end @@ -164,13 +160,13 @@ def cookie_expires(key) get root_path assert_response :success assert warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:admin) end test 'do not remember with invalid token' do create_user_and_remember('add') get users_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert_redirected_to new_user_session_path end @@ -178,7 +174,7 @@ def cookie_expires(key) create_user_and_remember swap Devise, remember_for: 0.days do get users_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert_redirected_to new_user_session_path end end @@ -189,11 +185,11 @@ def cookie_expires(key) assert warden.authenticated?(:user) delete destroy_user_session_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert_nil warden.cookies['remember_user_token'] get users_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'changing user password expires remember me token' do @@ -203,7 +199,7 @@ def cookie_expires(key) user.save! get users_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test 'valid sign in calls after_remembered callback' do diff --git a/test/integration/timeoutable_test.rb b/test/integration/timeoutable_test.rb index d831a96c6..670ddbbe8 100644 --- a/test/integration/timeoutable_test.rb +++ b/test/integration/timeoutable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class SessionTimeoutTest < Devise::IntegrationTest @@ -56,7 +58,7 @@ def last_request_at get users_path assert_redirected_to users_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert warden.authenticated?(:admin) end end @@ -70,12 +72,12 @@ def last_request_at assert_not_nil last_request_at get root_path - refute warden.authenticated?(:user) - refute warden.authenticated?(:admin) + assert_not warden.authenticated?(:user) + assert_not warden.authenticated?(:admin) end end - test 'time out user session after deault limit time and redirect to latest get request' do + test 'time out user session after default limit time and redirect to latest get request' do user = sign_in_as_user visit edit_form_user_path(user) @@ -85,6 +87,26 @@ def last_request_at assert_equal edit_form_user_url(user), current_url end + test 'time out on non-GET request does not redirect to an external host supplied via the referer' do + user = sign_in_as_user + get expire_user_path(user) + + put update_form_user_path(user), headers: { 'HTTP_REFERER' => 'http://evil.example/phishing' } + + assert_response :redirect + assert_redirected_to '/phishing' + end + + test 'time out on non-GET request with an opaque referer falls back to the sign in page' do + user = sign_in_as_user + get expire_user_path(user) + + put update_form_user_path(user), headers: { 'HTTP_REFERER' => 'javascript:alert(1)' } + + assert_response :redirect + assert_redirected_to new_user_session_path + end + test 'time out is not triggered on sign out' do user = sign_in_as_user get expire_user_path(user) @@ -107,8 +129,8 @@ def last_request_at follow_redirect! assert_response :success - assert_contain 'Sign in' - refute warden.authenticated?(:user) + assert_contain 'Log in' + assert_not warden.authenticated?(:user) end test 'time out is not triggered on sign in' do @@ -134,7 +156,7 @@ def last_request_at get expire_user_path(user) get users_path assert_redirected_to users_path - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end end @@ -165,6 +187,17 @@ def last_request_at end end + test 'error message redirect respects i18n locale set' do + user = sign_in_as_user + + get expire_user_path(user) + get root_path(locale: "pt-BR") + follow_redirect! + + assert_contain 'Sua sessão expirou. Por favor faça o login novamente para continuar.' + assert_not warden.authenticated?(:user) + end + test 'time out not triggered if remembered' do user = sign_in_as_user remember_me: true get expire_user_path(user) @@ -178,7 +211,9 @@ def last_request_at test 'does not crash when the last_request_at is a String' do user = sign_in_as_user - get edit_form_user_path(user, last_request_at: Time.now.utc.to_s) - get users_path + assert_nothing_raised do + get edit_form_user_path(user, last_request_at: Time.now.utc.to_s) + get users_path + end end end diff --git a/test/integration/trackable_test.rb b/test/integration/trackable_test.rb index 4337f1535..f5b6fcda8 100644 --- a/test/integration/trackable_test.rb +++ b/test/integration/trackable_test.rb @@ -1,6 +1,13 @@ +# frozen_string_literal: true + require 'test_helper' class TrackableHooksTest < Devise::IntegrationTest + test "trackable should not run model validations" do + sign_in_as_user + + assert_not User.validations_performed + end test "current and last sign in timestamps are updated on each sign in" do user = create_user @@ -37,7 +44,7 @@ class TrackableHooksTest < Devise::IntegrationTest assert_equal "127.0.0.1", user.last_sign_in_ip end - test "current remote ip returns original ip behind a non transparent proxy" do + test "current and last sign in remote ip returns original ip behind a non transparent proxy" do user = create_user arbitrary_ip = '200.121.1.69' @@ -46,6 +53,7 @@ class TrackableHooksTest < Devise::IntegrationTest end user.reload assert_equal arbitrary_ip, user.current_sign_in_ip + assert_equal arbitrary_ip, user.last_sign_in_ip end test "increase sign in count" do diff --git a/test/mailers/confirmation_instructions_test.rb b/test/mailers/confirmation_instructions_test.rb index f929ba43f..5b4633121 100644 --- a/test/mailers/confirmation_instructions_test.rb +++ b/test/mailers/confirmation_instructions_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class ConfirmationInstructionsTest < ActionMailer::TestCase @@ -29,7 +31,7 @@ def mail end test 'content type should be set to html' do - assert mail.content_type.include?('text/html') + assert_includes mail.content_type, 'text/html' end test 'send confirmation instructions to the user email' do @@ -86,7 +88,7 @@ def mail host, port = ActionMailer::Base.default_url_options.values_at :host, :port if mail.body.encoded =~ %r{} - assert_equal $1, user.confirmation_token + assert_equal user.confirmation_token, $1 else flunk "expected confirmation url regex to match" end diff --git a/test/mailers/email_changed_test.rb b/test/mailers/email_changed_test.rb index f3578297a..f32416545 100644 --- a/test/mailers/email_changed_test.rb +++ b/test/mailers/email_changed_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class EmailChangedTest < ActionMailer::TestCase @@ -17,7 +19,7 @@ def teardown def user @user ||= create_user.tap { |u| @original_user_email = u.email - u.update_attributes!(email: 'new-email@example.com') + u.update!(email: 'new-email@example.com') } end @@ -33,7 +35,7 @@ def mail end test 'content type should be set to html' do - assert mail.content_type.include?('text/html') + assert_includes mail.content_type, 'text/html' end test 'send email changed to the original user email' do @@ -106,7 +108,7 @@ def teardown def admin @admin ||= create_admin.tap { |u| @original_admin_email = u.email - u.update_attributes!(email: 'new-email@example.com') + u.update!(email: 'new-email@example.com') } end diff --git a/test/mailers/mailer_test.rb b/test/mailers/mailer_test.rb index f6ec5d5ad..6f9f568e8 100644 --- a/test/mailers/mailer_test.rb +++ b/test/mailers/mailer_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class MailerTest < ActionMailer::TestCase @@ -15,4 +17,30 @@ def confirmation_instructions(record, token, opts = {}) assert mail.content_transfer_encoding, "7bit" end + + test "default values defined as proc with different arity are handled correctly" do + class TestMailerWithDefault < Devise::Mailer + default from: -> { computed_from } + default reply_to: ->(_) { computed_reply_to } + + def confirmation_instructions(record, token, opts = {}) + @token = token + devise_mail(record, :confirmation_instructions, opts) + end + + private + + def computed_from + "from@example.com" + end + + def computed_reply_to + "reply_to@example.com" + end + end + + mail = TestMailerWithDefault.confirmation_instructions(create_user, "confirmation-token") + assert mail.from, "from@example.com" + assert mail.reply_to, "reply_to@example.com" + end end diff --git a/test/mailers/reset_password_instructions_test.rb b/test/mailers/reset_password_instructions_test.rb index 511cadd32..5a344cbf0 100644 --- a/test/mailers/reset_password_instructions_test.rb +++ b/test/mailers/reset_password_instructions_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class ResetPasswordInstructionsTest < ActionMailer::TestCase @@ -27,12 +29,12 @@ def mail end end - test 'email sent after reseting the user password' do + test 'email sent after resetting the user password' do assert_not_nil mail end test 'content type should be set to html' do - assert mail.content_type.include?('text/html') + assert_includes mail.content_type, 'text/html' end test 'send confirmation instructions to the user email' do @@ -82,7 +84,7 @@ def mail host, port = ActionMailer::Base.default_url_options.values_at :host, :port if mail.body.encoded =~ %r{} - assert_equal Devise.token_generator.digest(user.class, :reset_password_token, $1), user.reset_password_token + assert_equal user.reset_password_token, Devise.token_generator.digest(user.class, :reset_password_token, $1) else flunk "expected reset password url regex to match" end diff --git a/test/mailers/unlock_instructions_test.rb b/test/mailers/unlock_instructions_test.rb index 32b998f3c..dff580e2e 100644 --- a/test/mailers/unlock_instructions_test.rb +++ b/test/mailers/unlock_instructions_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class UnlockInstructionsTest < ActionMailer::TestCase @@ -33,7 +35,7 @@ def mail end test 'content type should be set to html' do - assert mail.content_type.include?('text/html') + assert_includes mail.content_type, 'text/html' end test 'send unlock instructions to the user email' do @@ -83,7 +85,7 @@ def mail host, port = ActionMailer::Base.default_url_options.values_at :host, :port if mail.body.encoded =~ %r{} - assert_equal Devise.token_generator.digest(user.class, :unlock_token, $1), user.unlock_token + assert_equal user.unlock_token, Devise.token_generator.digest(user.class, :unlock_token, $1) else flunk "expected unlock url regex to match" end diff --git a/test/mapping_test.rb b/test/mapping_test.rb index b1010166f..9d60287cd 100644 --- a/test/mapping_test.rb +++ b/test/mapping_test.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'test_helper' class FakeRequest < Struct.new(:path_info, :params) end class MappingTest < ActiveSupport::TestCase - def fake_request(path, params={}) + def fake_request(path, params = {}) FakeRequest.new(path, params) end @@ -115,7 +117,7 @@ def user.devise_scope; :special_scope; end assert mapping.authenticatable? assert mapping.recoverable? assert mapping.lockable? - refute mapping.omniauthable? + assert_not mapping.omniauthable? end test 'find mapping by path' do diff --git a/test/models/authenticatable_test.rb b/test/models/authenticatable_test.rb index ba664f3ed..4d58b1e49 100644 --- a/test/models/authenticatable_test.rb +++ b/test/models/authenticatable_test.rb @@ -1,22 +1,49 @@ +# frozen_string_literal: true + require 'test_helper' class AuthenticatableTest < ActiveSupport::TestCase test 'required_fields should be an empty array' do - assert_equal Devise::Models::Validatable.required_fields(User), [] + assert_equal [], Devise::Models::Validatable.required_fields(User) end test 'find_first_by_auth_conditions allows custom filtering parameters' do user = User.create!(email: "example@example.com", password: "1234567") - assert_equal User.find_first_by_auth_conditions({ email: "example@example.com" }), user + assert_equal user, User.find_first_by_auth_conditions({ email: "example@example.com" }) assert_nil User.find_first_by_auth_conditions({ email: "example@example.com" }, id: user.id.to_s.next) end + # assumes default configuration of + # config.case_insensitive_keys = [:email] + # config.strip_whitespace_keys = [:email] + test 'find_or_initialize_with_errors uses parameter filter on find' do + user = User.create!(email: "example@example.com", password: "1234567") + assert_equal user, User.find_or_initialize_with_errors([:email], { email: " EXAMPLE@example.com " }) + end + + # assumes default configuration of + # config.case_insensitive_keys = [:email] + # config.strip_whitespace_keys = [:email] + test 'find_or_initialize_with_errors uses parameter filter on initialize' do + assert_equal "example@example.com", User.find_or_initialize_with_errors([:email], { email: " EXAMPLE@example.com " }).email + end + + test 'find_or_initialize_with_errors adds blank error' do + user_with_error = User.find_or_initialize_with_errors([:email], { email: "" }) + assert user_with_error.errors.added?(:email, :blank) + end + + test 'find_or_initialize_with_errors adds invalid error' do + user_with_error = User.find_or_initialize_with_errors([:email], { email: "example@example.com" }) + assert user_with_error.errors.added?(:email, :invalid) + end + if defined?(ActionController::Parameters) test 'does not passes an ActionController::Parameters to find_first_by_auth_conditions through find_or_initialize_with_errors' do user = create_user(email: 'example@example.com') attributes = ActionController::Parameters.new(email: 'example@example.com') - User.expects(:find_first_by_auth_conditions).with('email' => 'example@example.com').returns(user) + User.expects(:find_first_by_auth_conditions).with({ 'email' => 'example@example.com' }).returns(user) User.find_or_initialize_with_errors([:email], attributes) end end diff --git a/test/models/confirmable_test.rb b/test/models/confirmable_test.rb index e0f08cc00..31a955e72 100644 --- a/test/models/confirmable_test.rb +++ b/test/models/confirmable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class ConfirmableTest < ActiveSupport::TestCase @@ -6,6 +8,17 @@ def setup setup_mailer end + test 'should set callbacks to send the mail' do + if DEVISE_ORM == :active_record + defined_callbacks = User._commit_callbacks.map(&:filter) + assert_includes defined_callbacks, :send_on_create_confirmation_instructions + assert_includes defined_callbacks, :send_reconfirmation_instructions + elsif DEVISE_ORM == :mongoid + assert_includes User._create_callbacks.map(&:filter), :send_on_create_confirmation_instructions + assert_includes User._update_callbacks.map(&:filter), :send_reconfirmation_instructions + end + end + test 'should generate confirmation token after creating a record' do assert_nil new_user.confirmation_token assert_not_nil create_user.confirmation_token @@ -15,7 +28,7 @@ def setup confirmation_tokens = [] 3.times do token = create_user.confirmation_token - assert !confirmation_tokens.include?(token) + assert_not_includes confirmation_tokens, token confirmation_tokens << token end end @@ -28,9 +41,9 @@ def setup end test 'should verify whether a user is confirmed or not' do - refute new_user.confirmed? + assert_not new_user.confirmed? user = create_user - refute user.confirmed? + assert_not user.confirmed? user.confirm assert user.confirmed? end @@ -40,7 +53,7 @@ def setup assert user.confirm assert_blank user.errors[:email] - refute user.confirm + assert_not user.confirm assert_equal "was already confirmed, please try signing in", user.errors[:email].join end @@ -48,20 +61,38 @@ def setup user = create_user raw = user.raw_confirmation_token confirmed_user = User.confirm_by_token(raw) - assert_equal confirmed_user, user + assert_equal user, confirmed_user assert user.reload.confirmed? end test 'should return a new record with errors when a invalid token is given' do confirmed_user = User.confirm_by_token('invalid_confirmation_token') - refute confirmed_user.persisted? + assert_not confirmed_user.persisted? assert_equal "is invalid", confirmed_user.errors[:confirmation_token].join end test 'should return a new record with errors when a blank token is given' do confirmed_user = User.confirm_by_token('') - refute confirmed_user.persisted? - assert_equal "can't be blank", confirmed_user.errors[:confirmation_token].join + assert_not confirmed_user.persisted? + assert confirmed_user.errors.added?(:confirmation_token, :blank) + end + + test 'should return a new record with errors when a blank token is given and a record exists on the database' do + user = create_user(confirmation_token: '') + + confirmed_user = User.confirm_by_token('') + + assert_not user.reload.confirmed? + assert confirmed_user.errors.added?(:confirmation_token, :blank) + end + + test 'should return a new record with errors when a nil token is given and a record exists on the database' do + user = create_user(confirmation_token: nil) + + confirmed_user = User.confirm_by_token(nil) + + assert_not user.reload.confirmed? + assert confirmed_user.errors.added?(:confirmation_token, :blank) end test 'should generate errors for a user email if user is already confirmed' do @@ -114,7 +145,7 @@ def setup assert_email_not_sent do user.save! - refute user.confirmed? + assert_not user.confirmed? end end @@ -129,12 +160,12 @@ def setup test 'should find a user to send confirmation instructions' do user = create_user confirmation_user = User.send_confirmation_instructions(email: user.email) - assert_equal confirmation_user, user + assert_equal user, confirmation_user end test 'should return a new user if no email was found' do confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com") - refute confirmation_user.persisted? + assert_not confirmation_user.persisted? end test 'should add error to new user email if no email was found' do @@ -181,7 +212,7 @@ def setup test 'should not be able to send instructions if the user is already confirmed' do user = create_user user.confirm - refute user.resend_confirmation_instructions + assert_not user.resend_confirmation_instructions assert user.confirmed? assert_equal 'was already confirmed, please try signing in', user.errors[:email].join end @@ -190,7 +221,7 @@ def setup swap Devise, allow_unconfirmed_access_for: 1.day do user = create_user user.confirmation_sent_at = 2.days.ago - refute user.active_for_authentication? + assert_not user.active_for_authentication? Devise.allow_unconfirmed_access_for = 3.days assert user.active_for_authentication? @@ -206,14 +237,14 @@ def setup assert user.active_for_authentication? user.confirmation_sent_at = 5.days.ago - refute user.active_for_authentication? + assert_not user.active_for_authentication? end end test 'should be active when already confirmed' do user = create_user - refute user.confirmed? - refute user.active_for_authentication? + assert_not user.confirmed? + assert_not user.active_for_authentication? user.confirm assert user.confirmed? @@ -224,7 +255,17 @@ def setup Devise.allow_unconfirmed_access_for = 0.days user = create_user user.confirmation_sent_at = Time.zone.today - refute user.active_for_authentication? + assert_not user.active_for_authentication? + end + + test 'should not be active when confirm period is set to 0 days' do + Devise.allow_unconfirmed_access_for = 0.days + user = create_user + + Timecop.freeze(Time.zone.today) do + user.confirmation_sent_at = Time.zone.today + assert_not user.active_for_authentication? + end end test 'should be active when we set allow_unconfirmed_access_for to nil' do @@ -239,7 +280,7 @@ def setup user = create_user user.confirmation_sent_at = nil user.save - refute user.reload.active_for_authentication? + assert_not user.reload.active_for_authentication? end test 'should be active without confirmation when confirmation is not required' do @@ -264,7 +305,7 @@ def setup swap Devise, authentication_keys: [:username, :email] do user = create_user confirm_user = User.send_confirmation_instructions(email: user.email, username: user.username) - assert_equal confirm_user, user + assert_equal user, confirm_user end end @@ -272,8 +313,8 @@ def setup swap Devise, confirmation_keys: [:username, :email] do user = create_user confirm_user = User.send_confirmation_instructions(email: user.email) - refute confirm_user.persisted? - assert_equal "can't be blank", confirm_user.errors[:username].join + assert_not confirm_user.persisted? + assert confirm_user.errors.added?(:username, :blank) end end @@ -281,7 +322,7 @@ def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at) user = create_user user.update_attribute(:confirmation_sent_at, confirmation_sent_at) confirmed_user = User.confirm_by_token(user.raw_confirmation_token) - assert_equal confirmed_user, user + assert_equal user, confirmed_user user.reload.confirmed? end @@ -297,7 +338,7 @@ def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at) test 'should not accept confirmation email token after 4 days when expiration is set to 3 days' do swap Devise, confirm_within: 3.days do - refute confirm_user_by_token_with_confirmation_sent_at(4.days.ago) + assert_not confirm_user_by_token_with_confirmation_sent_at(4.days.ago) end end @@ -337,14 +378,14 @@ def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at) self.username = self.username.to_s + 'updated' end old = user.username - refute user.confirm + assert_not user.confirm assert_equal user.username, old end test 'should always perform validations upon confirm when ensure valid true' do admin = create_admin admin.stubs(:valid?).returns(false) - refute admin.confirm(ensure_valid: true) + assert_not admin.confirm(ensure_valid: true) end end @@ -359,7 +400,7 @@ class ReconfirmableTest < ActiveSupport::TestCase admin = create_admin assert admin.confirm residual_token = admin.confirmation_token - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert_not_equal residual_token, admin.confirmation_token end @@ -368,9 +409,9 @@ class ReconfirmableTest < ActiveSupport::TestCase original_token = admin.confirmation_token assert admin.confirm admin.skip_reconfirmation! - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert admin.confirmed? - refute admin.pending_reconfirmation? + assert_not admin.pending_reconfirmation? assert_equal original_token, admin.confirmation_token end @@ -379,16 +420,16 @@ class ReconfirmableTest < ActiveSupport::TestCase admin.skip_confirmation_notification! assert_email_not_sent do - admin.update_attributes(email: 'new_test@example.com') + admin.update(email: 'new_test@example.com') end end test 'should regenerate confirmation token after changing email' do admin = create_admin assert admin.confirm - assert admin.update_attributes(email: 'old_test@example.com') + assert admin.update(email: 'old_test@example.com') token = admin.confirmation_token - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert_not_equal token, admin.confirmation_token end @@ -396,7 +437,7 @@ class ReconfirmableTest < ActiveSupport::TestCase admin = create_admin assert admin.confirm assert_email_sent "new_test@example.com" do - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') end assert_match "new_test@example.com", ActionMailer::Base.deliveries.last.body.encoded end @@ -404,7 +445,7 @@ class ReconfirmableTest < ActiveSupport::TestCase test 'should send confirmation instructions by email after changing email from nil' do admin = create_admin(email: nil) assert_email_sent "new_test@example.com" do - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') end assert_match "new_test@example.com", ActionMailer::Base.deliveries.last.body.encoded end @@ -413,7 +454,7 @@ class ReconfirmableTest < ActiveSupport::TestCase admin = create_admin assert admin.confirm assert_email_not_sent do - assert admin.update_attributes(password: 'newpass', password_confirmation: 'newpass') + assert admin.update(password: 'newpass', password_confirmation: 'newpass') end end @@ -429,14 +470,14 @@ class ReconfirmableTest < ActiveSupport::TestCase test 'should stay confirmed when email is changed' do admin = create_admin assert admin.confirm - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert admin.confirmed? end test 'should update email only when it is confirmed' do admin = create_admin assert admin.confirm - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email assert admin.confirm assert_equal 'new_test@example.com', admin.email @@ -445,23 +486,23 @@ class ReconfirmableTest < ActiveSupport::TestCase test 'should not allow admin to get past confirmation email by resubmitting their new address' do admin = create_admin assert admin.confirm - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email end test 'should find a admin by send confirmation instructions with unconfirmed_email' do admin = create_admin assert admin.confirm - assert admin.update_attributes(email: 'new_test@example.com') + assert admin.update(email: 'new_test@example.com') confirmation_admin = Admin.send_confirmation_instructions(email: admin.unconfirmed_email) - assert_equal confirmation_admin, admin + assert_equal admin, confirmation_admin end test 'should return a new admin if no email or unconfirmed_email was found' do confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com") - refute confirmation_admin.persisted? + assert_not confirmation_admin.persisted? end test 'should add error to new admin email if no email or unconfirmed_email was found' do @@ -479,25 +520,25 @@ class ReconfirmableTest < ActiveSupport::TestCase end test 'required_fields should contain the fields that Devise uses' do - assert_equal Devise::Models::Confirmable.required_fields(User), [ + assert_equal [ :confirmation_token, :confirmed_at, :confirmation_sent_at - ] + ], Devise::Models::Confirmable.required_fields(User) end test 'required_fields should also contain unconfirmable when reconfirmable_email is true' do - assert_equal Devise::Models::Confirmable.required_fields(Admin), [ + assert_equal [ :confirmation_token, :confirmed_at, :confirmation_sent_at, :unconfirmed_email - ] + ], Devise::Models::Confirmable.required_fields(Admin) end test 'should not require reconfirmation after creating a record' do admin = create_admin - assert !admin.pending_reconfirmation? + assert_not admin.pending_reconfirmation? end test 'should not require reconfirmation after creating a record with #save called in callback' do @@ -506,12 +547,12 @@ class Admin::WithSaveInCallback < Admin end admin = Admin::WithSaveInCallback.create(valid_attributes.except(:username)) - assert !admin.pending_reconfirmation? + assert_not admin.pending_reconfirmation? end test 'should require reconfirmation after creating a record and updating the email' do admin = create_admin - assert !admin.instance_variable_get(:@bypass_confirmation_postpone) + assert_not admin.instance_variable_get(:@bypass_confirmation_postpone) admin.email = "new_test@email.com" admin.save assert admin.pending_reconfirmation? @@ -523,7 +564,7 @@ class Admin::WithSaveInCallback < Admin original_email = admin.email assert_difference 'ActionMailer::Base.deliveries.size', 2 do - assert admin.update_attributes(email: 'new-email@example.com') + assert admin.update(email: 'new-email@example.com') end assert_equal original_email, ActionMailer::Base.deliveries[-2]['to'].to_s assert_equal 'new-email@example.com', ActionMailer::Base.deliveries[-1]['to'].to_s diff --git a/test/models/database_authenticatable_test.rb b/test/models/database_authenticatable_test.rb index a5c7c77fa..909e01045 100644 --- a/test/models/database_authenticatable_test.rb +++ b/test/models/database_authenticatable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' require 'test_models' require 'digest/sha1' @@ -86,10 +88,17 @@ def setup assert_equal( {'strip_whitespace' => 'strip_whitespace_val', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '}, conditions ) end + test 'param filter should not add keys to filtered hash' do + conditions = { 'present' => 'present_val' } + conditions.default = '' + conditions = Devise::ParameterFilter.new(['not_present'], []).filter(conditions) + assert_equal({ 'present' => 'present_val' }, conditions) + end + test 'should respond to password and password confirmation' do user = new_user - assert user.respond_to?(:password) - assert user.respond_to?(:password_confirmation) + assert_respond_to user, :password + assert_respond_to user, :password_confirmation end test 'should generate a hashed password while setting password' do @@ -99,7 +108,7 @@ def setup test 'should support custom hashing methods' do user = UserWithCustomHashing.new(password: '654321') - assert_equal user.encrypted_password, '123456' + assert_equal '123456', user.encrypted_password end test 'allow authenticatable_salt to work even with nil hashed password' do @@ -124,7 +133,7 @@ def setup test 'should test for a valid password' do user = create_user assert user.valid_password?('12345678') - refute user.valid_password?('654321') + assert_not user.valid_password?('654321') end test 'should not raise error with an empty password' do @@ -136,11 +145,11 @@ def setup test 'should be an invalid password if the user has an empty password' do user = create_user user.encrypted_password = '' - refute user.valid_password?('654321') + assert_not user.valid_password?('654321') end test 'should respond to current password' do - assert new_user.respond_to?(:current_password) + assert_respond_to new_user, :current_password end test 'should update password with valid current password' do @@ -152,7 +161,7 @@ def setup test 'should add an error to current password when it is invalid' do user = create_user - refute user.update_with_password(current_password: 'other', + assert_not user.update_with_password(current_password: 'other', password: 'pass4321', password_confirmation: 'pass4321') assert user.reload.valid_password?('12345678') assert_match "is invalid", user.errors[:current_password].join @@ -160,19 +169,19 @@ def setup test 'should add an error to current password when it is blank' do user = create_user - refute user.update_with_password(password: 'pass4321', + assert_not user.update_with_password(password: 'pass4321', password_confirmation: 'pass4321') assert user.reload.valid_password?('12345678') - assert_match "can't be blank", user.errors[:current_password].join + assert user.errors.added?(:current_password, :blank) end test 'should run validations even when current password is invalid or blank' do user = UserWithValidation.create!(valid_attributes) user.save assert user.persisted? - refute user.update_with_password(username: "") + assert_not user.update_with_password(username: "") assert_match "usertest", user.reload.username - assert_match "can't be blank", user.errors[:username].join + assert user.errors.added?(:username, :blank) end test 'should ignore password and its confirmation if they are blank' do @@ -183,14 +192,14 @@ def setup test 'should not update password with invalid confirmation' do user = create_user - refute user.update_with_password(current_password: '12345678', + assert_not user.update_with_password(current_password: '12345678', password: 'pass4321', password_confirmation: 'other') assert user.reload.valid_password?('12345678') end test 'should clean up password fields on failure' do user = create_user - refute user.update_with_password(current_password: '12345678', + assert_not user.update_with_password(current_password: '12345678', password: 'pass4321', password_confirmation: 'other') assert user.password.blank? assert user.password_confirmation.blank? @@ -205,34 +214,34 @@ def setup test 'should not update password without password' do user = create_user user.update_without_password(password: 'pass4321', password_confirmation: 'pass4321') - assert !user.reload.valid_password?('pass4321') + assert_not user.reload.valid_password?('pass4321') assert user.valid_password?('12345678') end test 'should destroy user if current password is valid' do user = create_user assert user.destroy_with_password('12345678') - assert !user.persisted? + assert_not user.persisted? end test 'should not destroy user with invalid password' do user = create_user - refute user.destroy_with_password('other') + assert_not user.destroy_with_password('other') assert user.persisted? assert_match "is invalid", user.errors[:current_password].join end test 'should not destroy user with blank password' do user = create_user - refute user.destroy_with_password(nil) + assert_not user.destroy_with_password(nil) assert user.persisted? - assert_match "can't be blank", user.errors[:current_password].join + assert user.errors.added?(:current_password, :blank) end test 'should not email on password change' do user = create_user assert_email_not_sent do - assert user.update_attributes(password: 'newpass', password_confirmation: 'newpass') + assert user.update(password: 'newpass', password_confirmation: 'newpass') end end @@ -241,7 +250,7 @@ def setup user = create_user original_email = user.email assert_email_sent original_email do - assert user.update_attributes(email: 'new-email@example.com') + assert user.update(email: 'new-email@example.com') end assert_match original_email, ActionMailer::Base.deliveries.last.body.encoded end @@ -251,31 +260,51 @@ def setup swap Devise, send_password_change_notification: true do user = create_user assert_email_sent user.email do - assert user.update_attributes(password: 'newpass', password_confirmation: 'newpass') + assert user.update(password: 'newpass', password_confirmation: 'newpass') end assert_match user.email, ActionMailer::Base.deliveries.last.body.encoded end end + test 'should not notify email on password change even when configured if skip_password_change_notification! is invoked' do + swap Devise, send_password_change_notification: true do + user = create_user + user.skip_password_change_notification! + assert_email_not_sent do + assert user.update(password: 'newpass', password_confirmation: 'newpass') + end + end + end + + test 'should not notify email on email change even when configured if skip_email_changed_notification! is invoked' do + swap Devise, send_email_changed_notification: true do + user = create_user + user.skip_email_changed_notification! + assert_email_not_sent do + assert user.update(email: 'new-email@example.com') + end + end + end + test 'downcase_keys with validation' do User.create(email: "HEllO@example.com", password: "123456") user = User.create(email: "HEllO@example.com", password: "123456") - assert !user.valid? + assert_not user.valid? end test 'required_fields should be encryptable_password and the email field by default' do - assert_equal Devise::Models::DatabaseAuthenticatable.required_fields(User), [ + assert_equal [ :encrypted_password, :email - ] + ], Devise::Models::DatabaseAuthenticatable.required_fields(User) end test 'required_fields should be encryptable_password and the login when the login is on authentication_keys' do swap Devise, authentication_keys: [:login] do - assert_equal Devise::Models::DatabaseAuthenticatable.required_fields(User), [ + assert_equal [ :encrypted_password, :login - ] + ], Devise::Models::DatabaseAuthenticatable.required_fields(User) end end end diff --git a/test/models/lockable_test.rb b/test/models/lockable_test.rb index 52373b819..b1d8cab0d 100644 --- a/test/models/lockable_test.rb +++ b/test/models/lockable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class LockableTest < ActiveSupport::TestCase @@ -32,11 +34,48 @@ def setup user.confirm swap Devise, lock_strategy: :none, maximum_attempts: 2 do 3.times { user.valid_for_authentication?{ false } } - assert !user.access_locked? + assert_not user.access_locked? assert_equal 0, user.failed_attempts end end + test "should read failed_attempts from database when incrementing" do + user = create_user + initial_failed_attempts = user.failed_attempts + same_user = User.find(user.id) + + user.increment_failed_attempts + same_user.increment_failed_attempts + + assert_equal initial_failed_attempts + 2, user.reload.failed_attempts + end + + test "reset_failed_attempts! updates the failed attempts counter back to 0" do + user = create_user(failed_attempts: 3) + assert_equal 3, user.failed_attempts + + user.reset_failed_attempts! + assert_equal 0, user.failed_attempts + + user.reset_failed_attempts! + assert_equal 0, user.failed_attempts + end + + test "reset_failed_attempts! does not run model validations" do + user = create_user(failed_attempts: 1) + user.expects(:after_validation_callback).never + + assert user.reset_failed_attempts! + assert_equal 0, user.failed_attempts + end + + test "reset_failed_attempts! does not try to reset if not using failed attempts strategy" do + admin = create_admin + + assert_not_respond_to admin, :failed_attempts + assert_not admin.reset_failed_attempts! + end + test 'should be valid for authentication with a unlocked user' do user = create_user user.lock_access! @@ -46,7 +85,7 @@ def setup test "should verify whether a user is locked or not" do user = create_user - refute user.access_locked? + assert_not user.access_locked? user.lock_access! assert user.access_locked? end @@ -56,7 +95,7 @@ def setup user.confirm assert user.active_for_authentication? user.lock_access! - refute user.active_for_authentication? + assert_not user.active_for_authentication? end test "should unlock a user by cleaning locked_at, failed_attempts and unlock_token" do @@ -72,7 +111,7 @@ def setup end test "new user should not be locked and should have zero failed_attempts" do - refute new_user.access_locked? + assert_not new_user.access_locked? assert_equal 0, create_user.failed_attempts end @@ -83,7 +122,7 @@ def setup assert user.access_locked? Devise.unlock_in = 1.hour - refute user.access_locked? + assert_not user.access_locked? end end @@ -108,7 +147,7 @@ def setup user = create_user user.lock_access! token = user.unlock_token - assert !unlock_tokens.include?(token) + assert_not_includes unlock_tokens, token unlock_tokens << token end end @@ -161,32 +200,32 @@ def setup user = create_user raw = user.send_unlock_instructions locked_user = User.unlock_access_by_token(raw) - assert_equal locked_user, user - refute user.reload.access_locked? + assert_equal user, locked_user + assert_not user.reload.access_locked? end test 'should return a new record with errors when a invalid token is given' do locked_user = User.unlock_access_by_token('invalid_token') - refute locked_user.persisted? + assert_not locked_user.persisted? assert_equal "is invalid", locked_user.errors[:unlock_token].join end test 'should return a new record with errors when a blank token is given' do locked_user = User.unlock_access_by_token('') - refute locked_user.persisted? - assert_equal "can't be blank", locked_user.errors[:unlock_token].join + assert_not locked_user.persisted? + assert locked_user.errors.added?(:unlock_token, :blank) end test 'should find a user to send unlock instructions' do user = create_user user.lock_access! unlock_user = User.send_unlock_instructions(email: user.email) - assert_equal unlock_user, user + assert_equal user, unlock_user end test 'should return a new user if no email was found' do unlock_user = User.send_unlock_instructions(email: "invalid@example.com") - refute unlock_user.persisted? + assert_not unlock_user.persisted? end test 'should add error to new user email if no email was found' do @@ -198,7 +237,7 @@ def setup swap Devise, authentication_keys: [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(email: user.email, username: user.username) - assert_equal unlock_user, user + assert_equal user, unlock_user end end @@ -206,23 +245,23 @@ def setup swap Devise, unlock_keys: [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(email: user.email) - refute unlock_user.persisted? - assert_equal "can't be blank", unlock_user.errors[:username].join + assert_not unlock_user.persisted? + assert unlock_user.errors.added?(:username, :blank) end end test 'should not be able to send instructions if the user is not locked' do user = create_user - refute user.resend_unlock_instructions - refute user.access_locked? + assert_not user.resend_unlock_instructions + assert_not user.access_locked? assert_equal 'was not locked', user.errors[:email].join end test 'should not be able to send instructions if the user if not locked and have username as unlock key' do swap Devise, unlock_keys: [:username] do user = create_user - refute user.resend_unlock_instructions - refute user.access_locked? + assert_not user.resend_unlock_instructions + assert_not user.access_locked? assert_equal 'was not locked', user.errors[:username].join end end @@ -257,11 +296,11 @@ def setup test 'required_fields should contain the all the fields when all the strategies are enabled' do swap Devise, unlock_strategy: :both do swap Devise, lock_strategy: :failed_attempts do - assert_equal Devise::Models::Lockable.required_fields(User), [ - :failed_attempts, - :locked_at, - :unlock_token - ] + assert_equal [ + :failed_attempts, + :locked_at, + :unlock_token + ], Devise::Models::Lockable.required_fields(User) end end end @@ -269,10 +308,10 @@ def setup test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do swap Devise, unlock_strategy: :time do swap Devise, lock_strategy: :failed_attempts do - assert_equal Devise::Models::Lockable.required_fields(User), [ - :failed_attempts, - :locked_at - ] + assert_equal [ + :failed_attempts, + :locked_at + ], Devise::Models::Lockable.required_fields(User) end end end @@ -280,10 +319,10 @@ def setup test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do swap Devise, unlock_strategy: :email do swap Devise, lock_strategy: :failed_attempts do - assert_equal Devise::Models::Lockable.required_fields(User), [ - :failed_attempts, - :unlock_token - ] + assert_equal [ + :failed_attempts, + :unlock_token + ], Devise::Models::Lockable.required_fields(User) end end end diff --git a/test/models/omniauthable_test.rb b/test/models/omniauthable_test.rb index 03e1f6886..22cea976c 100644 --- a/test/models/omniauthable_test.rb +++ b/test/models/omniauthable_test.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'test_helper' class OmniauthableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do - assert_equal Devise::Models::Omniauthable.required_fields(User), [] + assert_equal [], Devise::Models::Omniauthable.required_fields(User) end end diff --git a/test/models/recoverable_test.rb b/test/models/recoverable_test.rb index 96b36187d..b2234ac6a 100644 --- a/test/models/recoverable_test.rb +++ b/test/models/recoverable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class RecoverableTest < ActiveSupport::TestCase @@ -16,7 +18,7 @@ def setup user = create_user user.send_reset_password_instructions token = user.reset_password_token - assert !reset_password_tokens.include?(token) + assert_not_includes reset_password_tokens, token reset_password_tokens << token end end @@ -32,7 +34,7 @@ def setup assert create_user.reset_password('123456789', '123456789') end - test 'should clear reset password token while reseting the password' do + test 'should clear reset password token while resetting the password' do user = create_user assert_nil user.reset_password_token @@ -92,14 +94,14 @@ def setup user = create_user user.send_reset_password_instructions assert_present user.reset_password_token - refute user.reset_password('123456789', '987654321') + assert_not user.reset_password('123456789', '987654321') assert_present user.reset_password_token end test 'should not reset password with invalid data' do user = create_user user.stubs(:valid?).returns(false) - refute user.reset_password('123456789', '987654321') + assert_not user.reset_password('123456789', '987654321') end test 'should reset reset password token and send instructions by email' do @@ -114,12 +116,12 @@ def setup test 'should find a user to send instructions by email' do user = create_user reset_password_user = User.send_reset_password_instructions(email: user.email) - assert_equal reset_password_user, user + assert_equal user, reset_password_user end test 'should return a new record with errors if user was not found by e-mail' do reset_password_user = User.send_reset_password_instructions(email: "invalid@example.com") - refute reset_password_user.persisted? + assert_not reset_password_user.persisted? assert_equal "not found", reset_password_user.errors[:email].join end @@ -127,17 +129,17 @@ def setup swap Devise, authentication_keys: [:username, :email] do user = create_user reset_password_user = User.send_reset_password_instructions(email: user.email, username: user.username) - assert_equal reset_password_user, user + assert_equal user, reset_password_user end end test 'should require all reset_password_keys' do - swap Devise, reset_password_keys: [:username, :email] do - user = create_user - reset_password_user = User.send_reset_password_instructions(email: user.email) - refute reset_password_user.persisted? - assert_equal "can't be blank", reset_password_user.errors[:username].join - end + swap Devise, reset_password_keys: [:username, :email] do + user = create_user + reset_password_user = User.send_reset_password_instructions(email: user.email) + assert_not reset_password_user.persisted? + assert reset_password_user.errors.added?(:username, :blank) + end end test 'should reset reset_password_token before send the reset instructions email' do @@ -159,19 +161,19 @@ def setup raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token(reset_password_token: raw) - assert_equal reset_password_user, user + assert_equal user, reset_password_user end test 'should return a new record with errors if no reset_password_token is found' do reset_password_user = User.reset_password_by_token(reset_password_token: 'invalid_token') - refute reset_password_user.persisted? + assert_not reset_password_user.persisted? assert_equal "is invalid", reset_password_user.errors[:reset_password_token].join end test 'should return a new record with errors if reset_password_token is blank' do reset_password_user = User.reset_password_by_token(reset_password_token: '') - refute reset_password_user.persisted? - assert_match "can't be blank", reset_password_user.errors[:reset_password_token].join + assert_not reset_password_user.persisted? + assert reset_password_user.errors.added?(:reset_password_token, :blank) end test 'should return a new record with errors if password is blank' do @@ -179,8 +181,8 @@ def setup raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token(reset_password_token: raw, password: '') - refute reset_password_user.errors.empty? - assert_match "can't be blank", reset_password_user.errors[:password].join + assert_not reset_password_user.errors.empty? + assert reset_password_user.errors.added?(:password, :blank) assert_equal raw, reset_password_user.reset_password_token end @@ -189,8 +191,8 @@ def setup raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token(reset_password_token: raw) - refute reset_password_user.errors.empty? - assert_match "can't be blank", reset_password_user.errors[:password].join + assert_not reset_password_user.errors.empty? + assert reset_password_user.errors.added?(:password, :blank) assert_equal raw, reset_password_user.reset_password_token end @@ -207,7 +209,7 @@ def setup assert_nil reset_password_user.reset_password_token user.reload - refute user.valid_password?(old_password) + assert_not user.valid_password?(old_password) assert user.valid_password?('new_password') assert_nil user.reset_password_token end @@ -229,29 +231,29 @@ def setup user.reload assert user.valid_password?(old_password) - refute user.valid_password?('new_password') + assert_not user.valid_password?('new_password') assert_equal "has expired, please request a new one", reset_password_user.errors[:reset_password_token].join end end test 'required_fields should contain the fields that Devise uses' do - assert_equal Devise::Models::Recoverable.required_fields(User), [ + assert_equal [ :reset_password_sent_at, :reset_password_token - ] + ], Devise::Models::Recoverable.required_fields(User) end test 'should return a user based on the raw token' do user = create_user raw = user.send_reset_password_instructions - assert_equal User.with_reset_password_token(raw), user + assert_equal user, User.with_reset_password_token(raw) end test 'should return the same reset password token as generated' do user = create_user raw = user.send_reset_password_instructions - assert_equal Devise.token_generator.digest(self.class, :reset_password_token, raw), user.reset_password_token + assert_equal user.reset_password_token, Devise.token_generator.digest(self.class, :reset_password_token, raw) end test 'should return nil if a user based on the raw token is not found' do diff --git a/test/models/registerable_test.rb b/test/models/registerable_test.rb index bef6c8ce4..df5cf6fcf 100644 --- a/test/models/registerable_test.rb +++ b/test/models/registerable_test.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'test_helper' class RegisterableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do - assert_equal Devise::Models::Registerable.required_fields(User), [] + assert_equal [], Devise::Models::Registerable.required_fields(User) end end diff --git a/test/models/rememberable_test.rb b/test/models/rememberable_test.rb index aa9ce817a..8b8317212 100644 --- a/test/models/rememberable_test.rb +++ b/test/models/rememberable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class RememberableTest < ActiveSupport::TestCase @@ -127,8 +129,8 @@ def user.authenticatable_salt; ""; end end test 'should respond to remember_me attribute' do - assert resource_class.new.respond_to?(:remember_me) - assert resource_class.new.respond_to?(:remember_me=) + assert_respond_to resource_class.new, :remember_me + assert_respond_to resource_class.new, :remember_me= end test 'forget_me should clear remember_created_at if expire_all_remember_me_on_sign_out is true' do @@ -175,8 +177,8 @@ def user.authenticatable_salt; ""; end end test 'should have the required_fields array' do - assert_equal Devise::Models::Rememberable.required_fields(User), [ + assert_equal [ :remember_created_at - ] + ], Devise::Models::Rememberable.required_fields(User) end end diff --git a/test/models/serializable_test.rb b/test/models/serializable_test.rb index 6ced12d99..024ccf449 100644 --- a/test/models/serializable_test.rb +++ b/test/models/serializable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class SerializableTest < ActiveSupport::TestCase @@ -5,21 +7,6 @@ class SerializableTest < ActiveSupport::TestCase @user = create_user end - test 'should not include unsafe keys on XML' do - assert_match(/email/, @user.to_xml) - assert_no_match(/confirmation-token/, @user.to_xml) - end - - test 'should not include unsafe keys on XML even if a new except is provided' do - assert_no_match(/email/, @user.to_xml(except: :email)) - assert_no_match(/confirmation-token/, @user.to_xml(except: :email)) - end - - test 'should include unsafe keys on XML if a force_except is provided' do - assert_no_match(/ 'jose' }, sanitized) end + test 'permits empty params when received not a hash' do + sanitizer = sanitizer({ 'user' => 'string' }) + sanitized = sanitizer.sanitize(:sign_in) + + assert_equal({}, sanitized) + end + + test 'does not rise error when received string instead of hash' do + sanitizer = sanitizer('user' => 'string') + assert_nothing_raised do + sanitizer.sanitize(:sign_in) + end + end + + test 'does not rise error when received nil instead of hash' do + sanitizer = sanitizer('user' => nil) + assert_nothing_raised do + sanitizer.sanitize(:sign_in) + end + end + + test 'permits empty params when received nil instead of hash' do + sanitizer = sanitizer({ 'user' => nil }) + sanitized = sanitizer.sanitize(:sign_in) + + assert_equal({}, sanitized) + end + test 'permits the default parameters for sign up' do sanitizer = sanitizer('user' => { 'email' => 'jose', 'role' => 'invalid' }) sanitized = sanitizer.sanitize(:sign_up) diff --git a/test/rails_app/app/active_record/admin.rb b/test/rails_app/app/active_record/admin.rb index 124bc9059..5383b3b23 100644 --- a/test/rails_app/app/active_record/admin.rb +++ b/test/rails_app/app/active_record/admin.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_admin' class Admin < ActiveRecord::Base diff --git a/test/rails_app/app/active_record/shim.rb b/test/rails_app/app/active_record/shim.rb index 66f12cdb1..be35adb9b 100644 --- a/test/rails_app/app/active_record/shim.rb +++ b/test/rails_app/app/active_record/shim.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + module Shim end diff --git a/test/rails_app/app/active_record/user.rb b/test/rails_app/app/active_record/user.rb index 78b3530ae..37d454df4 100644 --- a/test/rails_app/app/active_record/user.rb +++ b/test/rails_app/app/active_record/user.rb @@ -1,7 +1,19 @@ +# frozen_string_literal: true + require 'shared_user' class User < ActiveRecord::Base include Shim include SharedUser - include ActiveModel::Serializers::Xml if Devise::Test.rails5? + + validates :sign_in_count, presence: true + + cattr_accessor :validations_performed + + after_validation :after_validation_callback + + def after_validation_callback + # used to check in our test if the validations were called + @@validations_performed = true + end end diff --git a/test/rails_app/app/active_record/user_on_engine.rb b/test/rails_app/app/active_record/user_on_engine.rb index 21eb30501..42f233f36 100644 --- a/test/rails_app/app/active_record/user_on_engine.rb +++ b/test/rails_app/app/active_record/user_on_engine.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_user_without_omniauth' class UserOnEngine < ActiveRecord::Base diff --git a/test/rails_app/app/active_record/user_on_main_app.rb b/test/rails_app/app/active_record/user_on_main_app.rb index 54ef1f804..596bc3b94 100644 --- a/test/rails_app/app/active_record/user_on_main_app.rb +++ b/test/rails_app/app/active_record/user_on_main_app.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_user_without_omniauth' class UserOnMainApp < ActiveRecord::Base diff --git a/test/rails_app/app/active_record/user_with_validations.rb b/test/rails_app/app/active_record/user_with_validations.rb new file mode 100644 index 000000000..c396ba883 --- /dev/null +++ b/test/rails_app/app/active_record/user_with_validations.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require 'shared_user' + +class UserWithValidations < ActiveRecord::Base + self.table_name = 'users' + include Shim + include SharedUser + + validates :email, presence: true +end + diff --git a/test/rails_app/app/active_record/user_without_email.rb b/test/rails_app/app/active_record/user_without_email.rb index 9ad581884..62bdb8976 100644 --- a/test/rails_app/app/active_record/user_without_email.rb +++ b/test/rails_app/app/active_record/user_without_email.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "shared_user_without_email" class UserWithoutEmail < ActiveRecord::Base diff --git a/test/rails_app/app/controllers/admins/sessions_controller.rb b/test/rails_app/app/controllers/admins/sessions_controller.rb index 525ca5ef1..122e15a77 100644 --- a/test/rails_app/app/controllers/admins/sessions_controller.rb +++ b/test/rails_app/app/controllers/admins/sessions_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Admins::SessionsController < Devise::SessionsController def new flash[:special] = "Welcome to #{controller_path.inspect} controller!" diff --git a/test/rails_app/app/controllers/admins_controller.rb b/test/rails_app/app/controllers/admins_controller.rb index 6b39be19e..c732f5890 100644 --- a/test/rails_app/app/controllers/admins_controller.rb +++ b/test/rails_app/app/controllers/admins_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class AdminsController < ApplicationController before_action :authenticate_admin! diff --git a/test/rails_app/app/controllers/application_controller.rb b/test/rails_app/app/controllers/application_controller.rb index 7adee128c..616845d76 100644 --- a/test/rails_app/app/controllers/application_controller.rb +++ b/test/rails_app/app/controllers/application_controller.rb @@ -1,11 +1,24 @@ +# frozen_string_literal: true + # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base protect_from_forgery + around_action :set_locale before_action :current_user, unless: :devise_controller? before_action :authenticate_user!, if: :devise_controller? respond_to(*Mime::SET.map(&:to_sym)) devise_group :commenter, contains: [:user, :admin] + + private + + def set_locale + I18n.with_locale(params[:locale] || I18n.default_locale) { yield } + end + + def default_url_options + {locale: params[:locale]}.compact + end end diff --git a/test/rails_app/app/controllers/application_with_fake_engine.rb b/test/rails_app/app/controllers/application_with_fake_engine.rb index c77d67f15..652bd2e00 100644 --- a/test/rails_app/app/controllers/application_with_fake_engine.rb +++ b/test/rails_app/app/controllers/application_with_fake_engine.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ApplicationWithFakeEngine < ApplicationController private diff --git a/test/rails_app/app/controllers/custom/registrations_controller.rb b/test/rails_app/app/controllers/custom/registrations_controller.rb index 3864661f2..dd0e7a2fa 100644 --- a/test/rails_app/app/controllers/custom/registrations_controller.rb +++ b/test/rails_app/app/controllers/custom/registrations_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Custom::RegistrationsController < Devise::RegistrationsController def new super do |resource| diff --git a/test/rails_app/app/controllers/home_controller.rb b/test/rails_app/app/controllers/home_controller.rb index e2a342302..b8f3327ad 100644 --- a/test/rails_app/app/controllers/home_controller.rb +++ b/test/rails_app/app/controllers/home_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class HomeController < ApplicationController def index end @@ -20,10 +22,6 @@ def set end def unauthenticated - if Devise::Test.rails5? - render body: "unauthenticated", status: :unauthorized - else - render text: "unauthenticated", status: :unauthorized - end + render body: "unauthenticated", status: :unauthorized end end diff --git a/test/rails_app/app/controllers/publisher/registrations_controller.rb b/test/rails_app/app/controllers/publisher/registrations_controller.rb index 7809a3638..f7bdaa08e 100644 --- a/test/rails_app/app/controllers/publisher/registrations_controller.rb +++ b/test/rails_app/app/controllers/publisher/registrations_controller.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + class Publisher::RegistrationsController < ApplicationController end diff --git a/test/rails_app/app/controllers/publisher/sessions_controller.rb b/test/rails_app/app/controllers/publisher/sessions_controller.rb index 2eed1bb0e..48ce6859d 100644 --- a/test/rails_app/app/controllers/publisher/sessions_controller.rb +++ b/test/rails_app/app/controllers/publisher/sessions_controller.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + class Publisher::SessionsController < ApplicationController end diff --git a/test/rails_app/app/controllers/streaming_controller.rb b/test/rails_app/app/controllers/streaming_controller.rb new file mode 100644 index 000000000..1045fea18 --- /dev/null +++ b/test/rails_app/app/controllers/streaming_controller.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +class StreamingController < ApplicationController + include ActionController::Live + + before_action :authenticate_user! + + def index + render body: 'Index' + end +end diff --git a/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb b/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb index 37cf9a8ae..f5327fbd7 100644 --- a/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb +++ b/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook data = request.respond_to?(:get_header) ? request.get_header("omniauth.auth") : request.env["omniauth.auth"] @@ -9,6 +11,6 @@ def sign_in_facebook user = User.to_adapter.find_first(email: 'user@test.com') user.remember_me = true sign_in user - render (Devise::Test.rails5? ? :body : :text) => "" + render body: "" end end diff --git a/test/rails_app/app/controllers/users_controller.rb b/test/rails_app/app/controllers/users_controller.rb index 1d2d74943..b3b49ee2a 100644 --- a/test/rails_app/app/controllers/users_controller.rb +++ b/test/rails_app/app/controllers/users_controller.rb @@ -1,7 +1,10 @@ +# frozen_string_literal: true + class UsersController < ApplicationController prepend_before_action :current_user, only: :exhibit before_action :authenticate_user!, except: [:accept, :exhibit] - respond_to :html, :xml + clear_respond_to + respond_to :html, :json def index user_session[:cart] = "Cart" @@ -13,7 +16,7 @@ def edit_form end def update_form - render (Devise::Test.rails5? ? :body : :text) => 'Update' + render body: 'Update' end def accept @@ -21,11 +24,11 @@ def accept end def exhibit - render (Devise::Test.rails5? ? :body : :text) => current_user ? "User is authenticated" : "User is not authenticated" + render body: current_user ? "User is authenticated" : "User is not authenticated" end def expire user_session['last_request_at'] = 31.minutes.ago.utc - render (Devise::Test.rails5? ? :body : :text) => 'User will be expired on next request' + render body: 'User will be expired on next request' end end diff --git a/test/rails_app/app/helpers/application_helper.rb b/test/rails_app/app/helpers/application_helper.rb index 22a7940eb..fc3fb393d 100644 --- a/test/rails_app/app/helpers/application_helper.rb +++ b/test/rails_app/app/helpers/application_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Methods added to this helper will be available to all templates in the application. module ApplicationHelper end diff --git a/test/rails_app/app/mailers/users/from_proc_mailer.rb b/test/rails_app/app/mailers/users/from_proc_mailer.rb index 1bff4cacc..e36951257 100644 --- a/test/rails_app/app/mailers/users/from_proc_mailer.rb +++ b/test/rails_app/app/mailers/users/from_proc_mailer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Users::FromProcMailer < Devise::Mailer default from: proc { 'custom@example.com' } end diff --git a/test/rails_app/app/mailers/users/mailer.rb b/test/rails_app/app/mailers/users/mailer.rb index 3342f75aa..5962e15da 100644 --- a/test/rails_app/app/mailers/users/mailer.rb +++ b/test/rails_app/app/mailers/users/mailer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Users::Mailer < Devise::Mailer default from: 'custom@example.com' end diff --git a/test/rails_app/app/mailers/users/reply_to_mailer.rb b/test/rails_app/app/mailers/users/reply_to_mailer.rb index 67ca82cff..4b241d32a 100644 --- a/test/rails_app/app/mailers/users/reply_to_mailer.rb +++ b/test/rails_app/app/mailers/users/reply_to_mailer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Users::ReplyToMailer < Devise::Mailer default from: 'custom@example.com' default reply_to: 'custom_reply_to@example.com' diff --git a/test/rails_app/app/mongoid/admin.rb b/test/rails_app/app/mongoid/admin.rb index d5884cb69..c41ea059d 100644 --- a/test/rails_app/app/mongoid/admin.rb +++ b/test/rails_app/app/mongoid/admin.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_admin' class Admin diff --git a/test/rails_app/app/mongoid/shim.rb b/test/rails_app/app/mongoid/shim.rb index cd48fd408..e5f35782f 100644 --- a/test/rails_app/app/mongoid/shim.rb +++ b/test/rails_app/app/mongoid/shim.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Shim extend ::ActiveSupport::Concern diff --git a/test/rails_app/app/mongoid/user.rb b/test/rails_app/app/mongoid/user.rb index 0a2e5ea1c..7e5b2b381 100644 --- a/test/rails_app/app/mongoid/user.rb +++ b/test/rails_app/app/mongoid/user.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_user' class User @@ -36,4 +38,13 @@ class User field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts field :unlock_token, type: String # Only if unlock strategy is :email or :both field :locked_at, type: Time + + cattr_accessor :validations_performed + + after_validation :after_validation_callback + + def after_validation_callback + # used to check in our test if the validations were called + @@validations_performed = true + end end diff --git a/test/rails_app/app/mongoid/user_on_engine.rb b/test/rails_app/app/mongoid/user_on_engine.rb index e68b096f6..f63b727bb 100644 --- a/test/rails_app/app/mongoid/user_on_engine.rb +++ b/test/rails_app/app/mongoid/user_on_engine.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_user_without_omniauth' class UserOnEngine diff --git a/test/rails_app/app/mongoid/user_on_main_app.rb b/test/rails_app/app/mongoid/user_on_main_app.rb index a35f2336a..92fea262b 100644 --- a/test/rails_app/app/mongoid/user_on_main_app.rb +++ b/test/rails_app/app/mongoid/user_on_main_app.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'shared_user_without_omniauth' class UserOnMainApp diff --git a/test/rails_app/app/mongoid/user_with_validations.rb b/test/rails_app/app/mongoid/user_with_validations.rb new file mode 100644 index 000000000..c1b73a306 --- /dev/null +++ b/test/rails_app/app/mongoid/user_with_validations.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +require "shared_user" + +class UserWithValidations + include Mongoid::Document + include Shim + include SharedUser + + field :username, type: String + field :facebook_token, type: String + + ## Database authenticatable + field :email, type: String, default: "" + field :encrypted_password, type: String, default: "" + + ## Recoverable + field :reset_password_token, type: String + field :reset_password_sent_at, type: Time + + ## Rememberable + field :remember_created_at, type: Time + + ## Trackable + field :sign_in_count, type: Integer, default: 0 + field :current_sign_in_at, type: Time + field :last_sign_in_at, type: Time + field :current_sign_in_ip, type: String + field :last_sign_in_ip, type: String + + ## Lockable + field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts + field :unlock_token, type: String # Only if unlock strategy is :email or :both + field :locked_at, type: Time + + validates :email, presence: true +end diff --git a/test/rails_app/app/mongoid/user_without_email.rb b/test/rails_app/app/mongoid/user_without_email.rb index f46ab6356..b82ea56ad 100644 --- a/test/rails_app/app/mongoid/user_without_email.rb +++ b/test/rails_app/app/mongoid/user_without_email.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "shared_user_without_email" class UserWithoutEmail diff --git a/test/rails_app/app/views/admins/sessions/new.html.erb b/test/rails_app/app/views/admins/sessions/new.html.erb index 75f3b860f..f3be6278e 100644 --- a/test/rails_app/app/views/admins/sessions/new.html.erb +++ b/test/rails_app/app/views/admins/sessions/new.html.erb @@ -1,2 +1,2 @@ Welcome to "sessions/new" view! -<%= render file: "devise/sessions/new" %> +<%= render template: "devise/sessions/new" %> diff --git a/test/rails_app/config/application.rb b/test/rails_app/config/application.rb index 34732d0a4..fc3b171d0 100644 --- a/test/rails_app/config/application.rb +++ b/test/rails_app/config/application.rb @@ -1,5 +1,8 @@ +# frozen_string_literal: true + require File.expand_path('../boot', __FILE__) +require "logger" require "action_controller/railtie" require "action_mailer/railtie" require "rails/test_unit/railtie" @@ -32,13 +35,19 @@ class Application < Rails::Application config.action_mailer.default_url_options = { host: "localhost", port: 3000 } - if DEVISE_ORM == :active_record && (Rails::VERSION::MAJOR >= 4 && Rails::VERSION::MINOR >= 2) - config.active_record.raise_in_transactional_callbacks = true - end - # This was used to break devise in some situations config.to_prepare do Devise::SessionsController.layout "application" end + + if DEVISE_ORM == :active_record + if Devise::Test.rails70? + config.active_record.legacy_connection_handling = false + end + end + + if Devise::Test.rails70_and_up? + config.active_support.cache_format_version = 7.0 + end end end diff --git a/test/rails_app/config/boot.rb b/test/rails_app/config/boot.rb index 60b907302..e328fce49 100644 --- a/test/rails_app/config/boot.rb +++ b/test/rails_app/config/boot.rb @@ -1,16 +1,23 @@ +# frozen_string_literal: true + unless defined?(DEVISE_ORM) DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym end module Devise module Test - # Detection for minor differences between Rails 4 and 5, and 5.1 in tests. - def self.rails51? - Rails.version.start_with? '5.1' + # Detection for minor differences between Rails versions in tests. + + def self.rails71_and_up? + !rails70? && Rails::VERSION::MAJOR >= 7 + end + + def self.rails70_and_up? + Rails::VERSION::MAJOR >= 7 end - def self.rails5? - Rails.version.start_with? '5' + def self.rails70? + Rails.version.start_with? '7.0' end end end diff --git a/test/rails_app/config/environment.rb b/test/rails_app/config/environment.rb index 1fe685fd9..1c7a3ec2c 100644 --- a/test/rails_app/config/environment.rb +++ b/test/rails_app/config/environment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Load the rails application. require File.expand_path('../application', __FILE__) diff --git a/test/rails_app/config/environments/development.rb b/test/rails_app/config/environments/development.rb index fcddb5f58..d23c88d15 100644 --- a/test/rails_app/config/environments/development.rb +++ b/test/rails_app/config/environments/development.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RailsApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. diff --git a/test/rails_app/config/environments/production.rb b/test/rails_app/config/environments/production.rb index bb2d0504d..17c5b266f 100644 --- a/test/rails_app/config/environments/production.rb +++ b/test/rails_app/config/environments/production.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RailsApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. @@ -20,13 +22,7 @@ # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). - if Rails.version >= "5.0.0" - config.public_file_server.enabled = false - elsif Rails.version >= "4.2.0" - config.serve_static_files = false - else - config.serve_static_assets = false - end + config.public_file_server.enabled = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier diff --git a/test/rails_app/config/environments/test.rb b/test/rails_app/config/environments/test.rb index 147329738..acc06f31f 100644 --- a/test/rails_app/config/environments/test.rb +++ b/test/rails_app/config/environments/test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + RailsApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb. @@ -14,23 +16,19 @@ # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. - if Rails.version >= "5.0.0" - config.public_file_server.enabled = true - config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'} - elsif Rails.version >= "4.2.0" - config.serve_static_files = true - config.static_cache_control = "public, max-age=3600" - else - config.serve_static_assets = true - config.static_cache_control = "public, max-age=3600" - end + config.public_file_server.enabled = true + config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'} # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. - config.action_dispatch.show_exceptions = false + if Devise::Test.rails71_and_up? + config.action_dispatch.show_exceptions = :none + else + config.action_dispatch.show_exceptions = false + end # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false diff --git a/test/rails_app/config/initializers/backtrace_silencers.rb b/test/rails_app/config/initializers/backtrace_silencers.rb index 56ddc8da8..9edabe936 100644 --- a/test/rails_app/config/initializers/backtrace_silencers.rb +++ b/test/rails_app/config/initializers/backtrace_silencers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. diff --git a/test/rails_app/config/initializers/devise.rb b/test/rails_app/config/initializers/devise.rb index d79e71f57..85fdfe0ae 100644 --- a/test/rails_app/config/initializers/devise.rb +++ b/test/rails_app/config/initializers/devise.rb @@ -1,6 +1,14 @@ +# frozen_string_literal: true + require "omniauth-facebook" require "omniauth-openid" +# Assuming you have not yet modified this file, each configuration option below +# is set to its default value. Note that some are commented out while others +# are not: uncommented lines are intended to protect your configuration from +# breaking changes in upgrades (i.e., in the event that future versions of +# Devise change the default values for those options). +# # Use this hook to configure devise mailer, warden hooks and so forth. The first # four configuration values can also be set straight in your models. Devise.setup do |config| @@ -173,8 +181,19 @@ # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # - # config.warden do |manager| - # manager.failure_app = AnotherApp - # manager.default_strategies(scope: :user).unshift :some_external_strategy + # config.warden do |warden_config| + # warden_config.failure_app = AnotherApp + # warden_config.default_strategies(scope: :user).unshift :some_external_strategy # end + + # ==> Configuration for :registerable + + # When set to false, does not sign a user in automatically after their password is + # changed. Defaults to true, so a user is signed in automatically after changing a password. + # config.sign_in_after_change_password = true + + ActiveSupport.on_load(:devise_failure_app) do + require "lazy_load_test_module" + include LazyLoadTestModule + end end diff --git a/test/rails_app/config/initializers/inflections.rb b/test/rails_app/config/initializers/inflections.rb index 45fc8f45a..7bb3dc01f 100644 --- a/test/rails_app/config/initializers/inflections.rb +++ b/test/rails_app/config/initializers/inflections.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + ActiveSupport::Inflector.inflections do |inflect| end diff --git a/test/rails_app/config/initializers/secret_token.rb b/test/rails_app/config/initializers/secret_token.rb index 35818fa16..48d1b70a5 100644 --- a/test/rails_app/config/initializers/secret_token.rb +++ b/test/rails_app/config/initializers/secret_token.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + config = Rails.application.config config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10' diff --git a/test/rails_app/config/initializers/session_store.rb b/test/rails_app/config/initializers/session_store.rb index 5ac94e7e5..5cfac4ec5 100644 --- a/test/rails_app/config/initializers/session_store.rb +++ b/test/rails_app/config/initializers/session_store.rb @@ -1 +1,3 @@ +# frozen_string_literal: true + RailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session' diff --git a/test/rails_app/config/routes.rb b/test/rails_app/config/routes.rb index fb33154f0..0b748f3fd 100644 --- a/test/rails_app/config/routes.rb +++ b/test/rails_app/config/routes.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Rails.application.routes.draw do # Resources for testing resources :users, only: [:index] do @@ -15,6 +17,8 @@ resources :admins, only: [:index] + resources :streaming, only: [:index] + # Users scope devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" } diff --git a/test/rails_app/db/migrate/20100401102949_create_tables.rb b/test/rails_app/db/migrate/20100401102949_create_tables.rb index 4eecbc2cd..8d46b3e5c 100644 --- a/test/rails_app/db/migrate/20100401102949_create_tables.rb +++ b/test/rails_app/db/migrate/20100401102949_create_tables.rb @@ -1,8 +1,6 @@ -superclass = ActiveRecord::Migration -# TODO: Inherit from the 5.0 Migration class directly when we drop support for Rails 4. -superclass = ActiveRecord::Migration[5.0] if superclass.respond_to?(:[]) +# frozen_string_literal: true -class CreateTables < superclass +class CreateTables < ActiveRecord::Migration[5.0] def self.up create_table :users do |t| t.string :username diff --git a/test/rails_app/db/schema.rb b/test/rails_app/db/schema.rb index a7446056c..c435f6b96 100644 --- a/test/rails_app/db/schema.rb +++ b/test/rails_app/db/schema.rb @@ -1,4 +1,6 @@ # encoding: UTF-8 +# frozen_string_literal: true + # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. diff --git a/test/rails_app/lib/lazy_load_test_module.rb b/test/rails_app/lib/lazy_load_test_module.rb new file mode 100644 index 000000000..15b0a03c4 --- /dev/null +++ b/test/rails_app/lib/lazy_load_test_module.rb @@ -0,0 +1,5 @@ +module LazyLoadTestModule + def lazy_loading_works? + "yes it does" + end +end \ No newline at end of file diff --git a/test/rails_app/lib/shared_admin.rb b/test/rails_app/lib/shared_admin.rb index 7d6227a3c..374666ff5 100644 --- a/test/rails_app/lib/shared_admin.rb +++ b/test/rails_app/lib/shared_admin.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module SharedAdmin extend ActiveSupport::Concern @@ -8,11 +10,7 @@ module SharedAdmin allow_unconfirmed_access_for: 2.weeks, reconfirmable: true validates_length_of :reset_password_token, minimum: 3, allow_blank: true - if Devise::Test.rails51? - validates_uniqueness_of :email, allow_blank: true, if: :will_save_change_to_email? - else - validates_uniqueness_of :email, allow_blank: true, if: :email_changed? - end + validates_uniqueness_of :email, allow_blank: true, if: :devise_will_save_change_to_email? end def raw_confirmation_token diff --git a/test/rails_app/lib/shared_user.rb b/test/rails_app/lib/shared_user.rb index c3b023a42..e037fe867 100644 --- a/test/rails_app/lib/shared_user.rb +++ b/test/rails_app/lib/shared_user.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module SharedUser extend ActiveSupport::Concern diff --git a/test/rails_app/lib/shared_user_without_email.rb b/test/rails_app/lib/shared_user_without_email.rb index cc0a4045b..5a86729ff 100644 --- a/test/rails_app/lib/shared_user_without_email.rb +++ b/test/rails_app/lib/shared_user_without_email.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module SharedUserWithoutEmail extend ActiveSupport::Concern @@ -19,7 +21,7 @@ def email_changed? raise NoMethodError end - def respond_to?(method_name, include_all=false) + def respond_to?(method_name, include_all = false) return false if method_name.to_sym == :email_changed? super(method_name, include_all) end diff --git a/test/rails_app/lib/shared_user_without_omniauth.rb b/test/rails_app/lib/shared_user_without_omniauth.rb index 7f0396c0a..7b9ae08fd 100644 --- a/test/rails_app/lib/shared_user_without_omniauth.rb +++ b/test/rails_app/lib/shared_user_without_omniauth.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module SharedUserWithoutOmniauth extend ActiveSupport::Concern diff --git a/test/rails_test.rb b/test/rails_test.rb index 65cba2ebf..64ff82cda 100644 --- a/test/rails_test.rb +++ b/test/rails_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class RailsTest < ActiveSupport::TestCase @@ -6,4 +8,10 @@ class RailsTest < ActiveSupport::TestCase assert_equal :load_config_initializers, initializer.after assert_equal :build_middleware_stack, initializer.before end + + if Devise::Test.rails71_and_up? + test 'deprecator is added to application deprecators' do + assert_not_nil Rails.application.deprecators[:devise] + end + end end diff --git a/test/routes_test.rb b/test/routes_test.rb index 84229f254..20ba31172 100644 --- a/test/routes_test.rb +++ b/test/routes_test.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'test_helper' -ExpectedRoutingError = MiniTest::Assertion +ExpectedRoutingError = Minitest::Assertion class DefaultRoutingTest < ActionController::TestCase test 'map new user session' do @@ -203,56 +205,51 @@ class CustomizedRoutingTest < ActionController::TestCase test 'map with format false for sessions' do expected_params = {controller: 'devise/sessions', action: 'new'} - expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in', method: :get}) assert_raise ExpectedRoutingError do - assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in.xml', method: :get}) + assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in.json', method: :get}) end end test 'map with format false for passwords' do expected_params = {controller: 'devise/passwords', action: 'create'} - expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_admin/password', method: :post}) assert_raise ExpectedRoutingError do - assert_recognizes(expected_params, {path: '/htmlonly_admin/password.xml', method: :post}) + assert_recognizes(expected_params, {path: '/htmlonly_admin/password.json', method: :post}) end end test 'map with format false for registrations' do expected_params = {controller: 'devise/registrations', action: 'new'} - expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up', method: :get}) assert_raise ExpectedRoutingError do - assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up.xml', method: :get}) + assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up.json', method: :get}) end end test 'map with format false for confirmations' do expected_params = {controller: 'devise/confirmations', action: 'show'} - expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation', method: :get}) assert_raise ExpectedRoutingError do - assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation.xml', method: :get}) + assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation.json', method: :get}) end end test 'map with format false for unlocks' do expected_params = {controller: 'devise/unlocks', action: 'show'} - expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_users/unlock', method: :get}) assert_raise ExpectedRoutingError do - assert_recognizes(expected_params, {path: '/htmlonly_users/unlock.xml', method: :get}) + assert_recognizes(expected_params, {path: '/htmlonly_users/unlock.json', method: :get}) end end test 'map with format false is not permanent' do - assert_equal "/set.xml", @routes.url_helpers.set_path(:xml) + assert_equal "/set.json", @routes.url_helpers.set_path(:json) end test 'checks if mapping has proper configuration for omniauth callback' do diff --git a/test/support/action_controller/record_identifier.rb b/test/support/action_controller/record_identifier.rb index 89b3483ed..3d6c61e8b 100644 --- a/test/support/action_controller/record_identifier.rb +++ b/test/support/action_controller/record_identifier.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Since webrat uses ActionController::RecordIdentifier class that was moved to # ActionView namespace in Rails 4.1+ diff --git a/test/support/assertions.rb b/test/support/assertions.rb index 7ec8b3234..9872a0ae4 100644 --- a/test/support/assertions.rb +++ b/test/support/assertions.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'active_support/test_case' class ActiveSupport::TestCase diff --git a/test/support/helpers.rb b/test/support/helpers.rb index ab77b91f6..01dc6aa56 100644 --- a/test/support/helpers.rb +++ b/test/support/helpers.rb @@ -1,8 +1,8 @@ +# frozen_string_literal: true + require 'active_support/test_case' class ActiveSupport::TestCase - VALID_AUTHENTICATION_TOKEN = 'AbCdEfGhIjKlMnOpQrSt'.freeze - def setup_mailer ActionMailer::Base.deliveries = [] end @@ -25,31 +25,35 @@ def generate_unique_email "test#{@@email_count}@example.com" end - def valid_attributes(attributes={}) + def valid_attributes(attributes = {}) { username: "usertest", email: generate_unique_email, password: '12345678', password_confirmation: '12345678' }.update(attributes) end - def new_user(attributes={}) + def new_user(attributes = {}) User.new(valid_attributes(attributes)) end - def create_user(attributes={}) + def create_user(attributes = {}) User.create!(valid_attributes(attributes)) end - def create_admin(attributes={}) + def create_admin(attributes = {}) valid_attributes = valid_attributes(attributes) valid_attributes.delete(:username) Admin.create!(valid_attributes) end - def create_user_without_email(attributes={}) + def create_user_without_email(attributes = {}) UserWithoutEmail.create!(valid_attributes(attributes)) end + def create_user_with_validations(attributes = {}) + UserWithValidations.create!(valid_attributes(attributes)) + end + # Execute the block setting the given values and restoring old values after # the block is executed. def swap(object, new_values) @@ -67,6 +71,17 @@ def swap(object, new_values) end end + def swap_model_config(model, new_values) + new_values.each do |key, value| + model.send :"#{key}=", value + end + yield + ensure + new_values.each_key do |key| + model.remove_instance_variable :"@#{key}" + end + end + def clear_cached_variables(options) if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys) Devise.mappings.each do |_, mapping| diff --git a/test/support/http_method_compatibility.rb b/test/support/http_method_compatibility.rb index 7b8fdf085..44d80dffd 100644 --- a/test/support/http_method_compatibility.rb +++ b/test/support/http_method_compatibility.rb @@ -1,51 +1,9 @@ +# frozen_string_literal: true + module Devise class IntegrationTest < ActionDispatch::IntegrationTest - # %w( get post patch put head delete xml_http_request - # xhr get_via_redirect post_via_redirect - # ).each do |method| - %w( get post put ).each do |method| - if Rails.version >= '5.0.0' - define_method(method) do |url, options={}| - if options.empty? - super url - else - super url, options - end - end - else - define_method(method) do |url, options={}| - if options[:xhr]==true - xml_http_request __method__, url, options[:params] || {}, options[:headers] - else - super url, options[:params] || {}, options[:headers] - end - end - end - end end class ControllerTestCase < ActionController::TestCase - # %w( get post patch put head delete xml_http_request - # xhr get_via_redirect post_via_redirect - # ).each do |method| - %w( get post put ).each do |method| - if Rails.version >= '5.0.0' - define_method(method) do |action, options={}| - if options.empty? - super action - else - super action, options - end - end - else - define_method(method) do |action, options={}| - if options[:xhr]==true - xml_http_request __method__, action, options[:params] || {}, options[:headers] - else - super action, options[:params] || {}, options[:headers] - end - end - end - end end end diff --git a/test/support/integration.rb b/test/support/integration.rb index ac140e86d..3ed0d85aa 100644 --- a/test/support/integration.rb +++ b/test/support/integration.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'action_dispatch/testing/integration' class ActionDispatch::IntegrationTest @@ -5,7 +7,7 @@ def warden request.env['warden'] end - def create_user(options={}) + def create_user(options = {}) @user ||= begin user = User.create!( username: 'usertest', @@ -17,11 +19,12 @@ def create_user(options={}) user.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at] user.confirm unless options[:confirm] == false user.lock_access! if options[:locked] == true + User.validations_performed = false user end end - def create_admin(options={}) + def create_admin(options = {}) @admin ||= begin admin = Admin.create!( email: options[:email] || 'admin@test.com', @@ -33,7 +36,7 @@ def create_admin(options={}) end end - def sign_in_as_user(options={}, &block) + def sign_in_as_user(options = {}, &block) user = create_user(options) visit_with_option options[:visit], new_user_session_path fill_in 'email', with: options[:email] || 'user@test.com' @@ -44,7 +47,7 @@ def sign_in_as_user(options={}, &block) user end - def sign_in_as_admin(options={}, &block) + def sign_in_as_admin(options = {}, &block) admin = create_admin(options) visit_with_option options[:visit], new_admin_session_path fill_in 'email', with: 'admin@test.com' @@ -58,8 +61,8 @@ def sign_in_as_admin(options={}, &block) # account Middleware redirects. # def assert_redirected_to(url) - assert [301, 302].include?(@integration_session.status), - "Expected status to be 301 or 302, got #{@integration_session.status}" + assert_includes [301, 302, 303], @integration_session.status, + "Expected status to be 301, 302, or 303, got #{@integration_session.status}" assert_url url, @integration_session.headers["Location"] end diff --git a/test/support/locale/de.yml b/test/support/locale/de.yml new file mode 100644 index 000000000..b60457162 --- /dev/null +++ b/test/support/locale/de.yml @@ -0,0 +1,12 @@ +de: + activerecord: + attributes: + user: + email: E-Mail + mongoid: + attributes: + user: + email: E-Mail + devise: + failure: + invalid: "%{authentication_keys} oder Passwort ist ungültig." diff --git a/test/support/locale/pt-BR.yml b/test/support/locale/pt-BR.yml new file mode 100644 index 000000000..687cc87ae --- /dev/null +++ b/test/support/locale/pt-BR.yml @@ -0,0 +1,7 @@ +pt-BR: + devise: + failure: + invalid: "%{authentication_keys} ou senha inválidos." + unauthenticated: "Para continuar, faça login ou registre-se." + timeout: "Sua sessão expirou. Por favor faça o login novamente para continuar." + unconfirmed: "Você precisa confirmar seu email para continuar." diff --git a/test/support/mongoid.yml b/test/support/mongoid.yml index cfd0124e2..d55de9250 100644 --- a/test/support/mongoid.yml +++ b/test/support/mongoid.yml @@ -1,5 +1,5 @@ test: - <%= Mongoid::VERSION.to_i > 4 ? 'clients' : 'sessions' %>: + clients: default: database: devise-test-suite hosts: diff --git a/test/support/webrat/integrations/rails.rb b/test/support/webrat/integrations/rails.rb index 6f4aedcf2..a78d04e66 100644 --- a/test/support/webrat/integrations/rails.rb +++ b/test/support/webrat/integrations/rails.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'webrat/core/elements/form' require 'action_dispatch/testing/integration' @@ -16,6 +18,12 @@ def logger # :nodoc: end class RailsAdapter + # This method is private within webrat gem and after Ruby 2.4 we get a lot of warnings because + # Webrat::Session#response is delegated to this method. + def response + integration_session.response + end + protected def do_request(http_method, url, data, headers) diff --git a/test/support/webrat/matchers.rb b/test/support/webrat/matchers.rb new file mode 100644 index 000000000..24d71df3d --- /dev/null +++ b/test/support/webrat/matchers.rb @@ -0,0 +1,16 @@ +# Monkey patch for Nokogiri changes - https://github.com/sparklemotion/nokogiri/issues/2469 +module Webrat + module Matchers + class HaveSelector + def query + Nokogiri::CSS::Parser.new.parse(@expected.to_s).map do |ast| + if ::Gem::Version.new(Nokogiri::VERSION) < ::Gem::Version.new('1.17.2') + ast.to_xpath('//', Nokogiri::CSS::XPathVisitor.new) + else + ast.to_xpath(Nokogiri::CSS::XPathVisitor.new) + end + end.first + end + end + end +end diff --git a/test/test/controller_helpers_test.rb b/test/test/controller_helpers_test.rb index e94ce309e..a158e8753 100644 --- a/test/test/controller_helpers_test.rb +++ b/test/test/controller_helpers_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class TestControllerHelpersTest < Devise::ControllerTestCase @@ -13,7 +15,7 @@ class TestControllerHelpersTest < Devise::ControllerTestCase test "redirects if attempting to access a page with an unconfirmed account" do swap Devise, allow_unconfirmed_access_for: 0.days do user = create_user - assert !user.active_for_authentication? + assert_not user.active_for_authentication? sign_in user get :index @@ -24,7 +26,7 @@ class TestControllerHelpersTest < Devise::ControllerTestCase test "returns nil if accessing current_user with an unconfirmed account" do swap Devise, allow_unconfirmed_access_for: 0.days do user = create_user - assert !user.active_for_authentication? + assert_not user.active_for_authentication? sign_in user get :accept, params: { id: user } @@ -95,11 +97,22 @@ def respond test "returns the body of a failure app" do get :index - assert_equal response.body, "You are being redirected." + + if Devise::Test.rails71_and_up? + assert_empty response.body + else + assert_equal "You are being redirected.", response.body + end + end + + test "returns the content type of a failure app" do + get :index, params: { format: :json } + + assert_includes response.media_type, 'application/json' end test "defined Warden after_authentication callback should not be called when sign_in is called" do - begin + assert_nothing_raised do Warden::Manager.after_authentication do |user, auth, opts| flunk "callback was called while it should not" end @@ -113,7 +126,7 @@ def respond end test "defined Warden before_logout callback should not be called when sign_out is called" do - begin + assert_nothing_raised do Warden::Manager.before_logout do |user, auth, opts| flunk "callback was called while it should not" end @@ -164,13 +177,7 @@ def respond test "creates a new warden proxy if the request object has changed" do old_warden_proxy = warden - @request = if Devise::Test.rails51? - ActionController::TestRequest.create(Class.new) # needs a "controller class" - elsif Devise::Test.rails5? - ActionController::TestRequest.create - else - ActionController::TestRequest.new - end + @request = ActionController::TestRequest.create(Class.new) # needs a "controller class" new_warden_proxy = warden @@ -184,3 +191,18 @@ def respond assert_equal old_warden_proxy, new_warden_proxy end end + +class TestControllerHelpersForStreamingControllerTest < Devise::ControllerTestCase + tests StreamingController + include Devise::Test::ControllerHelpers + + test "doesn't hang when sending an authentication error response body" do + get :index + + if Devise::Test.rails71_and_up? + assert_empty response.body + else + assert_equal "You are being redirected.", response.body + end + end +end diff --git a/test/test/integration_helpers_test.rb b/test/test/integration_helpers_test.rb index 5f7dfd31b..7f579a8da 100644 --- a/test/test/integration_helpers_test.rb +++ b/test/test/integration_helpers_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class TestIntegrationsHelpersTest < Devise::IntegrationTest @@ -16,7 +18,7 @@ class TestIntegrationsHelpersTest < Devise::IntegrationTest sign_out user visit '/' - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) end test '#sign_out does not signs out other scopes' do @@ -26,7 +28,7 @@ class TestIntegrationsHelpersTest < Devise::IntegrationTest visit '/' - refute warden.authenticated?(:user) + assert_not warden.authenticated?(:user) assert warden.authenticated?(:admin) end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 9f36b4882..e6df81203 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + ENV["RAILS_ENV"] = "test" DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym @@ -8,9 +10,10 @@ require "rails/test_help" require "orm/#{DEVISE_ORM}" -I18n.load_path << File.expand_path("../support/locale/en.yml", __FILE__) +I18n.load_path.concat Dir["#{File.dirname(__FILE__)}/support/locale/*.yml"] -require 'mocha/setup' +require 'mocha/minitest' +require 'timecop' require 'webrat' Webrat.configure do |config| config.mode = :rails diff --git a/test/test_models.rb b/test/test_models.rb index d65648d90..0e52bef43 100644 --- a/test/test_models.rb +++ b/test/test_models.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Configurable < User devise :database_authenticatable, :confirmable, :rememberable, :timeoutable, :lockable, stretches: 15, pepper: 'abcdef', allow_unconfirmed_access_for: 5.days,