diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..75ad21eca9 --- /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/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..5ace4600a1 --- /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 0000000000..6881eda89a --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,63 @@ +name: Test +on: [push, pull_request] +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 0ff7742714..ac2a95781c 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 97c4ae8352..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -script: "bundle exec rake test" -rvm: - - 1.8.7 - - 1.9.2 - - 1.9.3 - - ree -gemfile: - - gemfiles/Gemfile.rails-3.1.x - - Gemfile -notifications: - recipients: - - jose.valim@plataformatec.com.br - - carlos@plataformatec.com.br - - rodrigo.flores@plataformatec.com.br - - rafael.franca@plataformatec.com.br diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000000..55bb0d4b55 --- /dev/null +++ b/.yardopts @@ -0,0 +1,9 @@ +--protected +--no-private +--embed-mixin ClassMethods +- +README.md +CHANGELOG.rdoc +CONTRIBUTING.md +MIT-LICENSE + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..38b434e193 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,66 @@ +### 5.0.0 - 2026-01-23 + +no changes + +### 5.0.0.rc - 2025-12-31 + +* 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. + + This is potentially a breaking change because Devise previously used the following order to find a secret key: + + ``` + app.credentials.secret_key_base > app.secrets.secret_key_base > application.config.secret_key_base > application.secret_key_base + ``` + + 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). + + 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 + * 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). + + 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 + + ``` + validates_length_of :password, within: password_length, allow_blank: true` + ``` + + to + + ``` + 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) + + +Please check [4-stable](https://github.com/heartcombo/devise/blob/4-stable/CHANGELOG.md) +for previous changes. diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc deleted file mode 100644 index c827b4cd39..0000000000 --- a/CHANGELOG.rdoc +++ /dev/null @@ -1,876 +0,0 @@ -* enhancement - * Default minimum password length is now 8 (by @carlosgaldino). - * Confirmable now has a confirm_within option to set a period while the confirmation token is still valid (by @promisedlandt) - -* bug fix - * Fix a regression introduced on warden 1.2.1 (by @ejfinneran) - * Properly camelize omniauth strategies (by @saizai) - * Do not set flash messages for non navigational requests on session sign out (by @mathieul) - * Set the proper fields as required on the lockable module (by @nickhoffman) - * Respects Devise mailer default's reply_to (by @mrchrisadams) - -== 2.1.2 - -* enhancements - * Handle backwards incompatibility between Rails 3.2.6 and Thor 0.15.x - -* bug fix - * Fix regression on strategy validation on previous release - -== 2.1.1 (yanked) - -* enhancements - * `sign_out_all_scopes` now locks warden and does not allow new logins in the same action - * `Devise.omniauth_path_prefix` is available to configure omniauth path prefix - * Redirect to sign in page when trying to access password#edit without a token (by @gbataille) - * Allow a lambda in authenticate(d) routes helpers to further select the scope - * Removed warnings on Rails 3.2.6 (by @nashby) - -* bug fix - * `update_with_password` now relies on assign_attributes and forwards the :as option (by @wtn) - * Do not trigger timeout on sign in related actions - * Timeout does not explode when reset_authentication_token! is accidentally defined by Active Model (by @remomueller) - -* deprecations - * Strategy#validate() no longer validates nil resources - -== 2.1.0 - -* enhancements - * Add `check_fields!(model_class)` method on Devise::Models to check if the model includes the fields that Devise uses - * Add `skip_reconfirmation!` to skip reconfirmation - * Devise model generator now works with engines - * Devise encryptable was moved to its new gem (http://github.com/plataformatec/devise-encryptable) - -* deprecations - * Deprecations warnings added on Devise 2.0 are now removed with their features - * All devise modules should now have a `required_fields(klass)` module method to help gathering missing attributes - * `use_salt_as_remember_token` and `apply_schema` does not have any effect since 2.0 and are now deprecated - * `valid_for_authentication?` must now return a boolean - -* bug fix - * Ensure after sign in hook is not called without a resource - * Fix a term: now on Omniauth related flash messages, we say that we're authenticating from an omniauth provider instead of authorizing - * Fixed redirect when authenticated mounted apps (by @hakanensari) - * Ensure the failure app still respects config.relative_url_root - * `/users/sign_in` doesn't choke on protected attributes used to select sign in scope (by @Paymium) - * `failed_attempts` is set to zero after any sign in (including via reset password) (by @rodrigoflores) - * Added token expiration on timeout (by @antiarchitect) - * Do not accidentally mark `_prefixes` as private - * Better support for custom strategies on test helpers (by @mattconnolly) - * Return `head :no_content` in SessionsController now that most JS libraries handle it (by @julianvargasalvarez) - -== 2.0.4 - -Notes: https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.0 - -* bug fix - * Fix when :host is used with devise_for (by @mreinsch) - * Fix a regression that caused Warden to be initialized too late - -== 2.0.3 (yanked) - -* bug fix - * Ensure warning is not shown by mistake on apps with mounted engines - * Fixes related to remember_token and rememberable_options - * Ensure serializable_hash does not depend on accessible attributes - * Ensure that timeout callback does not run on sign out action - -== 2.0.2 - -* enhancements - * Add devise_i18n_options to customize I18n message - -* bug fix - * Ensure Devise.available_router_name defaults to :main_app - * Set autocomplete to off for password on edit forms - * Better error messages in case a trackable model can't be saved - * Show a warning in case someone gives a pluralized name to devise generator - * Fix test behavior for rspec subject requests (by @sj26) - -== 2.0.1 - -* enhancements - * Improved error messages on deprecation warnings - * Hide Devise's internal generators from `rails g` command - -* bug fix - * Removed tmp and log files from gem - -== 2.0.0 - -* enhancements - * Add support for e-mail reconfirmation on change (by @Mandaryn and @heimidal) - * Redirect users to sign in page after unlock (by @nashby) - * Redirect to the previous URL on timeout - * Inherit from the same Devise parent controller (by @sj26) - * Allow parent_controller to be customizable via Devise.parent_controller, useful for engines - * Allow router_name to be customizable via Devise.router_name, useful for engines - * Allow alternate ORMs to run compatibility setup code before Authenticatable is included (by @jm81) - -* deprecation - * Devise now only supports Rails 3.1 forward - * Devise.confirm_within was deprecated in favor Devise.allow_unconfirmed_access_for - * Devise.stateless_token= is deprecated in favor of appending :token_auth to Devise.skip_session_storage - * Usage of Devise.apply_schema is deprecated - * Usage of Devise migration helpers are deprecated - * Usage of Devise.remember_across_browsers was deprecated - * Usage of rememberable with remember_token was removed - * Usage of recoverable without reset_password_sent_at was removed - * Usage of Devise.case_insensitive_keys equals to false was removed - * Move devise/shared/_links.erb to devise/_links.erb - * Deprecated support of nested devise_for blocks - * Deprecated support to devise.registrations.reasons and devise.registrations.inactive_signed_up in favor of devise.registrations.signed_up_but_* - * Protected method render_with_scope was removed. - -== 1.5.3 - -* bug fix - * Ensure delegator converts scope to symbol (by @dmitriy-kiriyenko) - * Ensure passing :format => false to devise_for is not permanent - * Ensure path checker does not check invalid routes - -== 1.5.2 - -* enhancements - * Add support for Rails 3.1 new mass assignment conventions (by @kirs) - * Add timeout_in method to Timeoutable, it can be overridden in a model (by @lest) - -* bug fix - * OmniAuth error message now shows the proper option (:strategy_class instead of :klass) - -== 1.5.1 - -* bug fix - * Devise should not attempt to load OmniAuth strategies. Strategies should be loaded before hand by the developer or explicitly given to Devise. - -== 1.5.0 - -* enhancements - * Timeoutable also skips tracking if skip_trackable is given - * devise_for now accepts :failure_app as an option - * Models can select the proper mailer via devise_mailer method (by @locomotivecms) - * Migration generator now uses the change method (by @nashby) - * Support to markerb templates on the mailer generator (by @sbounmy) - * Support for Omniauth 1.0 (older versions are no longer supported) (by @TamiasSibiricus) - -* bug fix - * Allow idempotent API requests - * Fix bug where logs did not show 401 as status code - * Change paranoid settings to behave as success instead of as failure - * Fix bug where activation messages were shown first than the credentials error message - * Instance variables are expired after sign out - -* deprecation - * redirect_location is deprecated, please use after_sign_in_path_for - * after_sign_in_path_for now redirects to session[scope_return_to] if any value is stored in it - -== 1.4.9 - -* bug fix - * url helpers were not being set under some circumstances - -== 1.4.8 - -* enhancements - * Add docs for assets pipeline and Heroku - -* bug fix - * confirmation_url was not being set under some circumstances - -== 1.4.7 - -* bug fix - * Fix backward incompatible change from 1.4.6 for those using custom controllers - -== 1.4.6 (yanked) - -* enhancements - * Allow devise_for :skip => :all - * Allow options to be passed to authenticate_user! - * Allow --skip-routes to devise generator - * Add allow_params_authentication! to make it explicit when params authentication is allowed in a controller - -== 1.4.5 - -* bug fix - * Failure app tries the root path if a session one does not exist - * No need to finalize Devise helpers all the time (by @bradleypriest) - * Reset password shows proper message if user is not active - * `clean_up_passwords` sets the accessors to nil to skip validations - -== 1.4.4 - -* bug fix - * Do not always skip helpers, instead provide :skip_helpers as option to trigger it manually - -== 1.4.3 - -* enhancements - * Improve Rails 3.1 compatibility - * Use serialize_into_session and serialize_from_session in Warden serialize to improve extensibility - -* bug fix - * Generator properly generates a change_table migration if a model already exists - * Properly deprecate setup_mail - * Fix encoding issues with email regexp - * Only generate helpers for the used mappings - * Wrap :action constraints in the proper hash - -* deprecations - * Loosened the used email regexp to simply assert the existent of "@". If someone relies on a more strict regexp, they may use https://github.com/SixArm/sixarm_ruby_email_address_validation - -== 1.4.2 - -* bug fix - * Provide a more robust behavior to serializers and add :force_except option - -== 1.4.1 - -* enhancements - * Add :defaults and :format support on router - * Add simple form generators - * Better localization for devise_error_messages! (by @zedtux) - -* bug fix - * Ensure to_xml is properly white listened - * Ensure handle_unverified_request clean up any cached signed-in user - -== 1.4.0 - -* enhancements - * Added authenticated and unauthenticated to the router to route the used based on his status (by @sj26) - * Improve e-mail regexp (by @rodrigoflores) - * Add strip_whitespace_keys and default to e-mail (by @swrobel) - * Do not run format and uniqueness validations on e-mail if it hasn't changed (by @Thibaut) - * Added update_without_password to update models but not allowing the password to change (by @fschwahn) - * Added config.paranoid, check the generator for more information (by @rodrigoflores) - -* bug fix - * password_required? should not affect length validation - * User cannot access sign up and similar pages if he is already signed in through a cookie or token - * Do not convert booleans to strings on finders (by @xavier) - * Run validations even if current_password fails (by @crx) - * Devise now honors routes constraints (by @macmartine) - * Do not return the user resource when requesting instructions (by @rodrigoflores) - -== 1.3.4 - -* bug fix - * Do not add formats if html or "*/*" - -== 1.3.3 - -* bug fix - * Explicitly mark the token as expired if so - -== 1.3.2 - -* bug fix - * Fix another regression related to reset_password_sent_at (by @alexdreher) - -== 1.3.1 - -* enhancements - * Improve failure_app responses (by @indirect) - * sessions/new and registrations/new also respond to xml and json now - -* bug fix - * Fix a regression that occurred if reset_password_sent_at is not present (by @stevehodgkiss) - -== 1.3.0 - -* enhancements - * All controllers can now handle different mime types than html using Responders (by @sikachu) - * Added reset_password_within as configuration option to send the token for recovery (by @jdguyot) - * Bump password length to 128 characters (by @k33l0r) - * Add :only as option to devise_for (by @timoschilling) - * Allow to override path after sending password instructions (by @irohiroki) - * require_no_authentication has its own flash message (by @jackdempsey) - -* bug fix - * Fix a bug where configuration options were being included too late - * Ensure Devise::TestHelpers can be used to tests Devise internal controllers (by @jwilger) - * valid_password? should not choke on empty passwords (by @mikel) - * Calling devise more than once does not include previously added modules anymore - * downcase_keys before validation - -* backward incompatible changes - * authentication_keys are no longer considered when creating the e-mail validations, the previous behavior was buggy. You must double check if you were relying on such behavior. - -== 1.2.1 - -* enhancements - * Improve update path messages - -== 1.2.0 - -* bug fix - * Properly ignore path prefix on omniauthable - * Faster uniqueness queries - * Rename active? to active_for_authentication? to avoid conflicts - -== 1.2.rc2 - -* enhancements - * Make friendly_token 20 chars long - * Use secure_compare - -* bug fix - * Fix an issue causing infinite redirects in production - * rails g destroy works properly with devise generators (by @andmej) - * before_failure callbacks should work on test helpers (by @twinge) - * rememberable cookie now is httponly by default (by @JamesFerguson) - * Add missing confirmation_keys (by @JohnPlummer) - * Ensure after_* hooks are called on RegistrationsController - * When using database_authenticatable Devise will now only create an email field when appropriate (if using default authentication_keys or custom authentication_keys with email included) - * Ensure stateless token does not trigger timeout (by @pixelauthority) - * Implement handle_unverified_request for Rails 3.0.4 compatibility and improve FailureApp reliance on symbols - * Consider namespaces while generating routes - * Custom failure apps no longer ignored in test mode (by @jaghion) - * Do not depend on ActiveModel::Dirty - * Manual sign_in now triggers remember token - * Be sure to halt strategies on failures - * Consider SCRIPT_NAME on Omniauth paths - * Reset failed attempts when lock is expired - * Ensure there is no Mongoid injection - -* deprecations - * Deprecated anybody_signed_in? in favor of signed_in? (by @gavinhughes) - * Removed --haml and --slim view templates - * Devise::OmniAuth helpers were deprecated and removed in favor of Omniauth.config.test_mode - -== 1.2.rc - -* deprecations - * cookie_domain is deprecated in favor of cookie_options - * after_update_path_for can no longer be defined in ApplicationController - -* enhancements - * Added OmniAuth support - * Added ORM adapter to abstract ORM iteraction - * sign_out_via is available in the router to configure the method used for sign out (by @martinrehfeld) - * Improved Ajax requests handling in failure app (by @spastorino) - * Added request_keys to easily use request specific values (like subdomain) in authentication - * Increased the size of friendly_token to 60 characters (reduces the chances of a successful brute attack) - * Ensure the friendly token does not include "_" or "-" since some e-mails may not autolink it properly (by @rymai) - * Extracted encryptors into :encryptable for better bcrypt support - * :rememberable is now able to use salt as token if no remember_token is provided - * Store the salt in session and expire the session if the user changes his password - * Allow :stateless_token to be set to true avoiding users to be stored in session through token authentication - * cookie_options uses session_options values by default - * Sign up now check if the user is active or not and redirect him accordingly setting the inactive_signed_up message - * Use ActiveModel#to_key instead of #id - * sign_out_all_scopes now destroys the whole session - * Added case_insensitive_keys that automatically downcases the given keys, by default downcases only e-mail (by @adahl) - -* default behavior changes - * sign_out_all_scopes defaults to true as security measure - * http authenticatable is disabled by default - * Devise does not intercept 401 returned from applications - -* bugfix - * after_sign_in_path_for always receives a resource - * Do not execute Warden::Callbacks on Devise::TestHelpers (by @sgronblo) - * Allow password recovery and account unlocking to change used keys (by @RStankov) - * FailureApp now properly handles nil request.format - * Fix a bug causing FailureApp to return with HTTP Auth Headers for IE7 - * Ensure namespaces has proper scoped views - * Ensure Devise does not set empty flash messages (by @sxross) - -== 1.1.6 - -* Use a more secure e-mail regexp -* Implement Rails 3.0.4 handle unverified request -* Use secure_compare to compare passwords - -== 1.1.5 - -* bugfix - * Ensure to convert keys on indifferent hash - -* defaults - * Set config.http_authenticatable to false to avoid confusion - -== 1.1.4 - -* bugfix - * Avoid session fixation attacks - -== 1.1.3 - -* bugfix - * Add reply-to to e-mail headers by default - * Updated the views generator to respect the rails :template_engine option (by @fredwu) - * Check the type of HTTP Authentication before using Basic headers - * Avoid invalid_salt errors by checking salt presence (by @thibaudgg) - * Forget user deletes the right cookie before logout, not remembering the user anymore (by @emtrane) - * Fix for failed first-ever logins on PostgreSQL where column default is nil (by @bensie) - * :default options is now honored in migrations - -== 1.1.2 - -* bugfix - * Compatibility with latest Rails routes schema - -== 1.1.1 - -* bugfix - * Fix a small bug where generated locale file was empty on devise:install - -== 1.1.0 - -* enhancements - * Rememberable module allows user to be remembered across browsers and is enabled by default (by @trevorturk) - * Rememberable module allows you to activate the period the remember me token is extended (by @trevorturk) - * devise_for can now be used together with scope method in routes but with a few limitations (check the documentation) - * Support `as` or `devise_scope` in the router to specify controller access scope - * HTTP Basic Auth can now be disabled/enabled for xhr(ajax) requests using http_authenticatable_on_xhr option (by @pellja) - -* bug fix - * Fix a bug in Devise::TestHelpers where current_user was returning a Response object for non active accounts - * Devise should respect script_name and path_info contracts - * Fix a bug when accessing a path with (.:format) (by @klacointe) - * Do not add unlock routes unless unlock strategy is email or both - * Email should be case insensitive - * Store classes as string in session, to avoid serialization and stale data issues - -* deprecations - * use_default_scope is deprecated and has no effect. Use :as or :devise_scope in the router instead - -== 1.1.rc2 - -* enhancements - * Allow to set cookie domain for the remember token. (by @mantas) - * Added navigational formats to specify when it should return a 302 and when a 401. - * Added authenticate(scope) support in routes (by @wildchild) - * Added after_update_path_for to registrations controller (by @thedelchop) - * Allow the mailer object to be replaced through config.mailer = "MyOwnMailer" - -* bug fix - * Fix a bug where session was timing out on sign out - -* deprecations - * bcrypt is now the default encryptor - * devise.mailer.confirmations_instructions now should be devise.mailer.confirmations_instructions.subject - * devise.mailer.user.confirmations_instructions now should be devise.mailer.confirmations_instructions.user_subject - * Generators now use Rails 3 syntax (devise:install) instead of devise_install - -== 1.1.rc1 - -* enhancements - * Rails 3 compatibility - * All controllers and views are namespaced, for example: Devise::SessionsController and "devise/sessions" - * Devise.orm is deprecated. This reduces the required API to hook your ORM with devise - * Use metal for failure app - * HTML e-mails now have proper formatting - * Allow to give :skip and :controllers in routes - * Move trackable logic to the model - * E-mails now use any template available in the filesystem. Easy to create multipart e-mails - * E-mails asks headers_for in the model to set the proper headers - * Allow to specify haml in devise_views - * Compatibility with Mongoid - * Make config.devise available on config/application.rb - * TokenAuthenticatable now works with HTTP Basic Auth - * Allow :unlock_strategy to be :none and add :lock_strategy which can be :failed_attempts or none. Setting those values to :none means that you want to handle lock and unlocking by yourself - * No need to append ?unauthenticated=true in URLs anymore since Flash was moved to a middleware in Rails 3 - * :activatable is included by default in your models - -* bug fix - * Fix a bug with STI - -* deprecations - * Rails 3 compatible only - * Removed support for MongoMapper - * Scoped views are no longer "sessions/users/new". Now use "users/sessions/new" - * Devise.orm is deprecated, just require "devise/orm/YOUR_ORM" instead - * Devise.default_url_options is deprecated, just modify ApplicationController.default_url_options - * All messages under devise.sessions, except :signed_in and :signed_out, should be moved to devise.failure - * :as and :scope in routes is deprecated. Use :path and :singular instead - -== 1.0.8 - -* enhancements - * Support for latest MongoMapper - * Added anybody_signed_in? helper (by @SSDany) - -* bug fix - * confirmation_required? is properly honored on active? calls. (by @paulrosania) - -== 1.0.7 - -* bug fix - * Ensure password confirmation is always required - -* deprecations - * authenticatable was deprecated and renamed to database_authenticatable - * confirmable is not included by default on generation - -== 1.0.6 - -* bug fix - * Do not allow unlockable strategies based on time to access a controller. - * Do not send unlockable email several times. - * Allow controller to upstram custom! failures to Warden. - -== 1.0.5 - -* bug fix - * Use prepend_before_filter in require_no_authentication. - * require_no_authentication on unlockable. - * Fix a bug when giving an association proxy to devise. - * Do not use lock! on lockable since it's part of ActiveRecord API. - -== 1.0.4 - -* bug fix - * Fixed a bug when deleting an account with rememberable - * Fixed a bug with custom controllers - -== 1.0.3 - -* enhancements - * HTML e-mails now have proper formatting - * Do not remove MongoMapper options in find - -== 1.0.2 - -* enhancements - * Allows you set mailer content type (by @glennr) - -* bug fix - * Uses the same content type as request on http authenticatable 401 responses - -== 1.0.1 - -* enhancements - * HttpAuthenticatable is not added by default automatically. - * Avoid mass assignment error messages with current password. - -* bug fix - * Fixed encryptors autoload - -== 1.0.0 - -* deprecation - * :old_password in update_with_password is deprecated, use :current_password instead - -* enhancements - * Added Registerable - * Added Http Basic Authentication support - * Allow scoped_views to be customized per controller/mailer class - * [#99] Allow authenticatable to used in change_table statements - -== 0.9.2 - -* bug fix - * Ensure inactive user cannot sign in - * Ensure redirect to proper url after sign up - -* enhancements - * Added gemspec to repo - * Added token authenticatable (by @grimen) - -== 0.9.1 - -* bug fix - * Allow bigger salt size (by @jgeiger) - * Fix relative url root - -== 0.9.0 - -* deprecation - * devise :all is deprecated - * :success and :failure flash messages are now :notice and :alert - -* enhancements - * Added devise lockable (by @mhfs) - * Warden 0.9.0 compatibility - * Mongomapper 0.6.10 compatibility - * Added Devise.add_module as hooks for extensions (by @grimen) - * Ruby 1.9.1 compatibility (by @grimen) - -* bug fix - * Accept path prefix not starting with slash - * url helpers should rely on find_scope! - -== 0.8.2 - -* enhancements - * Allow Devise.mailer_sender to be a proc (by @grimen) - -* bug fix - * Fix bug with passenger, update is required to anyone deploying on passenger (by @dvdpalm) - -== 0.8.1 - -* enhancements - * Move salt to encryptors - * Devise::Lockable - * Moved view links into partial and I18n'ed them - -* bug fix - * Bcrypt generator was not being loaded neither setting the proper salt - -== 0.8.0 - -* enhancements - * Warden 0.8.0 compatibility - * Add an easy for map.connect "sign_in", :controller => "sessions", :action => "new" to work - * Added :bcrypt encryptor (by @capotej) - -* bug fix - * sign_in_count is also increased when user signs in via password change, confirmation, etc.. - * More DataMapper compatibility (by @lancecarlson) - -* deprecation - * Removed DeviseMailer.sender - -== 0.7.5 - -* enhancements - * Set a default value for mailer to avoid find_template issues - * Add models configuration to MongoMapper::EmbeddedDocument as well - -== 0.7.4 - -* enhancements - * Extract Activatable from Confirmable - * Decouple Serializers from Devise modules - -== 0.7.3 - -* bug fix - * Give scope to the proper model validation - -* enhancements - * Mail views are scoped as well - * Added update_with_password for authenticatable - * Allow render_with_scope to accept :controller option - -== 0.7.2 - -* deprecation - * Renamed reset_confirmation! to resend_confirmation! - * Copying locale is part of the installation process - -* bug fix - * Fixed render_with_scope to work with all controllers - * Allow sign in with two different users in Devise::TestHelpers - -== 0.7.1 - -* enhancements - * Small enhancements for other plugins compatibility (by @grimen) - -== 0.7.0 - -* deprecations - * :authenticatable is not included by default anymore - -* enhancements - * Improve loading process - * Extract SessionSerializer from Authenticatable - -== 0.6.3 - -* bug fix - * Added trackable to migrations - * Allow inflections to work - -== 0.6.2 - -* enhancements - * More DataMapper compatibility - * Devise::Trackable - track sign in count, timestamps and ips - -== 0.6.1 - -* enhancements - * Devise::Timeoutable - timeout sessions without activity - * DataMapper now accepts conditions - -== 0.6.0 - -* deprecations - * :authenticatable is still included by default, but yields a deprecation warning - -* enhancements - * Added DataMapper support - * Remove store_location from authenticatable strategy and add it to failure app - * Allow a strategy to be placed after authenticatable - * [#45] Do not rely attribute? methods, since they are not added on Datamapper - -== 0.5.6 - -* enhancements - * [#42] Do not send nil to build (DataMapper compatibility) - * [#44] Allow to have scoped views - -== 0.5.5 - -* enhancements - * Allow overwriting find for authentication method - * [#38] Remove Ruby 1.8.7 dependency - -== 0.5.4 - -* deprecations - * Deprecate :singular in devise_for and use :scope instead - -* enhancements - * [#37] Create after_sign_in_path_for and after_sign_out_path_for hooks to be - overwriten in ApplicationController - * Create sign_in_and_redirect and sign_out_and_redirect helpers - * Warden::Manager.default_scope is automatically configured to the first given scope - -== 0.5.3 - -* bug fix - * MongoMapper now converts DateTime to Time - * Ensure all controllers are unloadable - -* enhancements - * [#35] Moved friendly_token to Devise - * Added Devise.all, so you can freeze your app strategies - * Added Devise.apply_schema, so you can turn it to false in Datamapper or MongoMapper - in cases you don't want it be handlded automatically - -== 0.5.2 - -* enhancements - * [#28] Improved sign_in and sign_out helpers to accepts resources - * [#28] Added stored_location_for as a helper - * [#20] Added test helpers - -== 0.5.1 - -* enhancements - * Added serializers based on Warden ones - * Allow authentication keys to be set - -== 0.5.0 - -* bug fix - * Fixed a bug where remember me module was not working properly - -* enhancements - * Moved encryption strategy into the Encryptors module to allow several algorithms (by @mhfs) - * Implemented encryptors for Clearance, Authlogic and Restful-Authentication (by @mhfs) - * Added support for MongoMapper (by @shingara) - -== 0.4.3 - -* bug fix - * [#29] Authentication just fails if user cannot be serialized from session, without raising errors; - * Default configuration values should not overwrite user values; - -== 0.4.2 - -* deprecations - * Renamed mail_sender to mailer_sender - -* enhancements - * skip_before_filter added in Devise controllers - * Use home_or_root_path on require_no_authentication as well - * Added devise_controller?, useful to select or reject filters in ApplicationController - * Allow :path_prefix to be given to devise_for - * Allow default_url_options to be configured through devise (:path_prefix => "/:locale" is now supported) - -== 0.4.1 - -* bug fix - * [#21] Ensure options can be set even if models were not loaded - -== 0.4.0 - -* deprecations - * Notifier is deprecated, use DeviseMailer instead. Remember to rename - app/views/notifier to app/views/devise_mailer and I18n key from - devise.notifier to devise.mailer - * :authenticable calls are deprecated, use :authenticatable instead - -* enhancements - * [#16] Allow devise to be more agnostic and do not require ActiveRecord to be loaded - * Allow Warden::Manager to be configured through Devise - * Created a generator which creates an initializer - -== 0.3.0 - -* bug fix - * [#15] Allow yml messages to be configured by not using engine locales - -* deprecations - * Renamed confirm_in to confirm_within - * [#14] Do not send confirmation messages when user changes his e-mail - * [#13] Renamed authenticable to authenticatable and added deprecation warnings - -== 0.2.3 - -* enhancements - * Ensure fail! works inside strategies - * [#12] Make unauthenticated message (when you haven't signed in) different from invalid message - -* bug fix - * Do not redirect on invalid authenticate - * Allow model configuration to be set to nil - -== 0.2.2 - -* bug fix - * [#9] Fix a bug when using customized resources - -== 0.2.1 - -* refactor - * Clean devise_views generator to use devise existing views - -* enhancements - * [#7] Create instance variables (like @user) for each devise controller - * Use Devise::Controller::Helpers only internally - -* bug fix - * [#6] Fix a bug with Mongrel and Ruby 1.8.6 - -== 0.2.0 - -* enhancements - * [#4] Allow option :null => true in authenticable migration - * [#3] Remove attr_accessible calls from devise modules - * Customizable time frame for rememberable with :remember_for config - * Customizable time frame for confirmable with :confirm_in config - * Generators for creating a resource and copy views - -* optimize - * Do not load hooks or strategies if they are not used - -* bug fixes - * [#2] Fixed requiring devise strategies - -== 0.1.1 - -* bug fixes - * [#1] Fixed requiring devise mapping - -== 0.1.0 - -* Devise::Authenticable -* Devise::Confirmable -* Devise::Recoverable -* Devise::Validatable -* Devise::Migratable -* Devise::Rememberable - -* SessionsController -* PasswordsController -* ConfirmationsController - -* Create an example app -* devise :all, :except => :rememberable -* Use sign_in and sign_out in SessionsController - -* Mailer subjects namespaced by model -* Allow stretches and pepper per model - -* Store session[:return_to] in session -* Sign user in automatically after confirming or changing it's password diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..5d594d2f52 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,22 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by sending an email to [heartcombo.oss@gmail.com](heartcombo.oss@gmail.com) or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0125b06c31..336d614f40 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,12 +1,79 @@ -### Please read before contributing +# How to contribute to Devise -1) If you have any questions about Devise, search the [Wiki](https://github.com/plataformatec/devise/wiki) or use the [Mailing List](groups.google.com/group/plataformatec-devise) or [Stack Overflow](http://stackoverflow.com/questions/tagged/devise). Do not post questions here. +Thanks for your interest on contributing to Devise! Here are a few general +guidelines on contributing and reporting bugs to Devise that we ask you to +take a look first. Notice that all of your interactions in the project are +expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md). -2) If you find a security bug, **DO NOT** submit an issue here. Please send an e-mail to [developers@plataformatec.com.br](mailto:developers@plataformatec.com.br) instead. +## Reporting Issues -3) Do a small search on the issues tracker before submitting your issue to see if it was already reported / fixed. In case it was not, create your report including Rails, Devise and Warden versions. If you are getting exceptions, please include the full backtrace. +Before reporting a new issue, please be sure that the issue wasn't already +reported or fixed by searching on GitHub through our [issues](https://github.com/heartcombo/devise/issues). -That's it! The more information you give, the more easy it becomes for us to track it down and fix it. Ideal scenario would be adding the issue to Devise test suite or to a sample application. +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 +even better a **sample Rails app that replicates the issue** - Devise has a lot +of moving parts and it's functionality can be affected by third party gems, so +we need as much context and details as possible to identify what might be broken +for you. We have a [test case template](guides/bug_report_templates/integration_test.rb) +that can be used to replicate issues with minimal setup. -Thanks! +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/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). + +**If you find a security bug, do not report it through GitHub. Please send an +e-mail to [heartcombo.oss@gmail.com](mailto:heartcombo.oss@gmail.com) +instead.** + +## Sending Pull Requests + +Before sending a new Pull Request, take a look on existing Pull Requests and Issues +to see if the proposed change or fix has been discussed in the past, or if the +change was already implemented but not yet released. + +We expect new Pull Requests to include enough tests for new or changed behavior, +and we aim to maintain everything as most backwards compatible as possible, +reserving breaking changes to be ship in major releases when necessary - you +can wrap the new code path with a setting toggle from the `Devise` module defined +as `false` by default to require developers to opt-in for the new behavior. + +If your Pull Request includes new or changed behavior, be sure that the changes +are beneficial to a wide range of use cases or it's an application specific change +that might not be so valuable to other applications. Some changes can be introduced +as a new `devise-something` gem instead of belonging to the main codebase. + +When adding new settings, you can take advantage of the [`Devise::Models.config`](https://github.com/heartcombo/devise/blob/245b1f9de0b3386b7913e14b60ea24f43b77feb0/lib/devise/models.rb#L13-L50) method to add class and instance level fallbacks +to the new setting. + +We also welcome Pull Requests that improve our existing documentation (both our +`README.md` and the RDoc sections in the source code) or improve existing rough +edges in our API that might be blocking existing integrations or 3rd party gems. + +## Other ways to contribute + +We welcome anyone that wants to contribute to Devise to triage and reply to +open issues to help troubleshoot and fix existing bugs on Devise. Here is what +you can do: + +* Help ensure that existing issues follows the recommendations from the +_[Reporting Issues](#reporting-issues)_ section, providing feedback to the issue's +author on what might be missing. +* Review and update the existing content of our [Wiki](https://github.com/heartcombo/devise/wiki) +with up to date instructions and code samples - the wiki was grown with several +different tutorials and references that we can't keep track of everything, so if +there is a page that showcases an integration or customization that you are +familiar with feel free to update it as necessary. +* Review existing Pull Requests, and testing patches against real existing +applications that use Devise. + +Thanks again for your interest on contributing to the project! + +:heart: diff --git a/Gemfile b/Gemfile index 25e659ef5c..3fc8499f9c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,33 @@ -source "http://rubygems.org" +# frozen_string_literal: true + +source "https://rubygems.org" gemspec -gem "rails", "~> 3.2.6" -gem "omniauth", "~> 1.0.0" -gem "omniauth-oauth2", "~> 1.0.0" +gem "omniauth" +gem "omniauth-oauth2" +gem "rails", "~> 8.1.0" gem "rdoc" +gem "rails-controller-testing" + +gem "responders", "~> 3.1" + group :test do + gem "minitest", "< 6" + gem "mocha", "~> 2.1", require: false gem "omniauth-facebook" - gem "omniauth-openid", "~> 1.0.1" - gem "webrat", "0.7.2", :require => false - gem "mocha", :require => false -end - -platforms :jruby do - gem "activerecord-jdbc-adapter" - gem "activerecord-jdbcsqlite3-adapter" - gem "jruby-openssl" + gem "omniauth-openid" + gem "rexml" + gem "timecop" + gem "webrat" + gem "ostruct" end platforms :ruby do gem "sqlite3" +end - group :mongoid do - gem "mongo", "~> 1.3.0" - gem "mongoid", "~> 2.0" - gem "bson_ext", "~> 1.3.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 a13d5de8af..ddd309923f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,155 +1,312 @@ +GIT + remote: https://github.com/mongodb/mongoid.git + revision: dce2e0fa3c5f0dd2086b2c8341086ff05e1b37f9 + branch: 9.0-stable + specs: + mongoid (9.0.9) + 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 (2.1.2) - bcrypt-ruby (~> 3.0) + devise (5.0.0) + bcrypt (~> 3.0) orm_adapter (~> 0.1) - railties (~> 3.1) - warden (~> 1.2.1) + railties (>= 7.0) + responders + warden (~> 1.2.3) GEM - remote: http://rubygems.org/ + remote: https://rubygems.org/ specs: - actionmailer (3.2.6) - actionpack (= 3.2.6) - mail (~> 2.4.4) - actionpack (3.2.6) - activemodel (= 3.2.6) - activesupport (= 3.2.6) - builder (~> 3.0.0) - erubis (~> 2.7.0) - journey (~> 1.0.1) - rack (~> 1.4.0) - rack-cache (~> 1.2) - rack-test (~> 0.6.1) - sprockets (~> 2.1.3) - activemodel (3.2.6) - activesupport (= 3.2.6) - builder (~> 3.0.0) - activerecord (3.2.6) - activemodel (= 3.2.6) - activesupport (= 3.2.6) - arel (~> 3.0.2) - tzinfo (~> 0.3.29) - activeresource (3.2.6) - activemodel (= 3.2.6) - activesupport (= 3.2.6) - activesupport (3.2.6) - i18n (~> 0.6) - multi_json (~> 1.0) - addressable (2.2.6) - arel (3.0.2) - bcrypt-ruby (3.0.1) - bson (1.5.1) - bson_ext (1.3.1) - builder (3.0.0) - erubis (2.7.0) - faraday (0.7.5) - addressable (~> 2.2.6) - multipart-post (~> 1.1.3) - rack (>= 1.1.0, < 2) - hashie (1.2.0) - hike (1.2.1) - i18n (0.6.0) - journey (1.0.4) - json (1.7.3) - mail (2.4.4) - i18n (>= 0.4.0) - mime-types (~> 1.16) - treetop (~> 1.4.8) - metaclass (0.0.1) - mime-types (1.18) - mocha (0.10.0) - metaclass (~> 0.0.1) - mongo (1.3.1) - bson (>= 1.3.1) - mongoid (2.3.4) - activemodel (~> 3.1) - mongo (~> 1.3) - tzinfo (~> 0.3.22) - multi_json (1.0.4) - multipart-post (1.1.4) - nokogiri (1.5.0) - oauth2 (0.5.1) - faraday (~> 0.7.4) - multi_json (~> 1.0.3) - omniauth (1.0.1) - hashie (~> 1.2) - rack - omniauth-facebook (1.0.0) - omniauth-oauth2 (~> 1.0.0) - omniauth-oauth2 (1.0.0) - oauth2 (~> 0.5.0) - omniauth (~> 1.0) - omniauth-openid (1.0.1) - omniauth (~> 1.0) - rack-openid (~> 1.3.1) - orm_adapter (0.3.0) - polyglot (0.3.3) - rack (1.4.1) - rack-cache (1.2) - rack (>= 0.4) - rack-openid (1.3.1) + action_text-trix (2.1.16) + railties + actioncable (8.1.2) + actionpack (= 8.1.2) + activesupport (= 8.1.2) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.2) + actionpack (= 8.1.2) + activejob (= 8.1.2) + activerecord (= 8.1.2) + activestorage (= 8.1.2) + activesupport (= 8.1.2) + mail (>= 2.8.0) + actionmailer (8.1.2) + actionpack (= 8.1.2) + actionview (= 8.1.2) + activejob (= 8.1.2) + activesupport (= 8.1.2) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.2) + actionview (= 8.1.2) + activesupport (= 8.1.2) + 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.2) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.2) + activerecord (= 8.1.2) + activestorage (= 8.1.2) + activesupport (= 8.1.2) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.2) + activesupport (= 8.1.2) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.2) + activesupport (= 8.1.2) + globalid (>= 0.3.6) + activemodel (8.1.2) + activesupport (= 8.1.2) + activerecord (8.1.2) + activemodel (= 8.1.2) + activesupport (= 8.1.2) + timeout (>= 0.4.0) + activestorage (8.1.2) + actionpack (= 8.1.2) + activejob (= 8.1.2) + activerecord (= 8.1.2) + activesupport (= 8.1.2) + marcel (~> 1.0) + activesupport (8.1.2) + 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.21) + 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.1) + erubi (1.13.1) + faraday (2.14.0) + 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.16.0) + pp (>= 0.6.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (2.18.0) + jwt (3.1.2) + base64 + logger (1.7.0) + loofah (2.25.0) + 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.22.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.2) + 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.0) + 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, < 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) + ostruct (0.6.3) + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + psych (5.3.1) + date + stringio + racc (1.8.1) + rack (3.2.4) + rack-openid (1.4.2) rack (>= 1.1.0) ruby-openid (>= 2.1.8) - rack-ssl (1.3.2) - rack - rack-test (0.6.1) - rack (>= 1.0) - rails (3.2.6) - actionmailer (= 3.2.6) - actionpack (= 3.2.6) - activerecord (= 3.2.6) - activeresource (= 3.2.6) - activesupport (= 3.2.6) - bundler (~> 1.0) - railties (= 3.2.6) - railties (3.2.6) - actionpack (= 3.2.6) - activesupport (= 3.2.6) - rack-ssl (~> 1.3.2) - rake (>= 0.8.7) - rdoc (~> 3.4) - thor (>= 0.14.6, < 2.0) - rake (0.9.2.2) - rdoc (3.12) - json (~> 1.4) - ruby-openid (2.1.8) - sprockets (2.1.3) - hike (~> 1.2) - rack (~> 1.0) - tilt (~> 1.1, != 1.3.0) - sqlite3 (1.3.5) - thor (0.15.2) - tilt (1.3.3) - treetop (1.4.10) - polyglot - polyglot (>= 0.3.1) - tzinfo (0.3.33) - warden (1.2.1) - rack (>= 1.0) - webrat (0.7.2) + 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.2) + actioncable (= 8.1.2) + actionmailbox (= 8.1.2) + actionmailer (= 8.1.2) + actionpack (= 8.1.2) + actiontext (= 8.1.2) + actionview (= 8.1.2) + activejob (= 8.1.2) + activemodel (= 8.1.2) + activerecord (= 8.1.2) + activestorage (= 8.1.2) + activesupport (= 8.1.2) + bundler (>= 1.15.0) + railties (= 8.1.2) + 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.6.2) + loofah (~> 2.21) + 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.2) + actionpack (= 8.1.2) + activesupport (= 8.1.2) + 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.1.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.0) + mini_portile2 (~> 2.8.0) + stringio (3.2.0) + thor (1.5.0) + timecop (0.9.10) + timeout (0.6.0) + tsort (0.2.0) + tzinfo (2.0.6) + concurrent-ruby (~> 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.8.0) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.7.4) PLATFORMS ruby DEPENDENCIES - activerecord-jdbc-adapter - activerecord-jdbcsqlite3-adapter - bson_ext (~> 1.3.0) devise! - jruby-openssl - mocha - mongo (~> 1.3.0) - mongoid (~> 2.0) - omniauth (~> 1.0.0) + minitest (< 6) + mocha (~> 2.1) + mongoid (~> 9.0)! + omniauth omniauth-facebook - omniauth-oauth2 (~> 1.0.0) - omniauth-openid (~> 1.0.1) - rails (~> 3.2.6) + omniauth-oauth2 + omniauth-openid + ostruct + rails (~> 8.1.0) + rails-controller-testing rdoc + responders (~> 3.1) + rexml sqlite3 - webrat (= 0.7.2) + timecop + webrat + +BUNDLED WITH + 4.0.3 diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..445eedba53 --- /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 fd1e181c9b..ad599708f3 100644 --- a/MIT-LICENSE +++ b/MIT-LICENSE @@ -1,4 +1,5 @@ -Copyright 2009-2012 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 03d806c13e..426185e6d9 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,63 @@ -*IMPORTANT:* Devise 2.1 is out. If you are upgrading, please read: https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.1 - -## Devise - -INFO: This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/). - -[![Build Status](https://secure.travis-ci.org/plataformatec/devise.png)](http://travis-ci.org/plataformatec/devise) [![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/plataformatec/devise) +![Devise Logo](https://raw.github.com/heartcombo/devise/main/devise.png) Devise is a flexible authentication solution for Rails based on Warden. It: * Is Rack based; * Is a complete MVC solution based on Rails engines; -* Allows you to have multiple roles (or models/scopes) signed in at the same time; -* Is based on a modularity concept: use just what you really need. - -It's composed of 12 modules: - -* [Database Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication. -* [Token Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable): signs in a user based on an authentication token (also known as "single access token"). The token can be given both through query string or HTTP Basic Authentication. -* [Omniauthable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Omniauthable): adds Omniauth (https://github.com/intridea/omniauth) support; -* [Confirmable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in. -* [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions. -* [Registerable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account. -* [Rememberable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie. -* [Trackable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address. -* [Timeoutable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have no activity in a specified period of time. -* [Validatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations. -* [Lockable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period. +* Allows you to have multiple models signed in at the same time; +* Is based on a modularity concept: use only what you really need. + +It's composed of 10 modules: + +* [Database Authenticatable](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,93 +65,167 @@ It's composed of 12 modules: The Devise Wiki has lots of additional information about Devise including many "how-to" articles and answers to the most frequently asked questions. Please browse the Wiki after finishing this README: -https://wiki.github.com/plataformatec/devise +https://github.com/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 heartcombo.oss@gmail.com. + +### StackOverflow and Mailing List -If you found a security bug, do *NOT* use the GitHub issue tracker. Send an email to the maintainers listed at the bottom of the README. +If you have any questions, comments, or concerns, please use StackOverflow instead of the GitHub issue tracker: -### Mailing list +http://stackoverflow.com/questions/tagged/devise -If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker: +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 +http://rubydoc.info/github/heartcombo/devise/main/frames -If you need to use Devise with Rails 2.3, you can always run "gem server" from the command line after you install the gem to access the old documentation. +If you need to use Devise with previous versions of Rails, you can always run "gem server" from the command line after you install the gem to access the old documentation. ### Example applications 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 will usually want to write tests for your changes. To run the test suite, go into Devise's top-level directory and run "bundle install" and "rake". For the tests to pass, you will need to have a MongoDB server (version 2.0 or newer) running on your system. +You 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 +``` + +### Running tests +Devise uses [Mini Test](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 to *not* use Devise. Devise requires a good understanding of the Rails Framework. In such cases, we advise you to start a simple authentication system from scratch, today we have two resources: +If you are building your first Rails application, we recommend you *do not* use Devise. Devise requires a good understanding of the Rails Framework. In such cases, we advise you to start a simple authentication system from scratch. Here's a few resources that should help you get started: -* Michael Hartl's online book: http://railstutorial.org/chapters/modeling-and-viewing-users-two#top -* Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch +* Michael Hartl's online book: https://www.railstutorial.org/book/modeling_users +* Ryan Bates' Railscasts: http://railscasts.com/episodes/250-authentication-from-scratch and http://railscasts.com/episodes/250-authentication-from-scratch-revised +* Codecademy's Ruby on Rails: Authentication and Authorization: https://www.codecademy.com/learn/rails-auth -Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :) +Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :smiley: ## Getting started -Devise 2.0 works with Rails 3.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 ``` -Run the bundle command to install it. - -After you install Devise and add it to your Gemfile, you need to run the generator: +Next, you need to run the generator: ```console rails generate devise:install ``` -The generator will install an initializer which describes ALL Devise's configuration options and you MUST take a look at it. When you are done, you are ready to add Devise to any of your models using the generator: +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`: + +```ruby +config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } +``` + +The generator will install an initializer which describes ALL of Devise's configuration options. It is *imperative* that you take a look at it. When you are done, you are ready to add Devise to any of your models using the generator. + + +In the following command you will replace `MODEL` with the class name used for the application’s users (it’s frequently `User` but could also be `Admin`). This will create a model (if one does not exist) and configure it with the default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller. ```console rails generate devise MODEL ``` -Replace MODEL by the class name used for the applications users, it's frequently 'User' but could also be 'Admin'. This will create a model (if one does not exist) and configure it with default Devise modules. Next, you'll usually run "rake db:migrate" as the generator will have created a migration file (if your ORM supports them). This generator also configures your config/routes.rb file to point to Devise controller. +Next, check the MODEL for any additional configuration options you might want to add, such as confirmable or lockable. If you add an option, be sure to inspect the migration file (created by the generator if your ORM supports them) and uncomment the appropriate section. For example, if you add the confirmable option in the model, you'll need to uncomment the Confirmable section in the migration. + +Then run `rails db:migrate` -Note that you should re-start your app here if you've already started it. Otherwise you'll run into strange errors like users being unable to login and the 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 -Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_filter: +Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_action (assuming your devise model is 'User'): ```ruby -before_filter :authenticate_user! +before_action :authenticate_user! ``` +For Rails 5, note that `protect_from_forgery` is no longer prepended to the `before_action` chain, so if you have set `authenticate_user` before `protect_from_forgery`, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use `protect_from_forgery prepend: true`. + +If your devise model is something other than User, replace "_user" with "_yourmodel". The same logic applies to the instructions below. + To verify if a user is signed in, use the following helper: ```ruby @@ -138,24 +244,18 @@ You can access the session for this scope: user_session ``` -After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect. Example: For a :user resource, it will use `user_root_path` if it exists, otherwise default `root_path` will be used. This means that you need to set the root inside your routes: +After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect to. For instance, when using a `:user` resource, the `user_root_path` will be used if it exists; otherwise, the default `root_path` will be used. This means that you need to set the root inside your routes: ```ruby -root :to => "home#index" +root to: 'home#index' ``` -You can also overwrite `after_sign_in_path_for` and `after_sign_out_path_for` to customize your redirect hooks. - -Finally, you need to set up default url options for the mailer in each environment. Here is the configuration for "config/environments/development.rb": - -```ruby -config.action_mailer.default_url_options = { :host => 'localhost:3000' } -``` +You can also override `after_sign_in_path_for` and `after_sign_out_path_for` to customize your redirect hooks. -Notice that if your devise model is not called "user" but "member", then the helpers you should use are: +Notice that if your Devise model is called `Member` instead of `User`, for example, then the helpers available are: ```ruby -before_filter :authenticate_member! +before_action :authenticate_member! member_signed_in? @@ -166,42 +266,109 @@ member_session ### Configuring Models -The devise method in your models also accepts some options to configure its modules. For example, you can choose the cost of the encryption algorithm with: +The Devise method in your models also accepts some options to configure its modules. For example, you can choose the cost of the hashing algorithm with: ```ruby -devise :database_authenticatable, :registerable, :confirmable, :recoverable, :stretches => 20 +devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 13 ``` -Besides :stretches, you can define :pepper, :encryptor, :confirm_within, :remember_for, :timeout_in, :unlock_in and other values. For details, see the initializer file that was created when you invoked the "devise:install" generator described above. +Besides `:stretches`, you can define `:pepper`, `:encryptor`, `:confirm_within`, `:remember_for`, `:timeout_in`, `:unlock_in` among other options. For more details, see the initializer file that was created when you invoked the "devise:install" generator described above. This file is usually located at `/config/initializers/devise.rb`. -### Configuring multiple models +### Strong Parameters + +The Parameter Sanitizer API has changed for Devise 4 :warning: + +*For previous Devise versions see https://github.com/heartcombo/devise/tree/3-stable#strong-parameters* + +When you customize your own views, you may end up adding new attributes to forms. Rails 4 moved the parameter sanitization from the model to the controller, causing Devise to handle this concern at the controller as well. + +There are just three actions in Devise that allow any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and default permitted parameters are: + +* `sign_in` (`Devise::SessionsController#create`) - Permits only the authentication keys (like `email`) +* `sign_up` (`Devise::RegistrationsController#create`) - Permits authentication keys plus `password` and `password_confirmation` +* `account_update` (`Devise::RegistrationsController#update`) - Permits authentication keys plus `password`, `password_confirmation` and `current_password` -Devise allows you to set up as many roles as you want. For example, you may have a User model and also want an Admin model with just authentication and timeoutable features. If so, just follow these steps: +In case you want to permit additional parameters (the lazy way™), you can do so using a simple before action in your `ApplicationController`: ```ruby -# Create a migration with the required fields -create_table :admins do |t| - t.string :email - t.string :encrypted_password - t.timestamps +class ApplicationController < ActionController::Base + before_action :configure_permitted_parameters, if: :devise_controller? + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [:username]) + end end +``` -# Inside your Admin model -devise :database_authenticatable, :timeoutable +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: -# Inside your routes -devise_for :admins +```ruby +class ApplicationController < ActionController::Base + before_action :configure_permitted_parameters, if: :devise_controller? -# Inside your protected controller -before_filter :authenticate_admin! + protected -# Inside your controllers and views -admin_signed_in? -current_admin -admin_session + 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 + +```ruby +def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_in) do |user_params| + user_params.permit(:username, :email) + end +end +``` + +If you have some checkboxes that express the roles a user may take on registration, the browser will send those selected checkboxes as an array. An array is not one of Strong Parameters' permitted scalars, so we need to configure Devise in the following way: + +```ruby +def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up) do |user_params| + user_params.permit({ roles: [] }, :email, :password, :password_confirmation) + end +end +``` +For the list of permitted scalars, and how to declare permitted keys in nested hashes and arrays, see + +https://github.com/rails/strong_parameters#nested-parameters + +If you have multiple Devise models, you may want to set up a different parameter sanitizer per model. In this case, we recommend inheriting from `Devise::ParameterSanitizer` and adding your own logic: + +```ruby +class User::ParameterSanitizer < Devise::ParameterSanitizer + def initialize(*) + super + permit(:sign_up, keys: [:username, :email]) + end +end ``` -On the other hand, you can simply run the generator! +And then configure your controllers to use it: + +```ruby +class ApplicationController < ActionController::Base + protected + + def devise_parameter_sanitizer + if resource_class == User + User::ParameterSanitizer.new(User, :user, params) + else + super # Use the default one + end + end +end +``` + +The example above overrides the permitted parameters for the user to be both `:username` and `:email`. The non-lazy way to configure parameters would be by defining the before filter above in a custom controller. We detail how to configure and customize controllers in some sections below. ### Configuring views @@ -213,58 +380,141 @@ Since Devise is an engine, all its views are packaged inside the gem. These view rails generate devise:views ``` -If you have more than one role in your application (such as "User" and "Admin"), you will notice that Devise uses the same views for all roles. Fortunately, Devise offers an easy way to customize views. All you need to do is set "config.scoped_views = true" inside "config/initializers/devise.rb". +If you have more than one Devise model in your application (such as `User` and `Admin`), you will notice that Devise uses the same views for all models. Fortunately, Devise offers an easy way to customize views. All you need to do is set `config.scoped_views = true` inside the `config/initializers/devise.rb` file. -After doing so, you will be able to have views based on the role like "users/sessions/new" and "admins/sessions/new". If no view is found within the scope, Devise will use the default view at "devise/sessions/new". You can also use the generator to generate scoped views: +After doing so, you will be able to have views based on the role like `users/sessions/new` and `admins/sessions/new`. If no view is found within the scope, Devise will use the default view at `devise/sessions/new`. You can also use the generator to generate scoped views: ```console rails generate devise:views users ``` +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 views to the generator with the `-v` flag. + +```console +rails generate devise:views -v registrations confirmations +``` + ### Configuring controllers If the customization at the views level is not enough, you can customize each controller by following these steps: -1) Create your custom controller, for example a Admins::SessionsController: +1. Create your custom controllers using the generator which requires a scope: -```ruby -class Admins::SessionsController < Devise::SessionsController -end -``` + ```console + rails generate devise:controllers [scope] + ``` -2) Tell the router to use this controller: + If you specify `users` as the scope, controllers will be created in `app/controllers/users/`. + And the sessions controller will look like this: -```ruby -devise_for :admins, :controllers => { :sessions => "admins/sessions" } -``` + ```ruby + class Users::SessionsController < Devise::SessionsController + # GET /resource/sign_in + # def new + # super + # end + ... + 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: + + ```ruby + devise_for :users, controllers: { sessions: 'users/sessions' } + ``` + +3. Recommended but not required: copy (or move) the views from `devise/sessions` to `users/sessions`. Rails will continue using the views from `devise/sessions` due to inheritance if you skip this step, but having the views matching the controller(s) keeps things consistent. + +4. Finally, change or extend the desired controller actions. + + You can completely override a controller action: + + ```ruby + class Users::SessionsController < Devise::SessionsController + def create + # custom sign-in code + end + end + ``` + + Or you can simply add new behavior to it: -3) And since we changed the controller, it won't use the "devise/sessions" views, so remember to copy "devise/sessions" to "admin/sessions". + ```ruby + class Users::SessionsController < Devise::SessionsController + def create + super do |resource| + BackgroundWorker.trigger(resource) + end + end + end + ``` -Remember that Devise uses flash messages to let users know if sign in was successful or failed. Devise expects your application to call "flash[:notice]" and "flash[:alert]" as appropriate. Do not print the entire flash hash, print specific keys or at least remove the `:timedout` key from the hash as Devise adds this key in some circumstances, this key is not meant for display. + This is useful for triggering background jobs or logging events during certain actions. + +Remember that Devise uses flash messages to let users know if sign in was successful or unsuccessful. Devise expects your application to call `flash[:notice]` and `flash[:alert]` as appropriate. Do not print the entire flash hash, print only specific keys. In some circumstances, Devise adds a `:timedout` key to the flash hash, which is not meant for display. Remove this key from the hash if you intend to print the entire hash. ### Configuring routes Devise also ships with default routes. If you need to customize them, you should probably be able to do it through the devise_for method. It accepts several options like :class_name, :path_prefix and so on, including the possibility to change path names for I18n: ```ruby -devise_for :users, :path => "usuarios", :path_names => { :sign_in => 'login', :sign_out => 'logout', :password => 'secret', :confirmation => 'verification', :unlock => 'unblock', :registration => 'register', :sign_up => 'cmon_let_me_in' } +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 for details. +Be sure to check `devise_for` [documentation](https://www.rubydoc.info/gems/devise/ActionDispatch/Routing/Mapper#devise_for-instance_method) for details. -If you have the need for more deep customization, for instance to also allow "/sign_in" besides "/users/sign_in", all you need to do is to create your routes normally and wrap them in a `devise_scope` block in the router: +If you have the need for more deep customization, for instance to also allow "/sign_in" besides "/users/sign_in", all you need to do is create your routes normally and wrap them in a `devise_scope` block in the router: ```ruby devise_scope :user do - get "sign_in", :to => "devise/sessions#new" + get 'sign_in', to: 'devise/sessions#new' end ``` -This way you tell devise to use the scope :user when "/sign_in" is accessed. Notice `devise_scope` is also aliased as `as` in your router. +This way, you tell Devise to use the scope `:user` when "/sign_in" is accessed. Notice `devise_scope` is also aliased as `as` in your router. + +Please note: You will still need to add `devise_for` in your routes in order to use helper methods such as `current_user`. + +```ruby +devise_for :users, skip: :all +``` + +### Hotwire/Turbo + +Devise integrates with Hotwire/Turbo by treating such requests as navigational, and configuring certain responses for errors and redirects to match the expected behavior. New apps are generated with the following response configuration by default, and existing apps may opt-in by adding the config to their Devise initializers: + +```ruby +Devise.setup do |config| + # ... + # When using Devise with Hotwire/Turbo, the http status for error responses + # and some redirects must match the following. The default in Devise for existing + # apps is `200 OK` and `302 Found` respectively, but new apps are generated with + # these new defaults that match Hotwire/Turbo behavior. + # Note: These might become the new default in future versions of Devise. + config.responder.error_status = :unprocessable_content # for Rack 3.1 or higher + # config.responder.error_status = :unprocessable_entity # for Rack 3.0 or lower + config.responder.redirect_status = :see_other +end +``` + +**Important**: these custom responses require the `responders` gem version to be `3.1.0` or higher, please make sure you update it if you're going to use this configuration. Check [this upgrade guide](https://github.com/heartcombo/devise/wiki/How-To:-Upgrade-to-Devise-4.9.0-[Hotwire-Turbo-integration]) for more info. + +_Note_: the above statuses configuration may become the default for Devise in a future release. + +There are a couple other changes you might need to make in your app to work with Hotwire/Turbo, if you're migrating from rails-ujs: + +* The `data-confirm` option that adds a confirmation modal to buttons/forms before submission needs to change to `data-turbo-confirm`, so that Turbo handles those appropriately. +* The `data-method` option that sets the request method for link submissions needs to change to `data-turbo-method`. This is not necessary for `button_to` or `form`s since Turbo can handle those. + +If you're setting up Devise to sign out via `:delete`, and you're using links (instead of buttons wrapped in a form) to sign out with the `method: :delete` option, they will need to be updated as described above. (Devise does not provide sign out links/buttons in its shared views.) + +Make sure to inspect your views looking for those, and change appropriately. ### I18n -Devise uses flash messages with I18n with the flash keys :notice and :alert. To customize your app, you can set up your locale file: +Devise uses flash messages with I18n, in conjunction with the flash keys :notice and :alert. To customize your app, you can set up your locale file: ```yaml en: @@ -300,91 +550,227 @@ 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. ### Test helpers -Devise includes some tests helpers for functional specs. In order to use them, you need to include Devise in your functional tests by adding the following to the bottom of your `test/test_helper.rb` file: +Devise includes some test helpers for controller and integration tests. +In order to use them, you need to include the respective module in your test +cases/specs. + +### Controller tests + +Controller tests require that you include `Devise::Test::IntegrationHelpers` on +your test case or its parent `ActionController::TestCase` superclass. +For Rails versions prior to 5, include `Devise::Test::ControllerHelpers` instead, since the superclass +for controller tests was changed to ActionDispatch::IntegrationTest +(for more details, see the [Integration tests](#integration-tests) section). ```ruby -class ActionController::TestCase - include Devise::TestHelpers +class PostsControllerTest < ActionController::TestCase + include Devise::Test::IntegrationHelpers # Rails >= 5 end ``` -If you're using RSpec, you can put the following inside a file named `spec/support/devise.rb`: +```ruby +class PostsControllerTest < ActionController::TestCase + include Devise::Test::ControllerHelpers # Rails < 5 +end +``` + +If you're using RSpec, you can put the following inside a file named +`spec/support/devise.rb` or in your `spec/spec_helper.rb` (or +`spec/rails_helper.rb` if you are using `rspec-rails`): ```ruby RSpec.configure do |config| - config.include Devise::TestHelpers, :type => :controller + config.include Devise::Test::ControllerHelpers, type: :controller + config.include Devise::Test::ControllerHelpers, type: :view end ``` -Now you are ready to use the `sign_in` and `sign_out` methods. Such methods have the same signature as in controllers: +Just be sure that this inclusion is made *after* the `require 'rspec/rails'` directive. + +Now you are ready to use the `sign_in` and `sign_out` methods on your controller +tests: ```ruby -sign_in :user, @user # sign_in(scope, resource) -sign_in @user # sign_in(resource) +sign_in @user +sign_in @user, scope: :admin +``` -sign_out :user # sign_out(scope) -sign_out @user # sign_out(resource) +If you are testing Devise internal controllers or a controller that inherits +from Devise's, you need to tell Devise which mapping should be used before a +request. This is necessary because Devise gets this information from the router, +but since controller tests do not pass through the router, it needs to be stated +explicitly. For example, if you are testing the user scope, simply use: + +```ruby +test 'GET new' do + # Mimic the router behavior of setting the Devise scope through the env. + @request.env['devise.mapping'] = Devise.mappings[:user] + + # Use the sign_in helper to sign in a fixture `User` record. + sign_in users(:alice) + + get :new + + # assert something +end ``` -There are two things that is important to keep in mind: +### Integration tests -1) These helpers are not going to work for integration tests driven by Capybara or Webrat. They are meant to be used with functional tests only. Instead, fill in the form or explicitly set the user in session; +Integration test helpers are available by including the +`Devise::Test::IntegrationHelpers` module. -2) If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from router, but since functional tests do not pass through the router, it needs to be told explicitly. For example, if you are testing the user scope, simply do: +```ruby +class PostsTests < ActionDispatch::IntegrationTest + include Devise::Test::IntegrationHelpers +end +``` - @request.env["devise.mapping"] = Devise.mappings[:user] - get :new +Now you can use the following `sign_in` and `sign_out` methods in your integration +tests: -### Omniauth +```ruby +sign_in users(:bob) +sign_in users(:bob), scope: :admin -Devise comes with Omniauth support out of the box to authenticate from other providers. You can read more about Omniauth support in the wiki: +sign_out :user +``` -* https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview +RSpec users can include the `IntegrationHelpers` module on their `:feature` specs. -### Other ORMs +```ruby +RSpec.configure do |config| + config.include Devise::Test::IntegrationHelpers, type: :feature +end +``` + +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 controllers with RSpec in the wiki: + +* https://github.com/heartcombo/devise/wiki/How-To:-Test-controllers-with-Rails-(and-RSpec) -Devise supports ActiveRecord (default) and Mongoid. To choose other ORM, you just need to require it in the initializer file. +### OmniAuth -### Migrating from other solutions +Devise comes with OmniAuth support out of the box to authenticate with other providers. To use it, simply specify your OmniAuth configuration in `config/initializers/devise.rb`: -Devise implements encryption strategies for Clearance, Authlogic and Restful-Authentication. To make use of these strategies, you need set the desired encryptor in the encryptor initializer config option and add :encryptable to your model. You might also need to rename your encrypted password and salt columns to match Devise's fields (encrypted_password and password_salt). +```ruby +config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' +``` + +You can read more about OmniAuth support in the wiki: -## Troubleshooting +* https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview -### Heroku +### Configuring multiple models -Using devise on Heroku with Ruby on Rails 3.1 requires setting: +Devise allows you to set up as many Devise models as you want. If you want to have an Admin model with just authentication and timeout features, in addition to the User model above, just run: ```ruby -config.assets.initialize_on_precompile = false +# Create a migration with the required fields +create_table :admins do |t| + t.string :email + t.string :encrypted_password + t.timestamps null: false +end + +# Inside your Admin model +devise :database_authenticatable, :timeoutable + +# Inside your routes +devise_for :admins + +# Inside your protected controller +before_action :authenticate_admin! + +# Inside your controllers and views +admin_signed_in? +current_admin +admin_session ``` -Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html +Alternatively, you can simply run the Devise generator. -## Additional information +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. -### Warden +### Active Job Integration -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: +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. + +```ruby +def send_devise_notification(notification, *args) + devise_mailer.send(notification, self, *args).deliver_later +end +``` + +### Password reset tokens and Rails logs + +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: -https://github.com/hassox/warden +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. -### Contributors +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`: -We have a long list of valued contributors. Check them all at: +```ruby +config.log_level = :warn +``` + + +### Other ORMs + +Devise supports ActiveRecord (default) and Mongoid. To select another ORM, simply require it in the initializer file. + +### Rails API Mode -https://github.com/plataformatec/devise/contributors +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/)) -### Maintainers +#### 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)) -* José Valim (https://github.com/josevalim) -* Carlos Antônio da Silva (https://github.com/carlosantoniodasilva) -* Rodrigo Flores (https://github.com/rodrigoflores) +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.http_authenticatable = [:database] +``` + +This restriction does not limit you from implementing custom warden strategies, either in your application or via gem-based extensions for devise. +A common authentication strategy for APIs is token-based authentication. For more information on extending devise to support this type of authentication and others, see the wiki article for [Simple Token Authentication Examples and alternatives](https://github.com/heartcombo/devise/wiki/How-To:-Simple-Token-Authentication-Example#alternatives) or this blog post on [Custom authentication methods with Devise](http://blog.plataformatec.com.br/2019/01/custom-authentication-methods-with-devise/). + +#### Testing +API Mode changes the order of the middleware stack, and this can cause problems for `Devise::Test::IntegrationHelpers`. This problem usually surfaces as an ```undefined method `[]=' for nil:NilClass``` error when using integration test helpers, such as `#sign_in`. The solution is simply to reorder the middlewares by adding the following to test.rb: + +```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). + +Additionally be mindful that without views supported, some email-based flows from Confirmable, Recoverable and Lockable are not supported directly at this time. + +## Additional information + +### Warden + +Devise is based on Warden, which is a general Rack authentication framework created by Daniel Neighman. We encourage you to read more about Warden here: + +https://github.com/wardencommunity/warden ## License -MIT License. Copyright 2012 Plataformatec. http://plataformatec.com.br +MIT License. +Copyright 2020-CURRENT Rafael França, Carlos Antonio da Silva. +Copyright 2009-2019 Plataformatec. + +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 8a0ac62459..6e2ab1802a 100644 --- a/Rakefile +++ b/Rakefile @@ -1,10 +1,12 @@ # encoding: UTF-8 -require "bundler/gem_tasks" +# frozen_string_literal: true + +require 'bundler/gem_tasks' require 'rake/testtask' require 'rdoc/task' desc 'Default: run tests for all ORMs.' -task :default => :test +task default: :test desc 'Run Devise tests for all ORMs.' task :pre_commit do @@ -22,6 +24,7 @@ Rake::TestTask.new(:test) do |t| t.libs << 'test' t.pattern = 'test/**/*_test.rb' t.verbose = true + t.warning = false end desc 'Generate documentation for Devise.' diff --git a/app/controllers/devise/confirmations_controller.rb b/app/controllers/devise/confirmations_controller.rb index 68014c92bd..39ff669be7 100644 --- a/app/controllers/devise/confirmations_controller.rb +++ b/app/controllers/devise/confirmations_controller.rb @@ -1,15 +1,18 @@ +# frozen_string_literal: true + class Devise::ConfirmationsController < DeviseController # GET /resource/confirmation/new def new - build_resource({}) + self.resource = resource_class.new end # POST /resource/confirmation def create self.resource = resource_class.send_confirmation_instructions(resource_params) + yield resource if block_given? if successfully_sent?(resource) - respond_with({}, :location => after_resending_confirmation_instructions_path_for(resource_name)) + respond_with({}, location: after_resending_confirmation_instructions_path_for(resource_name)) else respond_with(resource) end @@ -18,13 +21,14 @@ def create # GET /resource/confirmation?confirmation_token=abcdef def show self.resource = resource_class.confirm_by_token(params[:confirmation_token]) + yield resource if block_given? if resource.errors.empty? - set_flash_message(:notice, :confirmed) if is_navigational_format? - sign_in(resource_name, resource) + set_flash_message!(:notice, :confirmed) respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) } else - respond_with_navigational(resource.errors, :status => :unprocessable_entity){ render :new } + # 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 @@ -32,12 +36,19 @@ def show # The path used after resending confirmation instructions. def after_resending_confirmation_instructions_path_for(resource_name) - new_session_path(resource_name) + is_navigational_format? ? new_session_path(resource_name) : '/' end # The path used after confirmation. def after_confirmation_path_for(resource_name, resource) - after_sign_in_path_for(resource) + if signed_in?(resource_name) + signed_in_root_path(resource) + else + new_session_path(resource_name) + end end + def translation_scope + 'devise.confirmations' + end end diff --git a/app/controllers/devise/omniauth_callbacks_controller.rb b/app/controllers/devise/omniauth_callbacks_controller.rb index 14b5ee1c5c..a9a2c30ea7 100644 --- a/app/controllers/devise/omniauth_callbacks_controller.rb +++ b/app/controllers/devise/omniauth_callbacks_controller.rb @@ -1,30 +1,36 @@ +# frozen_string_literal: true + class Devise::OmniauthCallbacksController < DeviseController - prepend_before_filter { request.env["devise.skip_timeout"] = true } + prepend_before_action { request.env["devise.skip_timeout"] = true } def passthru - render :status => 404, :text => "Not found. Authentication passthru." + render status: 404, plain: "Not found. Authentication 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 protected def failed_strategy - env["omniauth.error.strategy"] + request.respond_to?(:get_header) ? request.get_header("omniauth.error.strategy") : request.env["omniauth.error.strategy"] end def failure_message - exception = env["omniauth.error"] + exception = request.respond_to?(:get_header) ? request.get_header("omniauth.error") : request.env["omniauth.error"] error = exception.error_reason if exception.respond_to?(:error_reason) error ||= exception.error if exception.respond_to?(:error) - error ||= env["omniauth.error.type"].to_s + error ||= (request.respond_to?(:get_header) ? request.get_header("omniauth.error.type") : request.env["omniauth.error.type"]).to_s error.to_s.humanize if error end def after_omniauth_failure_path_for(scope) new_session_path(scope) end + + def translation_scope + 'devise.omniauth_callbacks' + end end diff --git a/app/controllers/devise/passwords_controller.rb b/app/controllers/devise/passwords_controller.rb index 46b323d23c..3af1f864b7 100644 --- a/app/controllers/devise/passwords_controller.rb +++ b/app/controllers/devise/passwords_controller.rb @@ -1,19 +1,22 @@ +# frozen_string_literal: true + class Devise::PasswordsController < DeviseController - prepend_before_filter :require_no_authentication + prepend_before_action :require_no_authentication # Render the #edit only if coming from a reset password email link - append_before_filter :assert_reset_token_passed, :only => :edit + append_before_action :assert_reset_token_passed, only: :edit # GET /resource/password/new def new - build_resource({}) + self.resource = resource_class.new end # POST /resource/password def create self.resource = resource_class.send_reset_password_instructions(resource_params) + yield resource if block_given? if successfully_sent?(resource) - respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name)) + respond_with({}, location: after_sending_reset_password_instructions_path_for(resource_name)) else respond_with(resource) end @@ -22,35 +25,59 @@ def create # GET /resource/password/edit?reset_password_token=abcdef def edit self.resource = resource_class.new + set_minimum_password_length resource.reset_password_token = params[:reset_password_token] end # PUT /resource/password def update self.resource = resource_class.reset_password_by_token(resource_params) + yield resource if block_given? if resource.errors.empty? - flash_message = resource.active_for_authentication? ? :updated : :updated_not_active - set_flash_message(:notice, flash_message) if is_navigational_format? - sign_in(resource_name, resource) - respond_with resource, :location => after_sign_in_path_for(resource) + resource.unlock_access! if unlockable?(resource) + if resource_class.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) + end + respond_with resource, location: after_resetting_password_path_for(resource) else + set_minimum_password_length respond_with resource end end protected + def after_resetting_password_path_for(resource) + resource_class.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 def after_sending_reset_password_instructions_path_for(resource_name) - new_session_path(resource_name) + new_session_path(resource_name) if is_navigational_format? end # Check if a reset_password_token is provided in the request def assert_reset_token_passed if params[:reset_password_token].blank? - set_flash_message(:error, :no_token) + set_flash_message(:alert, :no_token) redirect_to new_session_path(resource_name) end end + + # Check if proper Lockable module methods are present & unlock strategy + # allows to unlock resource on password reset + def unlockable?(resource) + resource.respond_to?(:unlock_access!) && + resource.respond_to?(:unlock_strategy_enabled?) && + resource.unlock_strategy_enabled?(:email) + end + + def translation_scope + 'devise.passwords' + end end diff --git a/app/controllers/devise/registrations_controller.rb b/app/controllers/devise/registrations_controller.rb index 6c0ede94d2..f1292b4d90 100644 --- a/app/controllers/devise/registrations_controller.rb +++ b/app/controllers/devise/registrations_controller.rb @@ -1,29 +1,36 @@ +# frozen_string_literal: true + class Devise::RegistrationsController < DeviseController - prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ] - prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy] + prepend_before_action :require_no_authentication, only: [:new, :create, :cancel] + prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy] + prepend_before_action :set_minimum_password_length, only: [:new, :edit] # GET /resource/sign_up def new - resource = build_resource({}) + build_resource + yield resource if block_given? respond_with resource end # POST /resource def create - build_resource + build_resource(sign_up_params) - if resource.save + resource.save + yield resource if block_given? + if resource.persisted? if resource.active_for_authentication? - set_flash_message :notice, :signed_up if is_navigational_format? - sign_in(resource_name, resource) - respond_with resource, :location => after_sign_up_path_for(resource) + set_flash_message! :notice, :signed_up + sign_up(resource_name, resource) + respond_with resource, location: after_sign_up_path_for(resource) else - set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format? - expire_session_data_after_sign_in! - respond_with resource, :location => after_inactive_sign_up_path_for(resource) + set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}" + expire_data_after_sign_in! + respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource + set_minimum_password_length respond_with resource end end @@ -40,16 +47,16 @@ def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email) - if resource.update_with_password(resource_params) - if is_navigational_format? - flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ? - :update_needs_confirmation : :updated - set_flash_message :notice, flash_key - end - sign_in resource_name, resource, :bypass => true - respond_with resource, :location => after_update_path_for(resource) + resource_updated = update_resource(resource, account_update_params) + yield resource if block_given? + if resource_updated + 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 + set_minimum_password_length respond_with resource end end @@ -58,8 +65,9 @@ def update def destroy resource.destroy Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name) - set_flash_message :notice, :destroyed if is_navigational_format? - respond_with_navigational(resource){ redirect_to after_sign_out_path_for(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), status: Devise.responder.redirect_status } end # GET /resource/cancel @@ -68,7 +76,7 @@ def destroy # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. def cancel - expire_session_data_after_sign_in! + expire_data_after_sign_in! redirect_to new_registration_path(resource_name) end @@ -80,34 +88,81 @@ def update_needs_confirmation?(resource, previous) 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) + resource.update_with_password(params) + end + # Build a devise resource passing in the session. Useful to move # temporary session data to the newly created user. - def build_resource(hash=nil) - hash ||= resource_params || {} + 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 + # RegistrationsController. + def sign_up(resource_name, resource) + sign_in(resource_name, resource) + end + # 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 # this method in your own RegistrationsController. def after_inactive_sign_up_path_for(resource) - respond_to?(:root_path) ? root_path : "/" + scope = Devise::Mapping.find_scope!(resource) + router_name = Devise.mappings[scope].router_name + context = router_name ? send(router_name) : self + context.respond_to?(:root_path) ? context.root_path : "/" end # 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. def authenticate_scope! - send(:"authenticate_#{resource_name}!", :force => true) + send(:"authenticate_#{resource_name}!", force: true) self.resource = send(:"current_#{resource_name}") end + + def sign_up_params + devise_parameter_sanitizer.sanitize(:sign_up) + end + + def account_update_params + devise_parameter_sanitizer.sanitize(:account_update) + end + + 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 sign_in_after_change_password? + return true if account_update_params[:password].blank? + + Devise.sign_in_after_change_password + end end diff --git a/app/controllers/devise/sessions_controller.rb b/app/controllers/devise/sessions_controller.rb index 2cbd671b33..41b74f39cb 100644 --- a/app/controllers/devise/sessions_controller.rb +++ b/app/controllers/devise/sessions_controller.rb @@ -1,50 +1,83 @@ +# frozen_string_literal: true + class Devise::SessionsController < DeviseController - prepend_before_filter :require_no_authentication, :only => [ :new, :create ] - prepend_before_filter :allow_params_authentication!, :only => :create - prepend_before_filter { request.env["devise.skip_timeout"] = true } + 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 } # GET /resource/sign_in def new - resource = build_resource(nil, :unsafe => true) + self.resource = resource_class.new(sign_in_params) clean_up_passwords(resource) + yield resource if block_given? respond_with(resource, serialize_options(resource)) end # POST /resource/sign_in def create - resource = warden.authenticate!(auth_options) - set_flash_message(:notice, :signed_in) if is_navigational_format? + self.resource = warden.authenticate!(auth_options) + set_flash_message!(:notice, :signed_in) sign_in(resource_name, resource) - respond_with resource, :location => after_sign_in_path_for(resource) + yield resource if block_given? + respond_with resource, location: after_sign_in_path_for(resource) end # DELETE /resource/sign_out def destroy - redirect_path = after_sign_out_path_for(resource_name) signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)) - set_flash_message :notice, :signed_out if signed_out && is_navigational_format? - - # We actually need to hardcode this as Rails default responder doesn't - # support returning empty response on GET request - respond_to do |format| - format.any(*navigational_formats) { redirect_to redirect_path } - format.all do - head :no_content - end - end + set_flash_message! :notice, :signed_out if signed_out + yield if block_given? + respond_to_on_destroy(non_navigational_status: :no_content) end protected + def sign_in_params + devise_parameter_sanitizer.sanitize(:sign_in) + end + def serialize_options(resource) methods = resource_class.authentication_keys.dup methods = methods.keys if methods.is_a?(Hash) methods << :password if resource.respond_to?(:password) - { :methods => methods, :only => [:password] } + { methods: methods, only: [:password] } end def auth_options - { :scope => resource_name, :recall => "#{controller_path}#new" } + { scope: resource_name, recall: "#{controller_path}#new", locale: I18n.locale } end -end + def translation_scope + 'devise.sessions' + end + + private + + # Check if there is no signed in user before doing the sign out. + # + # If there is no signed in user, it will set the flash message and redirect + # to the after_sign_out path. + def verify_signed_out_user + if all_signed_out? + set_flash_message! :notice, :already_signed_out + + respond_to_on_destroy(non_navigational_status: :unauthorized) + end + end + + def all_signed_out? + users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) } + + users.all?(&:blank?) + end + + 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 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 45f6b2c1d7..8cff126c96 100644 --- a/app/controllers/devise/unlocks_controller.rb +++ b/app/controllers/devise/unlocks_controller.rb @@ -1,17 +1,20 @@ +# frozen_string_literal: true + class Devise::UnlocksController < DeviseController - prepend_before_filter :require_no_authentication + prepend_before_action :require_no_authentication # GET /resource/unlock/new def new - build_resource({}) + self.resource = resource_class.new end # POST /resource/unlock def create self.resource = resource_class.send_unlock_instructions(resource_params) + yield resource if block_given? if successfully_sent?(resource) - respond_with({}, :location => after_sending_unlock_instructions_path_for(resource)) + respond_with({}, location: after_sending_unlock_instructions_path_for(resource)) else respond_with(resource) end @@ -20,12 +23,14 @@ def create # GET /resource/unlock?unlock_token=abcdef def show self.resource = resource_class.unlock_access_by_token(params[:unlock_token]) + yield resource if block_given? if resource.errors.empty? - set_flash_message :notice, :unlocked if is_navigational_format? + set_flash_message! :notice, :unlocked respond_with_navigational(resource){ redirect_to after_unlock_path_for(resource) } else - respond_with_navigational(resource.errors, :status => :unprocessable_entity){ render :new } + # 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 @@ -33,12 +38,15 @@ def show # The path used after sending unlock password instructions def after_sending_unlock_instructions_path_for(resource) - new_session_path(resource) + new_session_path(resource) if is_navigational_format? end # The path used after unlocking the resource def after_unlock_path_for(resource) - new_session_path(resource) + new_session_path(resource) if is_navigational_format? end + def translation_scope + 'devise.unlocks' + end end diff --git a/app/controllers/devise_controller.rb b/app/controllers/devise_controller.rb index 38b7be9ad0..1c3b41626d 100644 --- a/app/controllers/devise_controller.rb +++ b/app/controllers/devise_controller.rb @@ -1,16 +1,52 @@ +# frozen_string_literal: true + # All Devise controllers are inherited from here. class DeviseController < Devise.parent_controller.constantize include Devise::Controllers::ScopedViews - helper DeviseHelper + if respond_to?(:helper) + helper DeviseHelper + end + + if respond_to?(:helper_method) + helpers = %w(resource scope_name resource_name signed_in_resource + resource_class resource_params devise_mapping) + helper_method(*helpers) + end - helpers = %w(resource scope_name resource_name signed_in_resource - resource_class resource_params devise_mapping) - hide_action *helpers - helper_method *helpers + prepend_before_action :assert_is_devise_resource! + self.responder = Devise.responder + respond_to :html if mimes_for_respond_to.empty? - prepend_before_filter :assert_is_devise_resource! - respond_to *Mime::SET.map(&:to_sym) if mimes_for_respond_to.empty? + # Override prefixes to consider the scoped view. + # Notice we need to check for the request due to a bug in + # Action Controller tests that forces _prefixes to be + # loaded before even having a request object. + # + # 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 + ["#{devise_mapping.scoped_path}/#{controller_name}"] + super + else + super + 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 def resource @@ -28,13 +64,9 @@ def resource_class devise_mapping.to end - def resource_params - params[resource_name] - end - # Returns a signed in resource from session (if one exists) def signed_in_resource - warden.authenticate(:scope => resource_name) + warden.authenticate(scope: resource_name) end # Attempt to find the mapped route for devise based on request path @@ -42,22 +74,6 @@ def devise_mapping @devise_mapping ||= request.env["devise.mapping"] end - # Override prefixes to consider the scoped view. - # Notice we need to check for the request due to a bug in - # Action Controller tests that forces _prefixes to be - # loaded before even having a request object. - def _prefixes #:nodoc: - @_prefixes ||= if self.class.scoped_views? && request && devise_mapping - super.unshift("#{devise_mapping.scoped_path}/#{controller_name}") - else - super - end - end - - hide_action :_prefixes - - protected - # Checks whether it's a devise mapped resource or not. def assert_is_devise_resource! #:nodoc: unknown_action! <<-MESSAGE unless devise_mapping @@ -67,7 +83,7 @@ def assert_is_devise_resource! #:nodoc: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do - match "/some/route" => "some_devise_controller" + get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. @@ -93,41 +109,24 @@ def resource=(new_resource) instance_variable_set(:"@#{resource_name}", new_resource) end - # Build a devise resource. - # Assignment bypasses attribute protection when :unsafe option is passed - def build_resource(hash = nil, options = {}) - hash ||= resource_params || {} - - if options[:unsafe] - self.resource = resource_class.new.tap do |resource| - hash.each do |key, value| - setter = :"#{key}=" - resource.send(setter, value) if resource.respond_to?(setter) - end - end - else - self.resource = resource_class.new(hash) - end - end - - # Helper for use in before_filters where no authentication is required. + # Helper for use in before_actions where no authentication is required. # # Example: - # before_filter :require_no_authentication, :only => :new + # before_action :require_no_authentication, only: :new def require_no_authentication assert_is_devise_resource! return unless is_navigational_format? no_input = devise_mapping.no_input_strategies authenticated = if no_input.present? - args = no_input.dup.push :scope => resource_name + args = no_input.dup.push scope: resource_name warden.authenticate?(*args) else warden.authenticated?(resource_name) 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 @@ -144,14 +143,17 @@ def successfully_sent?(resource) end if notice - set_flash_message :notice, notice if is_navigational_format? + set_flash_message! :notice, notice true end end # Sets the flash message with :key, using I18n. By default you are able - # to setup your messages using specific resource scope, and if no one is - # found we look to default scope. + # to set up your messages using specific resource scope, and if no message is + # found we look to the default scope. Set the "now" options key to a true + # value to populate the flash.now hash in lieu of the default flash hash (so + # the flash message will be available to the current action instead of the + # next action). # Example (i18n locale file): # # en: @@ -163,13 +165,47 @@ def successfully_sent?(resource) # # Please refer to README or en.yml locale file to check what messages are # available. - def set_flash_message(key, kind, options={}) - options[:scope] = "devise.#{controller_name}" + def set_flash_message(key, kind, options = {}) + message = find_message(kind, options) + if options[:now] + flash.now[key] = message if message.present? + else + flash[key] = message if message.present? + end + end + + # Sets flash message if is_flashing_format? equals true + def set_flash_message!(key, kind, options = {}) + if is_flashing_format? + set_flash_message(key, kind, options) + end + end + + # Sets minimum password length to show to user + def set_minimum_password_length + if devise_mapping.validatable? + @minimum_password_length = resource_class.password_length.min + end + end + + def devise_i18n_options(options) + options + end + + # Get message for given + def find_message(kind, options = {}) + options[:scope] ||= translation_scope options[:default] = Array(options[:default]).unshift(kind.to_sym) options[:resource_name] = resource_name - options = devise_i18n_options(options) if respond_to?(:devise_i18n_options, true) - message = I18n.t("#{resource_name}.#{kind}", options) - flash[key] = message if message.present? + options = devise_i18n_options(options) + I18n.t("#{options[:resource_name]}.#{kind}", **options) + end + + # Controllers inheriting DeviseController are advised to override this + # method so that other controllers inheriting from them would use + # existing translations. + def translation_scope + "devise.#{controller_name}" end def clean_up_passwords(object) @@ -182,11 +218,9 @@ def respond_with_navigational(*args, &block) end end - def request_format - @request_format ||= request.format.try(:ref) + def resource_params + params.fetch(resource_name, {}) end - def is_navigational_format? - Devise.navigational_formats.include?(request_format) - end + ActiveSupport.run_load_hooks(:devise_controller, self) end diff --git a/app/helpers/devise_helper.rb b/app/helpers/devise_helper.rb index cfcbc82181..0bfcb06308 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 df07e0f178..e617edcd0b 100644 --- a/app/mailers/devise/mailer.rb +++ b/app/mailers/devise/mailer.rb @@ -1,15 +1,30 @@ -class Devise::Mailer < ::ActionMailer::Base - include Devise::Mailers::Helpers +# frozen_string_literal: true - def confirmation_instructions(record) - devise_mail(record, :confirmation_instructions) - end +if defined?(ActionMailer) + class Devise::Mailer < Devise.parent_mailer.constantize + include Devise::Mailers::Helpers - def reset_password_instructions(record) - devise_mail(record, :reset_password_instructions) - end + def confirmation_instructions(record, token, opts = {}) + @token = token + devise_mail(record, :confirmation_instructions, opts) + end + + def reset_password_instructions(record, token, opts = {}) + @token = token + devise_mail(record, :reset_password_instructions, opts) + end + + def unlock_instructions(record, token, opts = {}) + @token = token + devise_mail(record, :unlock_instructions, opts) + end + + def email_changed(record, opts = {}) + devise_mail(record, :email_changed, opts) + end - def unlock_instructions(record) - devise_mail(record, :unlock_instructions) + def password_change(record, opts = {}) + devise_mail(record, :password_change, opts) + end end end diff --git a/app/views/devise/_links.erb b/app/views/devise/_links.erb deleted file mode 100644 index 44416761d9..0000000000 --- a/app/views/devise/_links.erb +++ /dev/null @@ -1,3 +0,0 @@ -<% ActiveSupport::Deprecation.warn "Rendering partials devise/_links.erb is deprecated" \ - "please use devise/shared/_links.erb instead."%> -<%= render "shared/links" %> diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb index 9c27eb72ca..3c21122e10 100644 --- a/app/views/devise/confirmations/new.html.erb +++ b/app/views/devise/confirmations/new.html.erb @@ -1,12 +1,16 @@

Resend confirmation instructions

-<%= form_for(resource, :as => resource_name, :url => confirmation_path(resource_name), :html => { :method => :post }) do |f| %> - <%= devise_error_messages! %> +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= 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", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %>

+
-
<%= f.submit "Resend confirmation instructions" %>
+
+ <%= f.submit "Resend confirmation instructions" %> +
<% end %> <%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb index a5c4585e8d..dc55f64f69 100644 --- a/app/views/devise/mailer/confirmation_instructions.html.erb +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -1,5 +1,5 @@ -

Welcome <%= @resource.email %>!

+

Welcome <%= @email %>!

You can confirm your account email through the link below:

-

<%= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token => @resource.confirmation_token) %>

+

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/email_changed.html.erb b/app/views/devise/mailer/email_changed.html.erb new file mode 100644 index 0000000000..32f4ba8038 --- /dev/null +++ b/app/views/devise/mailer/email_changed.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @email %>!

+ +<% if @resource.try(:unconfirmed_email?) %> +

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

+<% else %> +

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

+<% end %> diff --git a/app/views/devise/mailer/password_change.html.erb b/app/views/devise/mailer/password_change.html.erb new file mode 100644 index 0000000000..b41daf476a --- /dev/null +++ b/app/views/devise/mailer/password_change.html.erb @@ -0,0 +1,3 @@ +

Hello <%= @resource.email %>!

+ +

We're contacting you to notify you that your password has been changed.

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb index ae9e888abb..f667dc12fe 100644 --- a/app/views/devise/mailer/reset_password_instructions.html.erb +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -1,8 +1,8 @@

Hello <%= @resource.email %>!

-

Someone has requested a link to change your password, and you can do this through the link below.

+

Someone has requested a link to change your password. You can do this through the link below.

-

<%= link_to 'Change my password', edit_password_url(@resource, :reset_password_token => @resource.reset_password_token) %>

+

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

If you didn't request this, please ignore this email.

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb index 2263c21952..41e148bf2a 100644 --- a/app/views/devise/mailer/unlock_instructions.html.erb +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -1,7 +1,7 @@

Hello <%= @resource.email %>!

-

Your account has been locked due to an excessive amount of unsuccessful sign in attempts.

+

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

Click the link below to unlock your account:

-

<%= link_to 'Unlock my account', unlock_url(@resource, :unlock_token => @resource.unlock_token) %>

+

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb index 34a49604a8..3f1dbc72e0 100644 --- a/app/views/devise/passwords/edit.html.erb +++ b/app/views/devise/passwords/edit.html.erb @@ -1,16 +1,25 @@

Change your password

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

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

+ <% if @minimum_password_length %> +

(<%= @minimum_password_length %> characters minimum)

+ <% end %> +

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

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

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

+

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

+
-
<%= f.submit "Change my password" %>
+
+ <%= f.submit "Change my password" %> +
<% end %> <%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb index 5a400df1fa..bea7ad1302 100644 --- a/app/views/devise/passwords/new.html.erb +++ b/app/views/devise/passwords/new.html.erb @@ -1,12 +1,16 @@

Forgot your password?

-<%= form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :post }) do |f| %> - <%= devise_error_messages! %> +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= 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 %> <%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb index 1f6bbf6bf6..19bb019bc7 100644 --- a/app/views/devise/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -1,25 +1,42 @@

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! %> - -
<%= f.label :email %>
- <%= f.email_field :email, :autofocus => true %>
- -
<%= f.label :password %> (leave blank if you don't want to change it)
- <%= f.password_field :password, :autocomplete => "off" %>
- -
<%= f.label :password_confirmation %>
- <%= f.password_field :password_confirmation %>
- -
<%= f.label :current_password %> (we need your current password to confirm your changes)
- <%= f.password_field :current_password %>
- -
<%= f.submit "Update" %>
+<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+

<%= f.label :email %>

+

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

+
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
+

<%= 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

+ <% end %> +
+ +
+

<%= 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: "current-password" %>

+
+ +
+ <%= f.submit "Update" %> +
<% end %>

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/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index 3f189d46c7..03f48fbb60 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -1,18 +1,29 @@

Sign up

-<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> - <%= devise_error_messages! %> +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= 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.password_field :password %>
+
+

<%= f.label :password %>

+ <% if @minimum_password_length %> +

(<%= @minimum_password_length %> characters minimum)

+ <% end %> +

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

+
-
<%= f.label :password_confirmation %>
- <%= f.password_field :password_confirmation %>
+
+

<%= f.label :password_confirmation %>

+

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

+
-
<%= f.submit "Sign up" %>
+
+ <%= f.submit "Sign up" %> +
<% end %> <%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb index f9bc2c16fe..6eeb9fc763 100644 --- a/app/views/devise/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -1,17 +1,26 @@ -

Sign in

+

Log in

-<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %> -
<%= f.label :email %>
- <%= f.email_field :email, :autofocus => true %>
+<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
+

<%= f.label :email %>

+

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

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

<%= f.label :password %>

+

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

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

<%= f.check_box :remember_me %>

+

<%= f.label :remember_me %>

+
+ <% end %> -
<%= f.submit "Sign in" %>
+
+ <%= f.submit "Log in" %> +
<% end %> <%= render "devise/shared/links" %> 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 0000000000..8c9c171147 --- /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) + %> +

+ +
+<% end %> diff --git a/app/views/devise/shared/_links.erb b/app/views/devise/shared/_links.erb deleted file mode 100644 index eab783a4c9..0000000000 --- a/app/views/devise/shared/_links.erb +++ /dev/null @@ -1,25 +0,0 @@ -<%- if controller_name != 'sessions' %> - <%= link_to "Sign in", new_session_path(resource_name) %>
-<% end -%> - -<%- if devise_mapping.registerable? && controller_name != 'registrations' %> - <%= link_to "Sign up", new_registration_path(resource_name) %>
-<% end -%> - -<%- if devise_mapping.recoverable? && controller_name != 'passwords' %> - <%= 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 -%> - -<%- 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 -%> - -<%- if devise_mapping.omniauthable? %> - <%- resource_class.omniauth_providers.each do |provider| %> - <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %>
- <% end -%> -<% end -%> \ No newline at end of file diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb new file mode 100644 index 0000000000..21cf422d51 --- /dev/null +++ b/app/views/devise/shared/_links.html.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> +

<%= 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 %> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> +

<%= 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 %> + +<%- 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 %> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> +

<%= 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 020787f8ea..6b68d724cb 100644 --- a/app/views/devise/unlocks/new.html.erb +++ b/app/views/devise/unlocks/new.html.erb @@ -1,12 +1,16 @@

Resend unlock instructions

-<%= form_for(resource, :as => resource_name, :url => unlock_path(resource_name), :html => { :method => :post }) do |f| %> - <%= devise_error_messages! %> +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= 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 "Resend unlock instructions" %>
+
+ <%= f.submit "Resend unlock instructions" %> +
<% end %> <%= render "devise/shared/links" %> diff --git a/bin/test b/bin/test new file mode 100755 index 0000000000..28141f2c77 --- /dev/null +++ b/bin/test @@ -0,0 +1,12 @@ +#!/usr/bin/env ruby +$: << File.expand_path(File.expand_path('../../test', __FILE__)) + +require 'bundler/setup' +require 'rails/test_unit/runner' +require 'rails/test_unit/reporter' +require 'rails/test_unit/line_filtering' + +Rails::TestUnitReporter.executable = 'bin/test' + +Rails::TestUnit::Runner.parse_options(ARGV) +Rails::TestUnit::Runner.run(ARGV) diff --git a/config/locales/en.yml b/config/locales/en.yml index a533f90ca2..260e1c4ba6 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,59 +1,65 @@ -# Additional translations at https://github.com/plataformatec/devise/wiki/I18n +# Additional translations at https://github.com/heartcombo/devise/wiki/I18n en: + devise: + confirmations: + confirmed: "Your email address has been successfully confirmed." + send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid %{authentication_keys} or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account is locked." + not_found_in_database: "Invalid %{authentication_keys} or password." + timeout: "Your session expired. Please sign in again to continue." + unauthenticated: "You need to sign in or sign up before continuing." + unconfirmed: "You have to confirm your email address before continuing." + mailer: + confirmation_instructions: + subject: "Confirmation instructions" + reset_password_instructions: + subject: "Reset password instructions" + unlock_instructions: + subject: "Unlock instructions" + email_changed: + subject: "Email Changed" + password_change: + subject: "Password Changed" + omniauth_callbacks: + failure: "Could not authenticate you from %{kind} because \"%{reason}\"." + success: "Successfully authenticated from %{kind} account." + passwords: + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." + updated: "Your password has been changed successfully. You are now signed in." + updated_not_active: "Your password has been changed successfully." + registrations: + destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." + signed_up: "Welcome! You have signed up successfully." + signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." + signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." + signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the 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." + already_signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." + unlocked: "Your account has been unlocked successfully. Please sign in to continue." errors: messages: + already_confirmed: "was already confirmed, please try signing in" + confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" expired: "has expired, please request a new one" not_found: "not found" - already_confirmed: "was already confirmed, please try signing in" not_locked: "was not locked" not_saved: one: "1 error prohibited this %{resource} from being saved:" other: "%{count} errors prohibited this %{resource} from being saved:" - confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" - - devise: - failure: - already_authenticated: 'You are already signed in.' - unauthenticated: 'You need to sign in or sign up before continuing.' - unconfirmed: 'You have to confirm your account before continuing.' - locked: 'Your account is locked.' - invalid: 'Invalid email or password.' - invalid_token: 'Invalid authentication token.' - timeout: 'Your session expired, please sign in again to continue.' - inactive: 'Your account was not activated yet.' - sessions: - signed_in: 'Signed in successfully.' - signed_out: 'Signed out successfully.' - passwords: - send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.' - updated: 'Your password was changed successfully. You are now signed in.' - updated_not_active: 'Your password was changed successfully.' - send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." - no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." - confirmations: - send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.' - send_paranoid_instructions: 'If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes.' - confirmed: 'Your account was successfully confirmed. You are now signed in.' - registrations: - signed_up: 'Welcome! You have signed up successfully.' - signed_up_but_unconfirmed: 'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.' - signed_up_but_inactive: 'You have signed up successfully. However, we could not sign you in because your account is not yet activated.' - signed_up_but_locked: 'You have signed up successfully. However, we could not sign you in because your account is locked.' - updated: 'You updated your account successfully.' - update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." - destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.' - unlocks: - send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.' - unlocked: 'Your account has been unlocked successfully. Please sign in to continue.' - send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.' - omniauth_callbacks: - success: 'Successfully authenticated from %{kind} account.' - failure: 'Could not authenticate you from %{kind} because "%{reason}".' - mailer: - confirmation_instructions: - subject: 'Confirmation instructions' - reset_password_instructions: - subject: 'Reset password instructions' - unlock_instructions: - subject: 'Unlock Instructions' diff --git a/devise.gemspec b/devise.gemspec index 4df95625dd..1caa6aeb39 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" @@ -6,20 +8,28 @@ Gem::Specification.new do |s| s.name = "devise" s.version = Devise::VERSION.dup 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 = "http://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.rubyforge_project = "devise" - - 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.7.0' - s.add_dependency("warden", "~> 1.2.1") + s.add_dependency("warden", "~> 1.2.3") s.add_dependency("orm_adapter", "~> 0.1") - s.add_dependency("bcrypt-ruby", "~> 3.0") - s.add_dependency("railties", "~> 3.1") + s.add_dependency("bcrypt", "~> 3.0") + s.add_dependency("railties", ">= 7.0") + s.add_dependency("responders") end diff --git a/devise.png b/devise.png new file mode 100644 index 0000000000..d803835918 Binary files /dev/null and b/devise.png differ diff --git a/gemfiles/Gemfile-rails-7-0 b/gemfiles/Gemfile-rails-7-0 new file mode 100644 index 0000000000..a397d04fcf --- /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 0000000000..41caefa805 --- /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 0000000000..2fa2804d54 --- /dev/null +++ b/gemfiles/Gemfile-rails-7-2 @@ -0,0 +1,32 @@ +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", 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 0000000000..23954ff580 --- /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 0000000000..57ed95a1ba --- /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-3.1.x b/gemfiles/Gemfile.rails-3.1.x deleted file mode 100644 index b881657f1a..0000000000 --- a/gemfiles/Gemfile.rails-3.1.x +++ /dev/null @@ -1,35 +0,0 @@ -source "http://rubygems.org" - -gem "devise", :path => ".." - -gem "rails", "~> 3.1.0" -gem "omniauth", "~> 1.0.0" -gem "omniauth-oauth2", "~> 1.0.0" -gem "rdoc" - -group :test do - gem "omniauth-facebook" - gem "omniauth-openid", "~> 1.0.1" - gem "webrat", "0.7.2", :require => false - gem "mocha", :require => false - - platforms :mri_18 do - gem "ruby-debug", ">= 0.10.3" - end -end - -platforms :jruby do - gem "activerecord-jdbc-adapter" - gem "activerecord-jdbcsqlite3-adapter" - gem "jruby-openssl" -end - -platforms :ruby do - gem "sqlite3" - - group :mongoid do - gem "mongo", "~> 1.3.0" - gem "mongoid", "~> 2.0" - gem "bson_ext", "~> 1.3.0" - end -end diff --git a/gemfiles/Gemfile.rails-3.1.x.lock b/gemfiles/Gemfile.rails-3.1.x.lock deleted file mode 100644 index 1dd424e0ca..0000000000 --- a/gemfiles/Gemfile.rails-3.1.x.lock +++ /dev/null @@ -1,167 +0,0 @@ -PATH - remote: .. - specs: - devise (2.1.0.rc2) - bcrypt-ruby (~> 3.0) - orm_adapter (~> 0.0.7) - railties (~> 3.1) - warden (~> 1.1.1) - -GEM - remote: http://rubygems.org/ - specs: - actionmailer (3.1.4) - actionpack (= 3.1.4) - mail (~> 2.3.0) - actionpack (3.1.4) - activemodel (= 3.1.4) - activesupport (= 3.1.4) - builder (~> 3.0.0) - erubis (~> 2.7.0) - i18n (~> 0.6) - rack (~> 1.3.6) - rack-cache (~> 1.1) - rack-mount (~> 0.8.2) - rack-test (~> 0.6.1) - sprockets (~> 2.0.3) - activemodel (3.1.4) - activesupport (= 3.1.4) - builder (~> 3.0.0) - i18n (~> 0.6) - activerecord (3.1.4) - activemodel (= 3.1.4) - activesupport (= 3.1.4) - arel (~> 2.2.3) - tzinfo (~> 0.3.29) - activeresource (3.1.4) - activemodel (= 3.1.4) - activesupport (= 3.1.4) - activesupport (3.1.4) - multi_json (~> 1.0) - addressable (2.2.7) - arel (2.2.3) - bcrypt-ruby (3.0.1) - bson (1.5.2) - bson_ext (1.3.1) - builder (3.0.0) - columnize (0.3.6) - erubis (2.7.0) - faraday (0.7.6) - addressable (~> 2.2) - multipart-post (~> 1.1) - rack (~> 1.1) - hashie (1.2.0) - hike (1.2.1) - i18n (0.6.0) - json (1.7.0) - linecache (0.46) - rbx-require-relative (> 0.0.4) - mail (2.3.3) - i18n (>= 0.4.0) - mime-types (~> 1.16) - treetop (~> 1.4.8) - metaclass (0.0.1) - mime-types (1.18) - mocha (0.10.4) - metaclass (~> 0.0.1) - mongo (1.3.1) - bson (>= 1.3.1) - mongoid (2.4.4) - activemodel (~> 3.1) - mongo (~> 1.3) - tzinfo (~> 0.3.22) - multi_json (1.3.4) - multipart-post (1.1.5) - nokogiri (1.5.0) - oauth2 (0.5.2) - faraday (~> 0.7) - multi_json (~> 1.0) - omniauth (1.0.2) - hashie (~> 1.2) - rack - omniauth-facebook (1.2.0) - omniauth-oauth2 (~> 1.0.0) - omniauth-oauth2 (1.0.0) - oauth2 (~> 0.5.0) - omniauth (~> 1.0) - omniauth-openid (1.0.1) - omniauth (~> 1.0) - rack-openid (~> 1.3.1) - orm_adapter (0.0.7) - polyglot (0.3.3) - rack (1.3.6) - rack-cache (1.2) - rack (>= 0.4) - rack-mount (0.8.3) - rack (>= 1.0.0) - rack-openid (1.3.1) - rack (>= 1.1.0) - ruby-openid (>= 2.1.8) - rack-ssl (1.3.2) - rack - rack-test (0.6.1) - rack (>= 1.0) - rails (3.1.4) - actionmailer (= 3.1.4) - actionpack (= 3.1.4) - activerecord (= 3.1.4) - activeresource (= 3.1.4) - activesupport (= 3.1.4) - bundler (~> 1.0) - railties (= 3.1.4) - railties (3.1.4) - actionpack (= 3.1.4) - activesupport (= 3.1.4) - rack-ssl (~> 1.3.2) - rake (>= 0.8.7) - rdoc (~> 3.4) - thor (~> 0.14.6) - rake (0.9.2.2) - rbx-require-relative (0.0.5) - rdoc (3.12) - json (~> 1.4) - ruby-debug (0.10.4) - columnize (>= 0.1) - ruby-debug-base (~> 0.10.4.0) - ruby-debug-base (0.10.4) - linecache (>= 0.3) - ruby-openid (2.1.8) - sprockets (2.0.4) - hike (~> 1.2) - rack (~> 1.0) - tilt (~> 1.1, != 1.3.0) - sqlite3 (1.3.5) - thor (0.14.6) - tilt (1.3.3) - treetop (1.4.10) - polyglot - polyglot (>= 0.3.1) - tzinfo (0.3.33) - warden (1.1.1) - rack (>= 1.0) - webrat (0.7.2) - nokogiri (>= 1.2.0) - rack (>= 1.0) - rack-test (>= 0.5.3) - -PLATFORMS - ruby - -DEPENDENCIES - activerecord-jdbc-adapter - activerecord-jdbcsqlite3-adapter - bson_ext (~> 1.3.0) - devise! - jruby-openssl - mocha - mongo (~> 1.3.0) - mongoid (~> 2.0) - omniauth (~> 1.0.0) - omniauth-facebook - omniauth-oauth2 (~> 1.0.0) - omniauth-openid (~> 1.0.1) - rails (~> 3.1.0) - rdoc - ruby-debug (>= 0.10.3) - sqlite3 - webrat (= 0.7.2) diff --git a/guides/bug_report_templates/integration_test.rb b/guides/bug_report_templates/integration_test.rb new file mode 100644 index 0000000000..08b3401772 --- /dev/null +++ b/guides/bug_report_templates/integration_test.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +begin + require 'bundler/inline' +rescue LoadError => e + $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' + raise e +end + +gemfile(true) do + source 'https://rubygems.org' + # Activate the gem you are reporting the issue against. + gem 'rails', '~> 4.2.0' + gem 'devise', '~> 4.0' + gem 'sqlite3' + gem 'byebug' +end + +require 'rack/test' +require 'action_controller/railtie' +require 'active_record' +require 'devise/rails/routes' +require 'devise/rails/warden_compat' + +ActiveRecord::Base.establish_connection( adapter: :sqlite3, database: ':memory:') + +class DeviseCreateUsers < ActiveRecord::Migration + def change + create_table(:users) do |t| + t.string :email, null: false + t.string :encrypted_password, null: true + t.timestamps null: false + end + + end +end + +Devise.setup do |config| + require 'devise/orm/active_record' + config.secret_key = 'secret_key_base' +end + +class TestApp < Rails::Application + config.root = File.dirname(__FILE__) + config.session_store :cookie_store, key: 'cookie_store_key' + secrets.secret_token = 'secret_token' + secrets.secret_key_base = 'secret_key_base' + config.eager_load = false + + config.middleware.use Warden::Manager do |config| + Devise.warden_config = config + end + + config.logger = Logger.new($stdout) + Rails.logger = config.logger + +end + +Rails.application.initialize! + +DeviseCreateUsers.migrate(:up) + +class User < ActiveRecord::Base + devise :database_authenticatable +end + +Rails.application.routes.draw do + devise_for :users + + get '/' => 'test#index' +end + +class ApplicationController < ActionController::Base +end + +class TestController < ApplicationController + include Rails.application.routes.url_helpers + + before_action :authenticate_user! + + def index + render plain: 'Home' + end +end + +require 'minitest/autorun' + +class BugTest < ActionDispatch::IntegrationTest + include Rack::Test::Methods + include Warden::Test::Helpers + + def test_returns_success + Warden.test_mode! + + login_as User.create!(email: 'test@test.com', password: 'test123456', password_confirmation: 'test123456') + + get '/' + assert last_response.ok? + end + + private + + def app + Rails.application + end +end diff --git a/lib/devise.rb b/lib/devise.rb index 572f63fb97..8e0c85e77d 100644 --- a/lib/devise.rb +++ b/lib/devise.rb @@ -1,23 +1,36 @@ +# frozen_string_literal: true + require 'rails' require 'active_support/core_ext/numeric/time' require 'active_support/dependencies' require 'orm_adapter' require 'set' require 'securerandom' +require 'responders' module Devise - autoload :Delegator, 'devise/delegator' - autoload :FailureApp, 'devise/failure_app' - autoload :OmniAuth, 'devise/omniauth' - autoload :ParamFilter, 'devise/param_filter' - autoload :TestHelpers, 'devise/test_helpers' - autoload :TimeInflector, 'devise/time_inflector' + autoload :Delegator, 'devise/delegator' + 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 :TimeInflector, 'devise/time_inflector' + autoload :TokenGenerator, 'devise/token_generator' module Controllers - autoload :Helpers, 'devise/controllers/helpers' - autoload :Rememberable, 'devise/controllers/rememberable' - autoload :ScopedViews, 'devise/controllers/scoped_views' - autoload :UrlHelpers, 'devise/controllers/url_helpers' + 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' + autoload :UrlHelpers, 'devise/controllers/url_helpers' + end + + module Hooks + autoload :Proxy, 'devise/hooks/proxy' end module Mailers @@ -25,35 +38,48 @@ module Mailers end module Strategies - autoload :Base, 'devise/strategies/base' + autoload :Base, 'devise/strategies/base' autoload :Authenticatable, 'devise/strategies/authenticatable' end + module Test + autoload :ControllerHelpers, 'devise/test/controller_helpers' + autoload :IntegrationHelpers, 'devise/test/integration_helpers' + end + # Constants which holds devise configuration for extensions. Those should # not be modified by the "end user" (this is why they are constants). ALL = [] - CONTROLLERS = ActiveSupport::OrderedHash.new - ROUTES = ActiveSupport::OrderedHash.new - STRATEGIES = ActiveSupport::OrderedHash.new - URL_HELPERS = ActiveSupport::OrderedHash.new + CONTROLLERS = {} + ROUTES = {} + STRATEGIES = {} + URL_HELPERS = {} # Strategies that do not require user input. 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'] - # Custom domain for cookies. Not set by default + # Secret key used by the key generator + mattr_accessor :secret_key + @@secret_key = nil + + # Custom domain or key for cookies. Not set by default mattr_accessor :rememberable_options @@rememberable_options = {} - # The number of times to encrypt password. + # The number of times to hash the password. mattr_accessor :stretches - @@stretches = 10 + @@stretches = 12 + + # The default key used when authenticating over http auth. + mattr_accessor :http_authentication_key + @@http_authentication_key = nil # Keys used when authenticating a user. mattr_accessor :authentication_keys - @@authentication_keys = [ :email ] + @@authentication_keys = [:email] # Request keys used when authenticating a user. mattr_accessor :request_keys @@ -61,11 +87,11 @@ module Strategies # Keys that should be case-insensitive. mattr_accessor :case_insensitive_keys - @@case_insensitive_keys = [ :email ] + @@case_insensitive_keys = [:email] # Keys that should have whitespace stripped. mattr_accessor :strip_whitespace_keys - @@strip_whitespace_keys = [] + @@strip_whitespace_keys = [:email] # If http authentication is enabled by default. mattr_accessor :http_authenticatable @@ -83,11 +109,11 @@ module Strategies mattr_accessor :http_authentication_realm @@http_authentication_realm = "Application" - # Email regex used to validate email formats. It simply asserts that - # an one (and only one) @ exists in the given string. This is mainly - # to give user feedback and not to assert the e-mail validity. + # Email regex used to validate email formats. It asserts that there are no + # @ symbols or whitespaces in either the localpart or the domain, and that + # there is a single @ symbol separating the localpart and the domain. mattr_accessor :email_regexp - @@email_regexp = /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/ + @@email_regexp = /\A[^@\s]+@[^@\s]+\z/ # Range validation for password length mattr_accessor :password_length @@ -101,7 +127,12 @@ module Strategies mattr_accessor :extend_remember_period @@extend_remember_period = false + # If true, all the remember me tokens are going to be invalidated when the user signs out. + mattr_accessor :expire_all_remember_me_on_sign_out + @@expire_all_remember_me_on_sign_out = true + # Time interval you can access your account before confirming your account. + # nil - allows unconfirmed access for unlimited time mattr_accessor :allow_unconfirmed_access_for @@allow_unconfirmed_access_for = 0.days @@ -111,25 +142,28 @@ module Strategies # Defines which key will be used when confirming an account. mattr_accessor :confirmation_keys - @@confirmation_keys = [ :email ] + @@confirmation_keys = [:email] # Defines if email should be reconfirmable. - # False by default for backwards compatibility. mattr_accessor :reconfirmable - @@reconfirmable = false + @@reconfirmable = true # Time interval to timeout the user session without activity. mattr_accessor :timeout_in @@timeout_in = 30.minutes - # Authentication token expiration on timeout - mattr_accessor :expire_auth_token_on_timeout - @@expire_auth_token_on_timeout = false - - # Used to encrypt password. Please generate one with rake secret. + # Used to hash the password. Please generate one with rails secret. mattr_accessor :pepper @@pepper = nil + # Used to send notification to the original user email when their email is changed. + mattr_accessor :send_email_changed_notification + @@send_email_changed_notification = false + + # Used to enable sending notification to user when their password is changed. + mattr_accessor :send_password_change_notification + @@send_password_change_notification = false + # Scoped views. Since it relies on fallbacks to render default views, it's # turned off by default. mattr_accessor :scoped_views @@ -142,7 +176,7 @@ module Strategies # Defines which key will be used when locking and unlocking an account mattr_accessor :unlock_keys - @@unlock_keys = [ :email ] + @@unlock_keys = [:email] # Defines which strategy can be used to unlock an account. # Values: :email, :time, :both @@ -159,12 +193,16 @@ module Strategies # Defines which key will be used when recovering the password for an account mattr_accessor :reset_password_keys - @@reset_password_keys = [ :email ] + @@reset_password_keys = [:email] # Time interval you can reset your password with a reset password key mattr_accessor :reset_password_within @@reset_password_within = 6.hours + # When set to false, resetting a password does not automatically sign in a user + mattr_accessor :sign_in_after_reset_password + @@sign_in_after_reset_password = true + # The default scope which is used by warden. mattr_accessor :default_scope @@default_scope = nil @@ -173,17 +211,22 @@ module Strategies mattr_accessor :mailer_sender @@mailer_sender = nil - # Authentication token params key name of choice. E.g. /users/sign_in?some_key=... - mattr_accessor :token_authentication_key - @@token_authentication_key = :auth_token - # Skip session storage for the following strategies mattr_accessor :skip_session_storage - @@skip_session_storage = [] + @@skip_session_storage = [:http_auth] # 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 @@ -191,7 +234,7 @@ module Strategies # The default method used while signing out mattr_accessor :sign_out_via - @@sign_out_via = :get + @@sign_out_via = :delete # The parent controller all Devise controllers inherits from. # Defaults to ApplicationController. This should be set early @@ -199,38 +242,49 @@ module Strategies mattr_accessor :parent_controller @@parent_controller = "ApplicationController" + # The parent mailer all Devise mailers inherit from. + # Defaults to ActionMailer::Base. This should be set early + # in the initialization process and should be set to a string. + mattr_accessor :parent_mailer + @@parent_mailer = "ActionMailer::Base" + # The router Devise should use to generate routes. Defaults - # to :main_app. Should be overriden by engines in order + # to :main_app. Should be overridden by engines in order # to provide custom routes. mattr_accessor :router_name @@router_name = nil - # Set the omniauth path prefix so it can be overriden when + # Set the OmniAuth path prefix so it can be overridden when # Devise is used in a mountable engine mattr_accessor :omniauth_path_prefix @@omniauth_path_prefix = nil - def self.encryptor=(value) - warn "\n[DEVISE] To select a encryption which isn't bcrypt, you should use devise-encryptable gem.\n" - end - - def self.use_salt_as_remember_token=(value) - warn "\n[DEVISE] Devise.use_salt_as_remember_token is deprecated and has no effect. Please remove it.\n" - end + # Set if we should clean up the CSRF Token on authentication + mattr_accessor :clean_up_csrf_token_on_authentication + @@clean_up_csrf_token_on_authentication = true - def self.apply_schema=(value) - warn "\n[DEVISE] Devise.apply_schema is deprecated and has no effect. Please remove it.\n" - end + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + mattr_accessor :reload_routes + @@reload_routes = true # PRIVATE CONFIGURATION # Store scopes mappings. - mattr_reader :mappings - @@mappings = ActiveSupport::OrderedHash.new + @@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. + # OmniAuth configurations. mattr_reader :omniauth_configs - @@omniauth_configs = ActiveSupport::OrderedHash.new + @@omniauth_configs = {} # Define a set of modules that are called when a mapping is added. mattr_reader :helpers @@ -240,35 +294,51 @@ def self.apply_schema=(value) # Private methods to interface with Warden. mattr_accessor :warden_config @@warden_config = nil - @@warden_config_block = nil + @@warden_config_blocks = [] # When true, enter in paranoid mode to avoid user enumeration. mattr_accessor :paranoid @@paranoid = false - # Default way to setup Devise. Run rails generate devise_install to create + # When true, warn user if they just used next-to-last attempt of authentication + mattr_accessor :last_attempt_warning + @@last_attempt_warning = true + + # Stores the token generator + mattr_accessor :token_generator + @@token_generator = nil + + # 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. def self.setup yield self end class Getter - def initialize name + def initialize(name) @name = 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) - if defined?(ActiveSupport::Dependencies::ClassCache) - ActiveSupport::Dependencies::reference(arg) - Getter.new(arg) - else - ActiveSupport::Dependencies.ref(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 def self.available_router_name @@ -299,14 +369,20 @@ def self.add_mapping(resource, options) mapping end - # Make Devise aware of an 3rd party Devise-module (like invitable). For convenience. + # Register available devise modules. For the standard modules that Devise provides, this method is + # called from lib/devise/modules.rb. Third-party modules need to be added explicitly using this method. + # + # Note that adding a module using this method does not cause it to be used in the authentication + # process. That requires that the module be listed in the arguments passed to the 'devise' method + # in the model class definition. # # == Options: # # +model+ - String representing the load path to a custom *model* for this module (to autoload.) - # +controller+ - Symbol representing the name of an exisiting or custom *controller* for this module. + # +controller+ - Symbol representing the name of an existing or custom *controller* for this module. # +route+ - Symbol representing the named *route* helper for this module. # +strategy+ - Symbol representing if this module got a custom *strategy*. + # +insert_at+ - Integer representing the order in which this module's model will be included # # All values, except :model, accept also a boolean and will have the same name as the given module # name. @@ -314,12 +390,14 @@ def self.add_mapping(resource, options) # == Examples: # # Devise.add_module(:party_module) - # Devise.add_module(:party_module, :strategy => true, :controller => :sessions) - # Devise.add_module(:party_module, :model => 'party_module/model') + # Devise.add_module(:party_module, strategy: true, controller: :sessions) + # Devise.add_module(:party_module, model: 'party_module/model') + # Devise.add_module(:party_module, insert_at: 0) # def self.add_module(module_name, options = {}) - ALL << module_name - options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input) + options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input, :insert_at) + + ALL.insert (options[:insert_at] || -1), module_name if strategy = options[:strategy] strategy = (strategy == true ? module_name : strategy) @@ -364,24 +442,23 @@ def self.add_module(module_name, options = {}) # Sets warden configuration using a block that will be invoked on warden # initialization. # - # Devise.initialize do |config| + # 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) - @@warden_config_block = block + @@warden_config_blocks << block end - # Specify an omniauth provider. + # Specify an OmniAuth provider. # # config.omniauth :github, APP_ID, APP_SECRET # def self.omniauth(provider, *args) - @@helpers << Devise::OmniAuth::UrlHelpers config = Devise::OmniAuth::Config.new(provider, args) @@omniauth_configs[config.strategy_name.to_sym] = config end @@ -404,8 +481,8 @@ def self.regenerate_helpers! Devise::Controllers::UrlHelpers.generate_helpers! end - # A method used internally to setup warden manager from the Rails initialize - # block. + # A method used internally to complete the setup of warden manager after routes are loaded. + # See lib/devise/rails/routes.rb - ActionDispatch::Routing::RouteSet#finalize_with_devise! def self.configure_warden! #:nodoc: @@warden_configured ||= begin warden_config.failure_app = Devise::Delegator.new @@ -413,27 +490,39 @@ def self.configure_warden! #:nodoc: warden_config.intercept_401 = false Devise.mappings.each_value do |mapping| - warden_config.scope_defaults mapping.name, :strategies => mapping.strategies + warden_config.scope_defaults mapping.name, strategies: mapping.strategies + + warden_config.serialize_into_session(mapping.name) do |record| + mapping.to.serialize_into_session(record) + end + + warden_config.serialize_from_session(mapping.name) do |args| + mapping.to.serialize_from_session(*args) + end end - @@warden_config_block.try :call, Devise.warden_config + @@warden_config_blocks.map { |block| block.call Devise.warden_config } true end end - # Generate a friendly string randomically to be used as token. - def self.friendly_token - SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz') + # Generate a friendly string randomly to be used as token. + # By default, length is 20 characters. + def self.friendly_token(length = 20) + # To calculate real characters, we must perform this operation. + # See SecureRandom.urlsafe_base64 + rlength = (length * 3) / 4 + SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz') end # 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 0c147b0655..68e8e8d1d6 100644 --- a/lib/devise/controllers/helpers.rb +++ b/lib/devise/controllers/helpers.rb @@ -1,14 +1,85 @@ +# frozen_string_literal: true + module Devise module Controllers # Those helpers are convenience methods added to ApplicationController. module Helpers extend ActiveSupport::Concern + include Devise::Controllers::SignInOut + include Devise::Controllers::StoreLocation included do - helper_method :warden, :signed_in?, :devise_controller? + if respond_to?(:helper_method) + helper_method :warden, :signed_in?, :devise_controller? + end end module ClassMethods + # Define authentication filters and accessor helpers for a group of mappings. + # These methods are useful when you are working with multiple mappings that + # share some functionality. They are pretty much the same as the ones + # defined for normal mappings. + # + # Example: + # + # inside BlogsController (or any other controller, it doesn't matter which): + # devise_group :blogger, contains: [:user, :admin] + # + # Generated methods: + # authenticate_blogger! # Redirects unless user or admin are signed in + # blogger_signed_in? # Checks whether there is either a user or an admin signed in + # current_blogger # Currently signed in user or admin + # current_bloggers # Currently signed in user and admin + # + # Use: + # before_action :authenticate_blogger! # Redirects unless either a user or an admin are authenticated + # 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 = {}) + mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]" + + class_eval <<-METHODS, __FILE__, __LINE__ + 1 + def authenticate_#{group_name}!(favorite = nil, opts = {}) + unless #{group_name}_signed_in? + mappings = #{mappings} + 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 + end + + def #{group_name}_signed_in? + #{mappings}.any? do |mapping| + warden.authenticate?(scope: mapping) + end + end + + def current_#{group_name}(favorite = nil) + mappings = #{mappings} + mappings.unshift mappings.delete(favorite.to_sym) if favorite + mappings.each do |mapping| + current = warden.authenticate(scope: mapping) + return current if current + end + nil + end + + def current_#{group_name.to_s.pluralize} + #{mappings}.map do |mapping| + warden.authenticate(scope: mapping) + end.compact + end + + if respond_to?(:helper_method) + helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?" + end + METHODS + end + def log_process_action(payload) payload[:status] ||= 401 unless payload[:exception] super @@ -16,7 +87,7 @@ def log_process_action(payload) end # Define authentication filters and accessor helpers based on mappings. - # These filters should be used inside the controllers as before_filters, + # These filters should be used inside the controllers as before_actions, # so you can control the scope of the user who should be signed in to # access that specific controller/action. # Example: @@ -36,15 +107,16 @@ def log_process_action(payload) # admin_session # Session data available only to the admin scope # # Use: - # before_filter :authenticate_user! # Tell devise to use :user map - # before_filter :authenticate_admin! # Tell devise to use :admin map + # before_action :authenticate_user! # Tell devise to use :user map + # before_action :authenticate_admin! # Tell devise to use :admin map # 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 @@ -53,7 +125,7 @@ def #{mapping}_signed_in? end def current_#{mapping} - @current_#{mapping} ||= warden.authenticate(:scope => :#{mapping}) + @current_#{mapping} ||= warden.authenticate(scope: :#{mapping}) end def #{mapping}_session @@ -62,22 +134,31 @@ def #{mapping}_session METHODS ActiveSupport.on_load(:action_controller) do - helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" + if respond_to?(:helper_method) + helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" + end end end # The main accessor for the warden proxy instance def warden - request.env['warden'] + request.env['warden'] or raise MissingWarden end # Return true if it's a devise_controller. false to all controllers unless # the controllers defined inside devise. Useful if you want to apply a before # filter to all controllers, except the ones in devise: # - # before_filter :my_filter, :unless => :devise_controller? + # before_action :my_filter, unless: :devise_controller? def devise_controller? - is_a?(DeviseController) + is_a?(::DeviseController) + end + + # Set up a param sanitizer to filter parameters using strong_parameters. See + # lib/devise/parameter_sanitizer.rb for more info. Override this + # method in your application controller to use your own parameter sanitizer. + def devise_parameter_sanitizer + @devise_parameter_sanitizer ||= Devise::ParameterSanitizer.new(resource_class, resource_name, params) end # Tell warden that params authentication is allowed for that specific page. @@ -85,102 +166,20 @@ def allow_params_authentication! request.env["devise.allow_params_authentication"] = true end - # 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) - [ scope || Devise.mappings.keys ].flatten.any? do |_scope| - warden.authenticate?(:scope => _scope) - end - end - - # 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. - # The only exception is the :bypass option, which bypass warden callbacks and stores - # the user straight in session. This option is useful in cases the user is already - # signed in, but we want to refresh the credentials in session. - # - # Examples: - # - # sign_in :user, @user # sign_in(scope, resource) - # sign_in @user # sign_in(resource) - # sign_in @user, :event => :authentication # sign_in(resource, options) - # sign_in @user, :bypass => true # sign_in(resource, options) - # - def sign_in(resource_or_scope, *args) - options = args.extract_options! - scope = Devise::Mapping.find_scope!(resource_or_scope) - resource = args.last || resource_or_scope - - expire_session_data_after_sign_in! - - if options[:bypass] - warden.session_serializer.store(resource, scope) - elsif warden.user(scope) == resource && !options.delete(:force) - # Do nothing. User already signed in and we are not forcing it. - true - else - warden.set_user(resource, options.merge!(:scope => scope)) - end - end - - # Sign out a given user or scope. This helper is useful for signing out a user - # after deleting accounts. Returns true if there was a logout and false if there - # is no user logged in on the referred scope - # - # Examples: - # - # sign_out :user # sign_out(scope) - # sign_out @user # sign_out(resource) - # - 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 - - warden.raw_session.inspect # Without this inspect here. The session does not clear. - warden.logout(scope) - warden.clear_strategies_cache!(:scope => scope) - instance_variable_set(:"@current_#{scope}", nil) - - !!user - end - - # 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) - users = Devise.mappings.keys.map { |s| warden.user(:scope => s, :run_callbacks => false) } - - warden.raw_session.inspect - warden.logout - expire_devise_cached_variables! - warden.clear_strategies_cache! - warden.lock! if lock - - users.any? - end - - # Returns and delete the url stored in the session for the given scope. Useful - # for giving redirect backs after sign up: - # - # Example: - # - # redirect_to stored_location_for(:user) || root_path - # - def stored_location_for(resource_or_scope) - scope = Devise::Mapping.find_scope!(resource_or_scope) - session.delete("#{scope}_return_to") - end - - # The scope root url to be used when he's signed in. By default, it first + # The scope root url to be used when they're signed in. By default, it first # tries to find a resource_root_path, otherwise it uses the root_path. def signed_in_root_path(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) + router_name = Devise.mappings[scope].router_name + home_path = "#{scope}_root_path" - if respond_to?(home_path, true) - send(home_path) + + context = router_name ? send(router_name) : self + + if context.respond_to?(home_path, true) + context.send(home_path) + elsif context.respond_to?(:root_path) + context.root_path elsif respond_to?(:root_path) root_path else @@ -197,10 +196,10 @@ def signed_in_root_path(resource_or_scope) # root path. For a user scope, you can define the default url in # the following way: # - # map.user_root '/users', :controller => 'users' # creates user_root_path + # get '/users' => 'users#index', as: :user_root # creates user_root_path # - # map.namespace :user do |user| - # user.root :controller => 'users' # creates user_root_path + # namespace :user do + # root 'users#index' # creates user_root_path # end # # If the resource root path is not defined, root_path is used. However, @@ -226,7 +225,10 @@ def after_sign_in_path_for(resource_or_scope) # # By default it is the root_path. def after_sign_out_path_for(resource_or_scope) - respond_to?(:root_path) ? root_path : "/" + scope = Devise::Mapping.find_scope!(resource_or_scope) + router_name = Devise.mappings[scope].router_name + context = router_name ? send(router_name) : self + context.respond_to?(:root_path) ? context.root_path : "/" end # Sign in a user and tries to redirect first to the stored location and @@ -240,10 +242,6 @@ def sign_in_and_redirect(resource_or_scope, *args) redirect_to after_sign_in_path_for(resource) end - def expire_session_data_after_sign_in! - session.keys.grep(/^devise\./).each { |k| session.delete(k) } - end - # Sign out a user and tries to redirect to the url specified by # after_sign_out_path_for. def sign_out_and_redirect(resource_or_scope) @@ -256,17 +254,42 @@ 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 - sign_out_all_scopes(false) + super # call the default behavior which resets/nullifies/raises request.env["devise.skip_storage"] = true - expire_devise_cached_variables! - super # call the default behaviour which resets the session + sign_out_all_scopes(false) + end + + def request_format + @request_format ||= request.format.try(:ref) + end + + def is_navigational_format? + Devise.navigational_formats.include?(request_format) + end + + # Check if flash messages should be emitted. Default is to do it on + # navigational formats + def is_flashing_format? + request.respond_to?(:flash) && is_navigational_format? end private - def expire_devise_cached_variables! + def expire_data_after_sign_out! Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) } + super end end end + + class MissingWarden < StandardError + def initialize + super "Devise could not find the `Warden::Proxy` instance on your request environment.\n" + \ + "Make sure that your application is loading Devise and Warden as expected and that " + \ + "the `Warden::Manager` middleware is present in your middleware stack.\n" + \ + "If you are seeing this on one of your tests, ensure that your tests are either " + \ + "executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` " + \ + "module to inject the `request.env['warden']` object for you." + end + end end diff --git a/lib/devise/controllers/rememberable.rb b/lib/devise/controllers/rememberable.rb index f664244daa..420a2f785d 100644 --- a/lib/devise/controllers/rememberable.rb +++ b/lib/devise/controllers/rememberable.rb @@ -1,36 +1,36 @@ +# frozen_string_literal: true + module Devise module Controllers # A module that may be optionally included in a controller in order - # to provide remember me behavior. + # to provide remember me behavior. Useful when signing in is done + # through a callback, like in OmniAuth. module Rememberable # Return default cookie values retrieved from session options. def self.cookie_values Rails.configuration.session_options.slice(:path, :domain, :secure) end - # A small warden proxy so we can remember and forget uses from hooks. - class Proxy #:nodoc: - include Devise::Controllers::Rememberable - - delegate :cookies, :env, :to => :@warden - - def initialize(warden) - @warden = warden - end + def remember_me_is_active?(resource) + return false unless resource.respond_to?(:remember_me) + scope = Devise::Mapping.find_scope!(resource) + _, token, generated_at = cookies.signed[remember_key(resource, scope)] + resource.remember_me?(token, generated_at) end # Remembers the given resource by setting up a cookie def remember_me(resource) + return if request.env["devise.skip_storage"] scope = Devise::Mapping.find_scope!(resource) - resource.remember_me!(resource.extend_remember_period) - cookies.signed["remember_#{scope}_token"] = remember_cookie_values(resource) + resource.remember_me! + cookies.signed[remember_key(resource, scope)] = remember_cookie_values(resource) end # Forgets the given resource by deleting a cookie def forget_me(resource) scope = Devise::Mapping.find_scope!(resource) resource.forget_me! - cookies.delete("remember_#{scope}_token", forget_cookie_values(resource)) + cookies.delete(remember_key(resource, scope), forget_cookie_values(resource)) end protected @@ -40,13 +40,17 @@ def forget_cookie_values(resource) end def remember_cookie_values(resource) - options = { :httponly => true } + options = { httponly: true } options.merge!(forget_cookie_values(resource)) options.merge!( - :value => resource.class.serialize_into_cookie(resource), - :expires => resource.remember_expires_at + value: resource.class.serialize_into_cookie(resource), + expires: resource.remember_expires_at ) end + + def remember_key(resource, scope) + resource.rememberable_options.fetch(:key, "remember_#{scope}_token") + end end end -end \ No newline at end of file +end diff --git a/lib/devise/controllers/responder.rb b/lib/devise/controllers/responder.rb new file mode 100644 index 0000000000..8e3858a13c --- /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 7865b7865b..989d3879cb 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 @@ -14,4 +16,4 @@ def scoped_views=(value) end end end -end \ No newline at end of file +end diff --git a/lib/devise/controllers/sign_in_out.rb b/lib/devise/controllers/sign_in_out.rb new file mode 100644 index 0000000000..7e053d1121 --- /dev/null +++ b/lib/devise/controllers/sign_in_out.rb @@ -0,0 +1,106 @@ +# 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. 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 + end + + # 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: + # + # sign_in :user, @user # sign_in(scope, resource) + # sign_in @user # sign_in(resource) + # sign_in @user, event: :authentication # sign_in(resource, options) + # sign_in @user, store: false # sign_in(resource, options) + # + def sign_in(resource_or_scope, *args) + options = args.extract_options! + scope = Devise::Mapping.find_scope!(resource_or_scope) + resource = args.last || resource_or_scope + + expire_data_after_sign_in! + + if warden.user(scope) == resource && !options.delete(:force) + # Do nothing. User already signed in and we are not forcing it. + true + else + warden.set_user(resource, options.merge!(scope: scope)) + end + end + + # Sign in a user bypassing the warden callbacks and stores the user + # straight in session. This option is useful in cases the user is already + # signed in, but we want to refresh the credentials in session. + # + # Examples: + # + # bypass_sign_in @user, scope: :user + # bypass_sign_in @user + def bypass_sign_in(resource, scope: nil) + scope ||= Devise::Mapping.find_scope!(resource) + expire_data_after_sign_in! + warden.session_serializer.store(resource, scope) + end + + # Sign out a given user or scope. This helper is useful for signing out a user + # after deleting accounts. Returns true if there was a logout and false if there + # is no user logged in on the referred scope + # + # Examples: + # + # sign_out :user # sign_out(scope) + # sign_out @user # sign_out(resource) + # + 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 + + warden.logout(scope) + warden.clear_strategies_cache!(scope: scope) + instance_variable_set(:"@current_#{scope}", nil) + + !!user + end + + # 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) + users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) } + + warden.logout + expire_data_after_sign_out! + warden.clear_strategies_cache! + warden.lock! if lock + + users.any? + end + + private + + def expire_data_after_sign_in! + session.keys.grep(/^devise\./).each { |k| session.delete(k) } + end + + alias :expire_data_after_sign_out! :expire_data_after_sign_in! + end + end +end diff --git a/lib/devise/controllers/store_location.rb b/lib/devise/controllers/store_location.rb new file mode 100644 index 0000000000..d2e431e800 --- /dev/null +++ b/lib/devise/controllers/store_location.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require "uri" + +module Devise + module Controllers + # Provide the ability to store a location. + # Used to redirect back to a desired path after sign in. + # Included by default in all controllers. + module StoreLocation + # Returns and delete (if it's navigational format) the url stored in the session for + # the given scope. Useful for giving redirect backs after sign up: + # + # Example: + # + # redirect_to stored_location_for(:user) || root_path + # + def stored_location_for(resource_or_scope) + session_key = stored_location_key_for(resource_or_scope) + + if is_navigational_format? + session.delete(session_key) + else + session[session_key] + end + end + + # Stores the provided location to redirect the user after signing in. + # Useful in combination with the `stored_location_for` helper. + # + # Example: + # + # store_location_for(:user, dashboard_path) + # redirect_to user_facebook_omniauth_authorize_path + # + def store_location_for(resource_or_scope, location) + session_key = stored_location_key_for(resource_or_scope) + + path = extract_path_from_location(location) + session[session_key] = path if path + end + + private + + def parse_uri(location) + location && URI.parse(location) + rescue URI::InvalidURIError + nil + end + + 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 + 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 480687f55b..2792a07c8b 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) @@ -42,14 +44,14 @@ def self.generate_helpers!(routes=nil) [:path, :url].each do |path_or_url| actions.each do |action| action = action ? "#{action}_" : "" - method = "#{action}#{module_name}_#{path_or_url}" + method = :"#{action}#{module_name}_#{path_or_url}" - class_eval <<-URL_HELPERS, __FILE__, __LINE__ + 1 - def #{method}(resource_or_scope, *args) - scope = Devise::Mapping.find_scope!(resource_or_scope) - _devise_route_context.send("#{action}\#{scope}_#{module_name}_#{path_or_url}", *args) - end - URL_HELPERS + define_method method do |resource_or_scope, *args| + scope = Devise::Mapping.find_scope!(resource_or_scope) + router_name = Devise.mappings[scope].router_name + context = router_name ? send(router_name) : _devise_route_context + context.send("#{action}#{scope}_#{module_name}_#{path_or_url}", *args) + end end end end diff --git a/lib/devise/delegator.rb b/lib/devise/delegator.rb index 361d4cffed..d04f15f198 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 new file mode 100644 index 0000000000..7a53bef309 --- /dev/null +++ b/lib/devise/encryptor.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require 'bcrypt' + +module Devise + module Encryptor + def self.digest(klass, password) + if klass.pepper.present? + password = "#{password}#{klass.pepper}" + end + ::BCrypt::Password.create(password, cost: klass.stretches).to_s + end + + def self.compare(klass, hashed_password, password) + return false if hashed_password.blank? + bcrypt = ::BCrypt::Password.new(hashed_password) + if klass.pepper.present? + password = "#{password}#{klass.pepper}" + end + password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt) + Devise.secure_compare(password, hashed_password) + end + end +end diff --git a/lib/devise/failure_app.rb b/lib/devise/failure_app.rb index 54d214a4f2..8222780f08 100644 --- a/lib/devise/failure_app.rb +++ b/lib/devise/failure_app.rb @@ -1,28 +1,39 @@ +# frozen_string_literal: true + require "action_controller/metal" module Devise # Failure application that will be called every time :warden is thrown from - # any strategy or hook. Responsible for redirect the user to the sign in - # page based on current scope and mapping. If no scope is given, redirect - # to the default_url. + # any strategy or hook. It is responsible for redirecting the user to the sign + # in page based on current scope and mapping. If no scope is given, it + # redirects to the default_url. class FailureApp < ActionController::Metal - include ActionController::RackDelegation include ActionController::UrlFor include ActionController::Redirecting include Rails.application.routes.url_helpers include Rails.application.routes.mounted_helpers - delegate :flash, :to => :request + include Devise::Controllers::StoreLocation + + 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) end + # Try retrieving the URL options from the parent controller (usually + # ApplicationController). Instance methods are not supported at the moment, + # so only the class-level attribute is used. def self.default_url_options(*args) - if defined?(ApplicationController) - ApplicationController.default_url_options(*args) + if defined?(Devise.parent_controller.constantize) + Devise.parent_controller.constantize.try(:default_url_options) || {} else {} end @@ -46,73 +57,136 @@ def http_auth end def recall - env["PATH_INFO"] = attempted_path - flash.now[:alert] = i18n_message(:invalid) - self.response = recall_app(warden_options[:recall]).call(env) + header_info = if relative_url_root? + base_path = Pathname.new(relative_url_root) + full_path = Pathname.new(attempted_path) + + { "SCRIPT_NAME" => relative_url_root, + "PATH_INFO" => '/' + full_path.relative_path_from(base_path).to_s } + else + { "PATH_INFO" => attempted_path } + end + + header_info.each do | var, value| + if request.respond_to?(:set_header) + request.set_header(var, value) + else + request.env[var] = value + end + end + + flash.now[:alert] = i18n_message(:invalid) if is_flashing_format? + 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 store_location! - if flash[:timedout] && flash[:alert] - flash.keep(:timedout) - flash.keep(:alert) - else - flash[:alert] = i18n_message + if is_flashing_format? + if flash[:timedout] && flash[:alert] + flash.keep(:timedout) + flash.keep(:alert) + else + flash[:alert] = i18n_message + end end redirect_to redirect_url end protected + def i18n_options(options) + options + end + def i18n_message(default = nil) message = warden_message || default || :unauthenticated if message.is_a?(Symbol) - I18n.t(:"#{scope}.#{message}", :resource_name => scope, - :scope => "devise.failure", :default => [message]) + options = {} + options[:resource_name] = scope + options[:scope] = "devise.failure" + options[:default] = [message] + auth_keys = scope_class.authentication_keys + human_keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key| + scope_class.human_attribute_name(key).downcase + } + options[:authentication_keys] = human_keys.join(I18n.t(:"support.array.words_connector")) + options = i18n_options(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 - attempted_path || scope_path + flash[:timedout] = true if is_flashing_format? + + path = if request.get? + attempted_path + else + request.referrer + end + + path || scope_url else - scope_path + scope_url end end - def scope_path + def route(scope) + :"new_#{scope}_session_url" + end + + def scope_url opts = {} - route = :"new_#{scope}_session_path" + + # Initialize script_name with nil to prevent infinite loops in + # authenticated mounted engines + opts[:script_name] = nil + + route = route(scope) + opts[:format] = request_format unless skip_format? - config = Rails.application.config - opts[:script_name] = (config.relative_url_root if config.respond_to?(:relative_url_root)) + router_name = Devise.mappings[scope].router_name || Devise.available_router_name + context = send(router_name) - context = send(Devise.available_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_path) - root_path(opts) + elsif respond_to?(:root_url) + root_url(opts) else "/" end 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 a http authentication fashion, + # Choose whether we should respond in an HTTP authentication fashion, # including 401 and optional headers. # - # This method allows the user to explicitly disable http authentication - # on ajax requests in case they want to redirect on failures instead of - # handling the errors on their own. This is useful in case your ajax API + # This method allows the user to explicitly disable HTTP authentication + # on AJAX requests in case they want to redirect on failures instead of + # handling the errors on their own. This is useful in case your AJAX API # is the same as your public API and uses a format like JSON (so you # cannot mark JSON as a navigational format). def http_auth? @@ -123,19 +197,19 @@ def http_auth? end end - # It does not make sense to send authenticate headers in ajax requests + # It doesn't make sense to send authenticate headers in AJAX requests # or if the user disabled them. def http_auth_header? - Devise.mappings[scope].to.http_authenticatable && !request.xhr? + scope_class.http_authenticatable && !request.xhr? end def http_auth_body return i18n_message unless request_format method = "to_#{request_format}" if method == "to_xml" - { :error => i18n_message }.to_xml(:root => "errors") + { error: i18n_message }.to_xml(root: "errors") elsif {}.respond_to?(method) - { :error => i18n_message }.send(method) + { error: i18n_message }.send(method) else i18n_message end @@ -149,11 +223,11 @@ def recall_app(app) end def warden - env['warden'] + request.respond_to?(:get_header) ? request.get_header("warden") : request.env["warden"] end def warden_options - env['warden.options'] + request.respond_to?(:get_header) ? request.get_header("warden.options") : request.env["warden.options"] end def warden_message @@ -164,24 +238,48 @@ def scope @scope ||= warden_options[:scope] || Devise.default_scope end + def scope_class + @scope_class ||= Devise.mappings[scope].to + end + def attempted_path warden_options[:attempted_path] end - # Stores requested uri to redirect the user after signing in. We cannot use - # scoped session provided by warden here, since the user is not authenticated - # yet, but we still need to store the uri based on scope, so different scopes - # would never use the same uri to redirect. + # Stores requested URI to redirect the user after signing in. We can't use + # the scoped session provided by warden here, since the user is not + # authenticated yet, but we still need to store the URI based on scope, so + # different scopes would never use the same URI to redirect. def store_location! - session["#{scope}_return_to"] = attempted_path if request.get? && !http_auth? + store_location_for(scope, attempted_path) if request.get? && !http_auth? end def is_navigational_format? Devise.navigational_formats.include?(request_format) end + # Check if flash messages should be emitted. Default is to do it on + # navigational formats + def is_flashing_format? + request.respond_to?(:flash) && is_navigational_format? + end + def request_format @request_format ||= request.format.try(:ref) end + + def relative_url_root + @relative_url_root ||= begin + config = Rails.application.config + + config.try(:relative_url_root) || config.action_controller.try(:relative_url_root) + end + end + + 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 e9b2d910d9..9feb963074 100644 --- a/lib/devise/hooks/activatable.rb +++ b/lib/devise/hooks/activatable.rb @@ -1,11 +1,12 @@ -# Deny user access whenever his account is not active yet. All strategies that inherits from -# Devise::Strategies::Authenticatable and uses the validate already check if the user is active_for_authentication? -# before actively signing him in. However, we need this as hook to validate the user activity -# in each request and in case the user is using other strategies beside Devise ones. +# 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. Warden::Manager.after_set_user do |record, warden, options| 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 \ No newline at end of file +end diff --git a/lib/devise/hooks/csrf_cleaner.rb b/lib/devise/hooks/csrf_cleaner.rb new file mode 100644 index 0000000000..4a64739551 --- /dev/null +++ b/lib/devise/hooks/csrf_cleaner.rb @@ -0,0 +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 + 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 bf0374f407..317dc54748 100644 --- a/lib/devise/hooks/forgetable.rb +++ b/lib/devise/hooks/forgetable.rb @@ -1,9 +1,11 @@ +# 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. # This avoids forgetting deleted users. Warden::Manager.before_logout do |record, warden, options| if record.respond_to?(:forget_me!) - Devise::Controllers::Rememberable::Proxy.new(warden).forget_me(record) + Devise::Hooks::Proxy.new(warden).forget_me(record) end end diff --git a/lib/devise/hooks/lockable.rb b/lib/devise/hooks/lockable.rb index 22d0428e41..b11db1e879 100644 --- a/lib/devise/hooks/lockable.rb +++ b/lib/devise/hooks/lockable.rb @@ -1,7 +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]) - record.update_attribute(:failed_attempts, 0) +Warden::Manager.after_set_user except: :fetch do |record, warden, options| + 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 new file mode 100644 index 0000000000..96b3a07e8b --- /dev/null +++ b/lib/devise/hooks/proxy.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +module Devise + module Hooks + # A small warden proxy so we can remember, forget and + # sign out users from hooks. + class Proxy #:nodoc: + include Devise::Controllers::Rememberable + include Devise::Controllers::SignInOut + + attr_reader :warden + delegate :cookies, :request, to: :warden + + def initialize(warden) + @warden = warden + end + + def session + warden.request.session + end + end + end +end diff --git a/lib/devise/hooks/rememberable.rb b/lib/devise/hooks/rememberable.rb index 4d7182645c..345f2f2403 100644 --- a/lib/devise/hooks/rememberable.rb +++ b/lib/devise/hooks/rememberable.rb @@ -1,6 +1,9 @@ -Warden::Manager.after_set_user :except => :fetch do |record, warden, options| +# frozen_string_literal: true + +Warden::Manager.after_set_user except: :fetch do |record, warden, options| scope = options[:scope] - if record.respond_to?(:remember_me) && record.remember_me && warden.authenticated?(scope) - Devise::Controllers::Rememberable::Proxy.new(warden).remember_me(record) + if record.respond_to?(:remember_me) && options[:store] != false && + record.remember_me && warden.authenticated?(scope) + Devise::Hooks::Proxy.new(warden).remember_me(record) end -end \ No newline at end of file +end diff --git a/lib/devise/hooks/timeoutable.rb b/lib/devise/hooks/timeoutable.rb index 2856a081ed..f1e7f6d577 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 @@ -7,19 +9,27 @@ scope = options[:scope] env = warden.request.env - if record && record.respond_to?(:timedout?) && warden.authenticated?(scope) && options[:store] != false + if record && record.respond_to?(:timedout?) && warden.authenticated?(scope) && + options[:store] != false && !env['devise.skip_timeoutable'] last_request_at = warden.session(scope)['last_request_at'] - if record.timedout?(last_request_at) && !env['devise.skip_timeout'] - warden.logout(scope) - if record.respond_to?(:expire_auth_token_on_timeout) && record.expire_auth_token_on_timeout - record.reset_authentication_token! - end - throw :warden, :scope => scope, :message => :timeout + if last_request_at.is_a? Integer + last_request_at = Time.at(last_request_at).utc + elsif last_request_at.is_a? String + last_request_at = Time.parse(last_request_at) + end + + proxy = Devise::Hooks::Proxy.new(warden) + + 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, locale: options.fetch(:locale, I18n.locale) end unless env['devise.skip_trackable'] - warden.session(scope)['last_request_at'] = Time.now.utc + warden.session(scope)['last_request_at'] = Time.now.utc.to_i end end end diff --git a/lib/devise/hooks/trackable.rb b/lib/devise/hooks/trackable.rb index 0b4bc6613d..53ac30dd32 100644 --- a/lib/devise/hooks/trackable.rb +++ b/lib/devise/hooks/trackable.rb @@ -1,8 +1,10 @@ +# 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 # not trigger it. -Warden::Manager.after_set_user :except => :fetch do |record, warden, options| +Warden::Manager.after_set_user except: :fetch do |record, warden, options| if record.respond_to?(:update_tracked_fields!) && warden.authenticated?(options[:scope]) && !warden.request.env['devise.skip_trackable'] record.update_tracked_fields!(warden.request) end diff --git a/lib/devise/mailers/helpers.rb b/lib/devise/mailers/helpers.rb index 7d1b92e283..29a491970d 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 @@ -5,15 +7,16 @@ module Helpers included do include Devise::Controllers::ScopedViews - attr_reader :scope_name, :resource end protected + attr_reader :scope_name, :resource + # Configure default email options - def devise_mail(record, action) + def devise_mail(record, action, opts = {}, &block) initialize_from_record(record) - mail headers_for(action) + mail headers_for(action, opts), &block end def initialize_from_record(record) @@ -25,34 +28,27 @@ def devise_mapping @devise_mapping ||= Devise.mappings[scope_name] end - def headers_for(action) + def headers_for(action, opts) headers = { - :subject => translate(devise_mapping, action), - :to => resource.email, - :from => mailer_sender(devise_mapping), - :reply_to => mailer_reply_to(devise_mapping), - :template_path => template_paths + subject: subject_for(action), + to: resource.email, + from: mailer_sender(devise_mapping), + reply_to: mailer_sender(devise_mapping), + template_path: template_paths, + template_name: action } + # 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] - if resource.respond_to?(:headers_for) - headers.merge!(resource.headers_for(action)) - end + 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) - if default_params[sender].present? - default_params[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 @@ -60,12 +56,12 @@ def mailer_sender(mapping, sender = :from) end def template_paths - template_path = [self.class.mailer_name] + template_path = _prefixes.dup template_path.unshift "#{@devise_mapping.scoped_path}/mailer" if self.class.scoped_views? template_path end - # Setup a subject doing an I18n lookup. At first, it attemps to set a subject + # Set up a subject doing an I18n lookup. At first, it attempts to set a subject # based on the current mapping: # # en: @@ -82,9 +78,9 @@ def template_paths # confirmation_instructions: # subject: '...' # - def translate(mapping, key) - I18n.t(:"#{mapping.name}_subject", :scope => [:devise, :mailer, key], - :default => [:subject, key.to_s.humanize]) + def subject_for(key) + I18n.t(:"#{devise_mapping.name}_subject", scope: [:devise, :mailer, key], + default: [:subject, key.to_s.humanize]) end end end diff --git a/lib/devise/mapping.rb b/lib/devise/mapping.rb index 84d638645a..8b1f94ced2 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 @@ -23,26 +25,28 @@ module Devise # class Mapping #:nodoc: attr_reader :singular, :scoped_path, :path, :controllers, :path_names, - :class_name, :sign_out_via, :format, :used_routes, :used_helpers, :failure_app + :class_name, :sign_out_via, :format, :used_routes, :used_helpers, + :failure_app, :router_name 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!(duck) - case duck + def self.find_scope!(obj) + obj = obj.devise_scope if obj.respond_to?(:devise_scope) + case obj when String, Symbol - return duck + return obj.to_sym when Class - Devise.mappings.each_value { |m| return m.name if duck <= m.to } + Devise.mappings.each_value { |m| return m.name if obj <= m.to } else - Devise.mappings.each_value { |m| return m.name if duck.is_a?(m.to) } + Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) } end - raise "Could not find a valid mapping for #{duck.inspect}" + 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 @@ -60,6 +64,8 @@ def initialize(name, options) #:nodoc: @sign_out_via = options[:sign_out_via] || Devise.sign_out_via @format = options[:format] + @router_name = options[:router_name] + default_failure_app(options) default_controllers(options) default_path_names(options) diff --git a/lib/devise/models.rb b/lib/devise/models.rb index f88aee162d..fb7dd89b06 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 @@ -12,7 +14,7 @@ def message # Creates configuration values for Devise and for the given module. # - # Devise::Models.config(Devise::Authenticatable, :stretches, 10) + # Devise::Models.config(Devise::Models::DatabaseAuthenticatable, :stretches) # # The line above creates: # @@ -56,14 +58,8 @@ def self.check_fields!(klass) klass.devise_modules.each do |mod| constant = const_get(mod.to_s.classify) - if constant.respond_to?(:required_fields) - constant.required_fields(klass).each do |field| - failed_attributes << field unless instance.respond_to?(field) - end - else - ActiveSupport::Deprecation.warn "The module #{mod} doesn't implement self.required_fields(klass). " \ - "Devise uses required_fields to warn developers of any missing fields in their models. " \ - "Please implement #{mod}.required_fields(klass) that returns an array of symbols with the required fields." + constant.required_fields(klass).each do |field| + failed_attributes << field unless instance.respond_to?(field) end end @@ -88,12 +84,10 @@ def devise(*modules) end devise_modules_hook! do + include Devise::Orm include Devise::Models::Authenticatable - selected_modules.each do |m| - if m == :encryptable && !(defined?(Devise::Models::Encryptable)) - warn "[DEVISE] You're trying to include :encryptable in your model but it is not bundled with the Devise gem anymore. Please add `devise-encryptable` to your Gemfile to proceed.\n" - end + selected_modules.each do |m| mod = Devise::Models.const_get(m.to_s.classify) if mod.const_defined?("ClassMethods") diff --git a/lib/devise/models/authenticatable.rb b/lib/devise/models/authenticatable.rb index b2eb1decab..df964537ea 100644 --- a/lib/devise/models/authenticatable.rb +++ b/lib/devise/models/authenticatable.rb @@ -1,4 +1,7 @@ +# frozen_string_literal: true + require 'devise/hooks/activatable' +require 'devise/hooks/csrf_cleaner' module Devise module Models @@ -6,36 +9,37 @@ 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]. # + # * +http_authentication_key+: map the username passed via HTTP Auth to this parameter. Defaults to + # the first element in +authentication_keys+. + # # * +request_keys+: parameters from the request object used for authentication. # By specifying a symbol (which should be a request method), it will automatically be # passed to find_for_authentication method and considered in your model lookup. # # For instance, if you set :request_keys to [:subdomain], :subdomain will be considered - # as key on authentication. This can also be a hash where the value is a boolean expliciting + # as key on authentication. This can also be a hash where the value is a boolean specifying # if the value is required or not. # - # * +http_authenticatable+: if this model allows http authentication. By default true. + # * +http_authenticatable+: if this model allows http authentication. By default false. # It also accepts an array specifying the strategies that should allow http. # # * +params_authenticatable+: if this model allows authentication through request params. By default true. # It also accepts an array specifying the strategies that should allow params authentication. # # * +skip_session_storage+: By default Devise will store the user in session. - # You can skip storage for http and token auth by appending values to array: - # :skip_session_storage => [:token_auth] or :skip_session_storage => [:http_auth, :token_auth], - # by default is set to :skip_session_storage => [:http_auth]. + # By default is set to skip_session_storage: [:http_auth]. # # == active_for_authentication? # # After authenticating a user and in each request, Devise checks if your model is active by - # calling model.active_for_authentication?. This method is overwriten by other devise modules. For instance, + # calling model.active_for_authentication?. This method is overwritten by other devise modules. For instance, # :confirmable overwrites .active_for_authentication? to only return true if your model was confirmed. # - # You overwrite this method yourself, but if you do, don't forget to call super: + # You can overwrite this method yourself, but if you do, don't forget to call super: # # def active_for_authentication? # super && special_condition_is_valid? @@ -51,13 +55,13 @@ 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, :authentication_token] + :remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at] included do - class_attribute :devise_modules, :instance_writer => false + class_attribute :devise_modules, instance_writer: false self.devise_modules ||= [] before_validation :downcase_keys @@ -93,33 +97,31 @@ def inactive_message def authenticatable_salt end - def headers_for(name) - {} + # Redefine serializable_hash in models for more secure defaults. + # By default, it removes from the serializable model all attributes that + # are *not* accessible. You can remove this default by using :force_except + # 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.try(:dup) || {} + options[:except] = Array(options[:except]).dup + + if options[:force_except] + options[:except].concat Array(options[:force_except]) + else + options[:except].concat UNSAFE_ATTRIBUTES_FOR_SERIALIZATION + end + + super(options) end - array = %w(serializable_hash) - # to_xml does not call serializable_hash on 3.1 - array << "to_xml" if Rails::VERSION::STRING[0,3] == "3.1" - - array.each do |method| - class_eval <<-RUBY, __FILE__, __LINE__ - # Redefine to_xml and serializable_hash in models for more secure defaults. - # By default, it removes from the serializable model all attributes that - # are *not* accessible. You can remove this default by using :force_except - # 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 #{method}(options=nil) - options ||= {} - options[:except] = Array(options[:except]) - - if options[:force_except] - options[:except].concat Array(options[:force_except]) - else - options[:except].concat BLACKLIST_FOR_SERIALIZATION - end - super(options) - end - RUBY + # Redefine inspect using serializable_hash, to ensure we don't accidentally + # leak passwords into exceptions. + def inspect + inspection = serializable_hash.collect do |k,v| + "#{k}: #{respond_to?(:attribute_for_inspect) ? attribute_for_inspect(k) : v.inspect}" + end + "#<#{self.class} #{inspection.join(", ")}>" end protected @@ -129,51 +131,96 @@ def devise_mailer end # This is an internal method called every time Devise needs - # to send a notification/mail. This can be overriden if you + # 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 # - # def send_devise_notification(notification) - # pending_notifications << notification + # def send_devise_notification(notification, *args) + # # 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. + # # For Rails < 6 use `changed?` instead of `saved_changes?`. + # if new_record? || saved_changes? + # pending_devise_notifications << [notification, args] + # else + # render_and_send_devise_message(notification, *args) + # end # end # - # def send_pending_notifications - # pending_notifications.each do |n| - # devise_mailer.send(n, self).deliver + # 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_devise_notifications.clear + # end + # + # def pending_devise_notifications + # @pending_devise_notifications ||= [] # end # - # def pending_notifications - # @pending_notifications ||= [] + # 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) - devise_mailer.send(notification, self).deliver + def send_devise_notification(notification, *args) + message = devise_mailer.send(notification, self, *args) + message.deliver_now end def downcase_keys - self.class.case_insensitive_keys.each { |k| self[k].try(:downcase!) } + self.class.case_insensitive_keys.each { |k| apply_to_attribute_or_variable(k, :downcase) } end def strip_whitespace - self.class.strip_whitespace_keys.each { |k| self[k].try(:strip!) } + self.class.strip_whitespace_keys.each { |k| apply_to_attribute_or_variable(k, :strip) } + end + + def apply_to_attribute_or_variable(attr, method) + if self[attr] + self[attr] = self[attr].try(method) + + # Use respond_to? here to avoid a regression where globally + # configured strip_whitespace_keys or case_insensitive_keys were + # attempting to strip or downcase when a model didn't have the + # globally configured key. + elsif respond_to?(attr) && respond_to?("#{attr}=") + new_value = send(attr).try(method) + send("#{attr}=", new_value) + end end module ClassMethods Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys, - :case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage) + :case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage, + :http_authentication_key) def serialize_into_session(record) [record.to_key, record.authenticatable_salt] @@ -199,68 +246,55 @@ def http_authenticatable?(strategy) # it may be wrapped as well. For instance, database authenticatable # provides a `find_for_database_authentication` that wraps a call to # this method. This allows you to customize both database authenticatable - # or the whole authenticate stack by customize `find_for_authentication.` + # or the whole authenticate stack by customize `find_for_authentication.` # # Overwrite to add customized conditions, create a join, or maybe use a # namedscope to filter records while authenticating. # Example: # - # def self.find_for_authentication(conditions={}) - # conditions[:active] = true - # super + # def self.find_for_authentication(tainted_conditions) + # find_first_by_auth_conditions(tainted_conditions, active: true) # 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(conditions) - find_first_by_auth_conditions(conditions) + def find_for_authentication(tainted_conditions) + find_first_by_auth_conditions(tainted_conditions) end - def find_first_by_auth_conditions(conditions) - to_adapter.find_first devise_param_filter.filter(conditions) + def find_first_by_auth_conditions(tainted_conditions, opts = {}) + to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts)) end - # Find an initialize a record setting an error if it can't be found. - def find_or_initialize_with_error_by(attribute, value, error=:invalid) #:nodoc: + # 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: find_or_initialize_with_errors([attribute], { attribute => value }, error) end - # Find an initialize a group of attributes based on a list of required attributes. - def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc: - attributes = attributes.slice(*required_attributes) - attributes.delete_if { |key, value| value.blank? } + # 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.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 - def devise_param_filter - @devise_param_filter ||= Devise::ParamFilter.new(case_insensitive_keys, strip_whitespace_keys) - end - - # Generate a token by looping and ensuring does not already exist. - def generate_token(column) - loop do - token = Devise.friendly_token - break token unless to_adapter.find_first({ column => token }) - end + def devise_parameter_filter + @devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys) end end end diff --git a/lib/devise/models/confirmable.rb b/lib/devise/models/confirmable.rb index f21ecb7f31..6ce22c30f0 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 @@ -5,38 +7,64 @@ module Models # Confirmation instructions are sent to the user email after creating a # record and when manually requested by a new confirmation instruction request. # + # Confirmable tracks the following columns: + # + # * confirmation_token - A unique random token + # * confirmed_at - A timestamp when the user clicked the confirmation link + # * confirmation_sent_at - A timestamp when the confirmation_token was generated (not sent) + # * unconfirmed_email - An email address copied from the email attr. After confirmation + # this value is copied to the email attr then cleared + # # == Options # - # Confirmable adds the following options to devise_for: + # Confirmable adds the following options to +devise+: # - # * +allow_unconfirmed_access_for+: the time you want to allow the user to access his account + # * +allow_unconfirmed_access_for+: the time you want to allow the user to access their account # before confirming it. After this period, the user access is denied. You can # use this to let your user access some features of your application without # confirming the account, but blocking it after a certain period (ie 7 days). # By default allow_unconfirmed_access_for is zero, it means users always have to confirm to sign in. # * +reconfirmable+: requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email - # db field to be setup (t.reconfirmable in migrations). Until confirmed new email is + # db field to be set up (t.reconfirmable in migrations). Until confirmed, new email is # stored in unconfirmed email column, and copied to email column on successful - # confirmation. + # 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. # * +confirm_within+: the time before a sent confirmation token becomes invalid. # You can use this to force the user to confirm within a set period of time. + # Confirmable will not generate a new token if a repeat confirmation is requested + # during this time frame, unless the user's email changed too. # # == Examples # - # User.find(1).confirm! # returns true unless it's already confirmed + # User.find(1).confirm # returns true unless it's already confirmed # User.find(1).confirmed? # true/false # User.find(1).send_confirmation_instructions # manually send instructions # module Confirmable extend ActiveSupport::Concern - include ActionView::Helpers::DateHelper included do - before_create :generate_confirmation_token, :if => :confirmation_required? - after_create :send_on_create_confirmation_instructions, :if => :confirmation_required? - before_update :postpone_email_change_until_confirmation, :if => :postpone_email_change? - after_update :send_confirmation_instructions, :if => :reconfirmation_required? + before_create :generate_confirmation_token, if: :confirmation_required? + after_create :skip_reconfirmation_in_callback!, if: :send_confirmation_notification? + 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 + after_create :send_on_create_confirmation_instructions, if: :send_confirmation_notification? + after_update :send_reconfirmation_instructions, if: :reconfirmation_required? + end + before_update :postpone_email_change_until_confirmation_and_regenerate_confirmation_token, if: :postpone_email_change? + end + + def initialize(*args, &block) + @bypass_confirmation_postpone = false + @skip_reconfirmation_in_callback = false + @reconfirmation_required = false + @skip_confirmation_notification = false + @raw_confirmation_token = nil + super end def self.required_fields(klass) @@ -48,27 +76,29 @@ 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! + def confirm(args = {}) pending_any_confirmation do if confirmation_period_expired? self.errors.add(:email, :confirmation_period_expired, - :period => Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago)) + period: Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago)) return false end - self.confirmation_token = nil self.confirmed_at = Time.now.utc - if self.class.reconfirmable && unconfirmed_email.present? + saved = if pending_reconfirmation? skip_reconfirmation! self.email = unconfirmed_email self.unconfirmed_email = nil # We need to validate in such cases to enforce e-mail uniqueness - save(:validate => true) + save(validate: true) else - save(:validate => false) + save(validate: args[:ensure_valid] == true) end + + after_confirmation if saved + saved end end @@ -83,17 +113,26 @@ def pending_reconfirmation? # Send confirmation instructions by email def send_confirmation_instructions - self.confirmation_token = nil if reconfirmation_required? + unless @raw_confirmation_token + generate_confirmation_token! + end + + opts = pending_reconfirmation? ? { to: unconfirmed_email } : { } + send_devise_notification(:confirmation_instructions, @raw_confirmation_token, opts) + end + + def send_reconfirmation_instructions @reconfirmation_required = false - generate_confirmation_token! if self.confirmation_token.blank? - send_devise_notification(:confirmation_instructions) + unless @skip_confirmation_notification + send_confirmation_instructions + end end - # Resend confirmation token. This method does not need to generate a new token. - def resend_confirmation_token + # Resend confirmation token. + # Regenerates the token if the period is expired. + def resend_confirmation_instructions pending_any_confirmation do - self.confirmation_token = nil if confirmation_period_expired? send_confirmation_instructions end end @@ -117,27 +156,31 @@ def skip_confirmation! self.confirmed_at = Time.now.utc end + # Skips sending the confirmation/reconfirmation notification email after_create/after_update. Unlike + # #skip_confirmation!, record still requires confirmation. + def skip_confirmation_notification! + @skip_confirmation_notification = true + end + # If you don't want reconfirmation to be sent, neither a code # to be generated, call skip_reconfirmation! def skip_reconfirmation! - @bypass_postpone = true - end - - def headers_for(action) - headers = super - if action == :confirmation_instructions && pending_reconfirmation? - headers[:to] = unconfirmed_email - end - headers + @bypass_confirmation_postpone = true end protected + # To not require reconfirmation after creating with #save called in a + # callback call skip_create_confirmation! + def skip_reconfirmation_in_callback! + @skip_reconfirmation_in_callback = true + end + # A callback method used to deliver confirmation - # instructions on creation. This can be overriden + # instructions on creation. This can be overridden # in models to map to a nice sign up e-mail. def send_on_create_confirmation_instructions - send_devise_notification(:confirmation_instructions) + send_confirmation_instructions end # Callback to overwrite if confirmation is required or not. @@ -148,7 +191,7 @@ def confirmation_required? # Checks if the confirmation for the user is within the limit time. # We do this by calculating if the difference between today and the # confirmation sent date does not exceed the confirm in time configured. - # Confirm_within is a model configuration, must always be an integer value. + # allow_unconfirmed_access_for is a model configuration, must always be an integer value. # # Example: # @@ -164,7 +207,13 @@ def confirmation_required? # # allow_unconfirmed_access_for = 0.days # confirmation_period_valid? # will always return false # + # # allow_unconfirmed_access_for = nil + # confirmation_period_valid? # will always return true + # def confirmation_period_valid? + 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 @@ -181,7 +230,7 @@ def confirmation_period_valid? # confirmation_period_expired? # will always return false # def confirmation_period_expired? - self.class.confirm_within && (Time.now > self.confirmation_sent_at + self.class.confirm_within ) + self.class.confirm_within && self.confirmation_sent_at && (Time.now.utc > self.confirmation_sent_at.utc + self.class.confirm_within) end # Checks whether the record requires any confirmation. @@ -194,36 +243,69 @@ def pending_any_confirmation end end - # Generates a new random token for confirmation, and stores the time - # this token is being generated + # Generates a new random token for confirmation, and stores + # the time this token is being generated in confirmation_sent_at def generate_confirmation_token - self.confirmation_token = self.class.confirmation_token - self.confirmation_sent_at = Time.now.utc + if self.confirmation_token && !confirmation_period_expired? + @raw_confirmation_token = self.confirmation_token + else + self.confirmation_token = @raw_confirmation_token = Devise.friendly_token + self.confirmation_sent_at = Time.now.utc + end end def generate_confirmation_token! - generate_confirmation_token && save(:validate => false) + generate_confirmation_token && save(validate: false) end - def after_password_reset - super - confirm! unless confirmed? - end - def postpone_email_change_until_confirmation + def postpone_email_change_until_confirmation_and_regenerate_confirmation_token @reconfirmation_required = true self.unconfirmed_email = self.email - self.email = self.email_was + self.email = self.devise_email_in_database + self.confirmation_token = nil + generate_confirmation_token end def postpone_email_change? - postpone = self.class.reconfirmable && email_changed? && !@bypass_postpone - @bypass_postpone = nil + 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? - self.class.reconfirmable && @reconfirmation_required + self.class.reconfirmable && @reconfirmation_required && (self.email.present? || self.unconfirmed_email.present?) + end + + def send_confirmation_notification? + confirmation_required? && !@skip_confirmation_notification && self.email.present? + end + + # With reconfirmable, notify the original email when the user first + # requests the email change, instead of when the change is confirmed. + def send_email_changed_notification? + if self.class.reconfirmable + self.class.send_email_changed_notification && reconfirmation_required? + else + super + end + end + + # A callback initiated after successfully confirming. This can be + # used to insert your own logic that is only run after the user successfully + # confirms. + # + # Example: + # + # def after_confirmation + # self.update_attribute(:invite_code, nil) + # end + # + def after_confirmation end module ClassMethods @@ -231,12 +313,12 @@ 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) end - confirmable.resend_confirmation_token if confirmable.persisted? + confirmable.resend_confirmation_instructions if confirmable.persisted? confirmable end @@ -245,18 +327,35 @@ 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) - confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_token) - confirmable.confirm! if confirmable.persisted? - confirmable - end + # 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) + end + + # TODO: replace above lines with + # confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_token) + # after enough time has passed that Devise clients do not use digested tokens - # Generate a token checking if one does not already exist in the database. - def confirmation_token - generate_token(:confirmation_token) + confirmable.confirm if confirmable.persisted? + confirmable end # Find a record for confirmation by unconfirmed email field def find_by_unconfirmed_email_with_errors(attributes = {}) + attributes = attributes.slice(*confirmation_keys).permit!.to_h if attributes.respond_to? :permit unconfirmed_required_attributes = confirmation_keys.map { |k| k == :email ? :unconfirmed_email : k } unconfirmed_attributes = attributes.symbolize_keys unconfirmed_attributes[:unconfirmed_email] = unconfirmed_attributes.delete(:email) diff --git a/lib/devise/models/database_authenticatable.rb b/lib/devise/models/database_authenticatable.rb index 349147a9a4..e16b7d8453 100644 --- a/lib/devise/models/database_authenticatable.rb +++ b/lib/devise/models/database_authenticatable.rb @@ -1,20 +1,29 @@ +# frozen_string_literal: true + require 'devise/strategies/database_authenticatable' -require 'bcrypt' module Devise module Models - # Authenticatable Module, responsible for encrypting password and validating - # authenticity of a user while signing in. + # 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 # - # DatabaseAuthenticable 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. # + # * +send_email_changed_notification+: notify original email when it changes. + # + # * +send_password_change_notification+: notify email when password changes. + # # == Examples # # User.find(1).valid_password?('password123') # returns true/false @@ -23,26 +32,44 @@ module DatabaseAuthenticatable extend ActiveSupport::Concern included do + after_update :send_email_changed_notification, if: :send_email_changed_notification? + after_update :send_password_change_notification, if: :send_password_change_notification? + attr_reader :password, :current_password 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 - # Generates password encryption based on the given value. + # Generates a hashed password based on the given value. + # For legacy reasons, we use `encrypted_password` to store + # the hashed password. def password=(new_password) @password = new_password self.encrypted_password = password_digest(@password) if @password.present? end - # Verifies whether an password (ie from sign in) is the user password. + # Verifies whether a password (ie from sign in) is the user password. def valid_password?(password) - return false if encrypted_password.blank? - bcrypt = ::BCrypt::Password.new(encrypted_password) - password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt) - Devise.secure_compare(password, encrypted_password) + Devise::Encryptor.compare(self.class, encrypted_password, password) end # Set password and password confirmation to nil @@ -50,10 +77,14 @@ def clean_up_passwords self.password = self.password_confirmation = nil end - # Update record attributes when :current_password matches, otherwise returns - # error on :current_password. It also automatically rejects :password and - # :password_confirmation if they are blank. - def update_with_password(params, *options) + # Update record attributes when :current_password matches, otherwise + # returns error on :current_password. + # + # This method also rejects the password field if it is blank (allowing + # 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) current_password = params.delete(:current_password) if params[:password].blank? @@ -62,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 @@ -75,26 +106,51 @@ def update_with_password(params, *options) end # Updates record attributes without asking for the current password. - # Never allows to change the current password. If you are using this + # Never allows a change to the current password. If you are using this # method, you should probably override this method to protect other # attributes you would not like to be updated without a password. # # Example: # - # def update_without_password(params={}) + # 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 + # Destroy record when :current_password matches, otherwise returns + # error on :current_password. It also automatically rejects + # :current_password if it is blank. + def destroy_with_password(current_password) + result = if valid_password?(current_password) + destroy + else + valid? + errors.add(:current_password, current_password.blank? ? :blank : :invalid) + false + end + + result + end + + # A callback initiated after successfully authenticating. This can be + # used to insert your own logic that is only run after the user successfully + # authenticates. + # + # Example: + # + # def after_database_authentication + # self.update_attribute(:invite_code, nil) + # end + # def after_database_authentication end @@ -103,15 +159,37 @@ def authenticatable_salt encrypted_password[0,29] if encrypted_password 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. + def send_password_change_notification + send_devise_notification(:password_change) + end + protected - # Digests the password using bcrypt. + # Hashes the password using bcrypt. Custom hash functions should override + # this method to apply their own algorithm. + # + # See https://github.com/heartcombo/devise-encryptable for examples + # of other hashing engines. def password_digest(password) - ::BCrypt::Password.create("#{password}#{self.class.pepper}", :cost => self.class.stretches).to_s + Devise::Encryptor.digest(self.class, password) + end + + def send_email_changed_notification? + self.class.send_email_changed_notification && devise_saved_change_to_email? && !@skip_email_changed_notification + 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 - Devise::Models.config(self, :pepper, :stretches) + Devise::Models.config(self, :pepper, :stretches, :send_email_changed_notification, :send_password_change_notification) # We assume this method already gets the sanitized values from the # DatabaseAuthenticatable strategy. If you are using this method on diff --git a/lib/devise/models/lockable.rb b/lib/devise/models/lockable.rb index 98b810f830..6ab0ce747e 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 @@ -7,7 +9,7 @@ module Models # blocked: email and time. The former will send an email to the user when # the lock happens, containing a link to unlock its account. The second # will unlock the user automatically after some configured time (ie 2.hours). - # It's also possible to setup lockable to use both email and time strategies. + # It's also possible to set up lockable to use both email and time strategies. # # == Options # @@ -16,13 +18,13 @@ 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 extend ActiveSupport::Concern - delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, :to => "self.class" + delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, to: "self.class" def self.required_fields(klass) attributes = [] @@ -34,14 +36,16 @@ def self.required_fields(klass) end # Lock a user setting its locked_at to actual time. - def lock_access! + # * +opts+: Hash options if you don't want to send email + # when you lock access, you could pass the next hash + # `{ send_instructions: false } as option`. + def lock_access!(opts = { }) self.locked_at = Time.now.utc - if unlock_strategy_enabled?(:email) - generate_unlock_token! + if unlock_strategy_enabled?(:email) && opts.fetch(:send_instructions, true) send_unlock_instructions else - save(:validate => false) + save(validate: false) end end @@ -50,25 +54,37 @@ def unlock_access! self.locked_at = nil self.failed_attempts = 0 if respond_to?(:failed_attempts=) self.unlock_token = nil if respond_to?(:unlock_token=) - save(:validate => false) + 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? + !!locked_at && !lock_expired? end # Send unlock instructions by email def send_unlock_instructions - send_devise_notification(:unlock_instructions) + raw, enc = Devise.token_generator.generate(self.class, :unlock_token) + self.unlock_token = enc + save(validate: false) + send_devise_notification(:unlock_instructions, raw, {}) + raw end # Resend the unlock instructions if the user is locked. - def resend_unlock_token + 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? @@ -93,20 +109,30 @@ 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 - save(:validate => false) + save(validate: false) end false end end + def increment_failed_attempts + self.class.increment_counter(:failed_attempts, id) + reload + end + def unauthenticated_message - if lock_strategy_enabled?(:failed_attempts) && attempts_exceeded? + # If set to paranoid mode, do not show the locked message because it + # leaks the existence of an account. + if Devise.paranoid + super + elsif access_locked? || (lock_strategy_enabled?(:failed_attempts) && attempts_exceeded?) :locked + elsif lock_strategy_enabled?(:failed_attempts) && last_attempt? && self.class.last_attempt_warning + :last_attempt else super end @@ -115,16 +141,11 @@ def unauthenticated_message protected def attempts_exceeded? - self.failed_attempts > self.class.maximum_attempts + self.failed_attempts >= self.class.maximum_attempts end - # Generates unlock token - def generate_unlock_token - self.unlock_token = self.class.unlock_token - end - - def generate_unlock_token! - generate_unlock_token && save(:validate => false) + def last_attempt? + self.failed_attempts == self.class.maximum_attempts - 1 end # Tells if the lock is expired if :time unlock strategy is active @@ -142,19 +163,22 @@ def if_access_locked if access_locked? yield else - self.errors.add(:email, :not_locked) + self.errors.add(Devise.unlock_keys.first, :not_locked) false end end module ClassMethods - # Attempt to find a user by its email. If a record is found, send new + # List of strategies that are enabled/supported if :both is used. + BOTH_STRATEGIES = [:time, :email] + + # Attempt to find a user by its unlock keys. If a record is found, send new # unlock instructions to it. If not user is found, returns a new user # with an email not found error. - # Options must contain the user email - def send_unlock_instructions(attributes={}) + # Options must contain the user's unlock keys + def send_unlock_instructions(attributes = {}) lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found) - lockable.resend_unlock_token if lockable.persisted? + lockable.resend_unlock_instructions if lockable.persisted? lockable end @@ -163,14 +187,19 @@ def send_unlock_instructions(attributes={}) # If the user is not locked, creates an error for the user # Options must have the unlock_token def unlock_access_by_token(unlock_token) + original_token = unlock_token + unlock_token = Devise.token_generator.digest(self, :unlock_token, unlock_token) + lockable = find_or_initialize_with_error_by(:unlock_token, unlock_token) lockable.unlock_access! if lockable.persisted? + lockable.unlock_token = original_token lockable end # Is the unlock enabled for the given unlock strategy? def unlock_strategy_enabled?(strategy) - [:both, strategy].include?(self.unlock_strategy) + self.unlock_strategy == strategy || + (self.unlock_strategy == :both && BOTH_STRATEGIES.include?(strategy)) end # Is the lock enabled for the given lock strategy? @@ -178,11 +207,7 @@ def lock_strategy_enabled?(strategy) self.lock_strategy == strategy end - def unlock_token - Devise.friendly_token - end - - Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys) + Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys, :last_attempt_warning) end end end diff --git a/lib/devise/models/omniauthable.rb b/lib/devise/models/omniauthable.rb index d1a2d4ae90..6f4c8976d5 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 avaialble to this model. It expects an array: + # * +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 @@ -24,4 +26,4 @@ module ClassMethods end end end -end \ No newline at end of file +end diff --git a/lib/devise/models/recoverable.rb b/lib/devise/models/recoverable.rb index 0bed681ea9..b17c42aae6 100644 --- a/lib/devise/models/recoverable.rb +++ b/lib/devise/models/recoverable.rb @@ -1,22 +1,22 @@ +# frozen_string_literal: true + module Devise module Models - # Recoverable takes care of reseting the user password and send reset instructions. + # Recoverable takes care of resetting the user password and send reset instructions. # # ==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. + # * +sign_in_after_reset_password+: whether or not to sign in the user automatically after a password reset. # # == Examples # # # resets the user password and save the record, true if valid passwords are given, otherwise false - # User.find(1).reset_password!('password123', 'password123') - # - # # only resets the user password, without saving the record - # user = User.find(1) - # user.reset_password('password123', 'password123') + # User.find(1).reset_password('password123', 'password123') # # # creates a new token and send it with instructions about how to reset the password # User.find(1).send_reset_password_instructions @@ -28,24 +28,30 @@ def self.required_fields(klass) [:reset_password_sent_at, :reset_password_token] end + included do + before_update :clear_reset_password_token, if: :clear_reset_password_token? + end + # Update password saving the record and clearing token. Returns true if # the passwords are valid and the record was saved, false otherwise. - def reset_password!(new_password, new_password_confirmation) - self.password = new_password - self.password_confirmation = new_password_confirmation - - if valid? - clear_reset_password_token - after_password_reset + def reset_password(new_password, new_password_confirmation) + if new_password.present? + self.password = new_password + self.password_confirmation = new_password_confirmation + save + else + errors.add(:password, :blank) + false end - - save end - # Resets reset password token and send reset password instructions by email + # Resets reset password token and send reset password instructions by email. + # Returns the token sent in the e-mail. def send_reset_password_instructions - generate_reset_password_token! if should_generate_reset_token? - send_devise_notification(:reset_password_instructions) + token = set_reset_password_token + send_reset_password_instructions_notification(token) + + token end # Checks if the reset password token sent is within the limit time. @@ -69,71 +75,81 @@ def send_reset_password_instructions # reset_password_period_valid? # will always return false # def reset_password_period_valid? - reset_password_sent_at && reset_password_sent_at.utc >= self.class.reset_password_within.ago + reset_password_sent_at && reset_password_sent_at.utc >= self.class.reset_password_within.ago.utc end protected - def should_generate_reset_token? - reset_password_token.nil? || !reset_password_period_valid? + # Removes reset_password token + def clear_reset_password_token + self.reset_password_token = nil + self.reset_password_sent_at = nil end - # Generates a new random token for reset password - def generate_reset_password_token - self.reset_password_token = self.class.reset_password_token + def set_reset_password_token + raw, enc = Devise.token_generator.generate(self.class, :reset_password_token) + + self.reset_password_token = enc self.reset_password_sent_at = Time.now.utc - self.reset_password_token + save(validate: false) + raw end - # Resets the reset password token with and save the record without - # validating - def generate_reset_password_token! - generate_reset_password_token && save(:validate => false) + def send_reset_password_instructions_notification(token) + send_devise_notification(:reset_password_instructions, token, {}) end - # Removes reset_password token - def clear_reset_password_token - self.reset_password_token = nil - self.reset_password_sent_at = nil - end + 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 - def after_password_reset + authentication_keys_changed || encrypted_password_changed end module ClassMethods + # Attempt to find a user by password reset token. If a user is found, return it + # If a user is not found, return nil + def with_reset_password_token(token) + reset_password_token = Devise.token_generator.digest(self, :reset_password_token, token) + to_adapter.find_first(reset_password_token: reset_password_token) + end + # Attempt to find a user by its email. If a record is found, send new - # password instructions to it. If not user is found, returns a new user + # password instructions to it. If user is not found, returns a new user # with an email not found error. - # Attributes must contain the user email - def send_reset_password_instructions(attributes={}) + # Attributes must contain the user's email + 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 end - # Generate a token checking if one does not already exist in the database. - def reset_password_token - generate_token(:reset_password_token) - end - # Attempt to find a user by its reset_password_token to reset its # password. If a user is found and token is still valid, reset its password and automatically # 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={}) - recoverable = find_or_initialize_with_error_by(:reset_password_token, attributes[:reset_password_token]) + 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) + + recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token) + if recoverable.persisted? if recoverable.reset_password_period_valid? - recoverable.reset_password!(attributes[:password], attributes[:password_confirmation]) + recoverable.reset_password(attributes[:password], attributes[:password_confirmation]) else recoverable.errors.add(:reset_password_token, :expired) end end + + recoverable.reset_password_token = original_token if recoverable.reset_password_token.present? recoverable end - Devise::Models.config(self, :reset_password_keys, :reset_password_within) + Devise::Models.config(self, :reset_password_keys, :reset_password_within, :sign_in_after_reset_password) end end end diff --git a/lib/devise/models/registerable.rb b/lib/devise/models/registerable.rb index 1f10dd2e69..e55dac2723 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 b9e433868a..a66979ad59 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,11 +15,11 @@ 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 - # will have to enter his credentials again. This configuration is also + # will have to enter their credentials again. This configuration is also # used to calculate the expires time for the cookie created to remember # the user. By default remember_for is 2.weeks. # @@ -39,46 +41,42 @@ module Models module Rememberable extend ActiveSupport::Concern - attr_accessor :remember_me, :extend_remember_period + attr_accessor :remember_me def self.required_fields(klass) [:remember_created_at] end - # Generate a new remember token and save the record without validations - # unless remember_across_browsers is true and the user already has a valid token. - def remember_me!(extend_period=false) - self.remember_token = self.class.remember_token if generate_remember_token? - self.remember_created_at = Time.now.utc if generate_remember_timestamp?(extend_period) - save(:validate => false) + def remember_me! + self.remember_token ||= self.class.remember_token if respond_to?(:remember_token) + self.remember_created_at ||= Time.now.utc + save(validate: false) if self.changed? end # If the record is persisted, remove the remember token (but only if # it exists), and save the record without validations. def forget_me! return unless persisted? - self.remember_token = nil if respond_to?(:remember_token=) - self.remember_created_at = nil - save(:validate => false) + self.remember_token = nil if respond_to?(:remember_token) + self.remember_created_at = nil if self.class.expire_all_remember_me_on_sign_out + save(validate: false) end - # Remember token should be expired if expiration time not overpass now. - def remember_expired? - remember_created_at.nil? || (remember_expires_at <= Time.now.utc) + def remember_expires_at + self.class.remember_for.from_now end - # Remember token expires at created time + remember_for configuration - def remember_expires_at - remember_created_at + self.class.remember_for + def extend_remember_period + self.class.extend_remember_period end def rememberable_value if respond_to?(:remember_token) remember_token - elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt) + elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt.presence) salt else - raise "authenticable_salt returned nil for the #{self.class.name} model. " \ + raise "authenticatable_salt returned nil for the #{self.class.name} model. " \ "In order to use rememberable, you must ensure a password is always set " \ "or have a remember_token column in your model or implement your own " \ "rememberable_value in the model with custom logic." @@ -89,36 +87,71 @@ def rememberable_options self.class.rememberable_options end - protected + # A callback initiated after successfully being remembered. This can be + # used to insert your own logic that is only run after the user is + # remembered. + # + # Example: + # + # def after_remembered + # self.update_attribute(:invite_code, nil) + # end + # + def after_remembered + end + + def remember_me?(token, generated_at) + # TODO: Normalize the JSON type coercion along with the Timeoutable hook + # 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 - def generate_remember_token? #:nodoc: - respond_to?(:remember_token) && remember_expired? + # The token is only valid if: + # 1. we have a date + # 2. the current time does not pass the expiry period + # 3. the record has a remember_created_at date + # 4. the token date is bigger than the remember_created_at + # 5. the token matches + generated_at.is_a?(Time) && + (self.class.remember_for.ago < generated_at) && + (generated_at > (remember_created_at || Time.now).utc) && + Devise.secure_compare(rememberable_value, token) end - # Generate a timestamp if extend_remember_period is true, if no remember_token - # exists, or if an existing remember token has expired. - def generate_remember_timestamp?(extend_period) #:nodoc: - extend_period || remember_created_at.nil? || remember_expired? + private + + def time_from_json(value) + if value =~ /\A\d+\.\d+\Z/ + Time.at(value.to_f) + else + Time.parse(value) rescue nil + end end module ClassMethods # Create the cookie key using the record id and remember_token def serialize_into_cookie(record) - [record.to_key, record.rememberable_value] + [record.to_key, record.rememberable_value, Time.now.utc.to_f.to_s] end # Recreate the user based on the stored cookie - def serialize_from_cookie(id, remember_token) + def serialize_from_cookie(*args) + id, token, generated_at = *args + record = to_adapter.get(id) - record if record && record.rememberable_value == remember_token && !record.remember_expired? + record if record && record.remember_me?(token, generated_at) end # Generate a token checking if one does not already exist in the database. def remember_token #:nodoc: - generate_token(:remember_token) + loop do + token = Devise.friendly_token + break token unless to_adapter.find_first({ remember_token: token }) + end end - Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options) + Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options, :expire_all_remember_me_on_sign_out) end end end diff --git a/lib/devise/models/timeoutable.rb b/lib/devise/models/timeoutable.rb index d595323c95..1d3ce2ae97 100644 --- a/lib/devise/models/timeoutable.rb +++ b/lib/devise/models/timeoutable.rb @@ -1,15 +1,17 @@ +# frozen_string_literal: true + require 'devise/hooks/timeoutable' module Devise module Models - # Timeoutable takes care of veryfing whether a user session has already + # Timeoutable takes care of verifying whether a user session has already # expired or not. When a session expires after the configured time, the user - # will be asked for credentials again, it means, he/she will be redirected + # will be asked for credentials again, it means, they will be redirected # to the sign in page. # # == 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. # @@ -26,7 +28,6 @@ def self.required_fields(klass) # Checks whether the user session has expired based on configured time. def timedout?(last_access) - return false if remember_exists_and_not_expired? !timeout_in.nil? && last_access && last_access <= timeout_in.ago end @@ -36,11 +37,6 @@ def timeout_in private - def remember_exists_and_not_expired? - return false unless respond_to?(:remember_created_at) - remember_created_at && !remember_expired? - end - module ClassMethods Devise::Models.config(self, :timeout_in) end diff --git a/lib/devise/models/token_authenticatable.rb b/lib/devise/models/token_authenticatable.rb deleted file mode 100644 index ffe4d30141..0000000000 --- a/lib/devise/models/token_authenticatable.rb +++ /dev/null @@ -1,89 +0,0 @@ -require 'devise/strategies/token_authenticatable' - -module Devise - module Models - # The TokenAuthenticatable module is responsible for generating an authentication token and - # validating the authenticity of the same while signing in. - # - # This module only provides a few helpers to help you manage the token, but it is up to you - # to choose how to use it. For example, if you want to have a new token every time the user - # saves his account, you can do the following: - # - # before_save :reset_authentication_token - # - # On the other hand, if you want to generate token unless one exists, you should use instead: - # - # before_save :ensure_authentication_token - # - # If you want to delete the token after it is used, you can do so in the - # after_token_authentication callback. - # - # == APIs - # - # If you are using token authentication with APIs and using trackable. Every - # request will be considered as a new sign in (since there is no session in - # APIs). You can disable this by creating a before filter as follow: - # - # before_filter :skip_trackable - # - # def skip_trackable - # request.env['devise.skip_trackable'] = true - # end - # - # == Options - # - # TokenAuthenticatable adds the following options to devise_for: - # - # * +token_authentication_key+: Defines name of the authentication token params key. E.g. /users/sign_in?some_key=... - # - module TokenAuthenticatable - extend ActiveSupport::Concern - - def self.required_fields(klass) - [:authentication_token] - end - - # Generate new authentication token (a.k.a. "single access token"). - def reset_authentication_token - self.authentication_token = self.class.authentication_token - end - - # Generate new authentication token and save the record. - def reset_authentication_token! - reset_authentication_token - save(:validate => false) - end - - # Generate authentication token unless already exists. - def ensure_authentication_token - reset_authentication_token if authentication_token.blank? - end - - # Generate authentication token unless already exists and save the record. - def ensure_authentication_token! - reset_authentication_token! if authentication_token.blank? - end - - # Hook called after token authentication. - def after_token_authentication - end - - def expire_auth_token_on_timeout - self.class.expire_auth_token_on_timeout - end - - module ClassMethods - def find_for_token_authentication(conditions) - find_for_authentication(:authentication_token => conditions[token_authentication_key]) - end - - # Generate a token checking if one does not already exist in the database. - def authentication_token - generate_token(:authentication_token) - end - - Devise::Models.config(self, :token_authentication_key, :expire_auth_token_on_timeout) - end - end - end -end diff --git a/lib/devise/models/trackable.rb b/lib/devise/models/trackable.rb index cfb70476a0..2328597c30 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 @@ -15,21 +17,35 @@ def self.required_fields(klass) [:current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count] end - def update_tracked_fields!(request) + def update_tracked_fields(request) old_current, new_current = self.current_sign_in_at, Time.now.utc 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 self.sign_in_count ||= 0 self.sign_in_count += 1 + 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? - save(:validate => false) or raise "Devise trackable could not save #{inspect}." \ - "Please make sure a model using trackable can be saved at sign in." + 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 bc8ae22553..62486cfbe0 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,15 +9,17 @@ 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..128. + # * +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, - :validates_confirmation_of, :validates_length_of ].freeze + VALIDATIONS = [:validates_presence_of, :validates_uniqueness_of, :validates_format_of, + :validates_confirmation_of, :validates_length_of].freeze def self.required_fields(klass) [] @@ -26,13 +30,13 @@ def self.included(base) assert_validations_api!(base) base.class_eval do - validates_presence_of :email, :if => :email_required? - validates_uniqueness_of :email, :allow_blank => true, :if => :email_changed? - validates_format_of :email, :with => email_regexp, :allow_blank => true, :if => :email_changed? + validates_presence_of :email, if: :email_required? + 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_presence_of :password, if: :password_required? + validates_confirmation_of :password, if: :password_required? + validates_length_of :password, minimum: proc { password_length.min }, maximum: proc { password_length.max }, allow_blank: true end end @@ -40,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 1c620ca35b..d8cde834c1 100644 --- a/lib/devise/modules.rb +++ b/lib/devise/modules.rb @@ -1,29 +1,30 @@ +# frozen_string_literal: true + require 'active_support/core_ext/object/with_options' -Devise.with_options :model => true do |d| +Devise.with_options model: true do |d| # Strategies first - d.with_options :strategy => true do |s| + d.with_options strategy: true do |s| routes = [nil, :new, :destroy] - s.add_module :database_authenticatable, :controller => :sessions, :route => { :session => routes } - s.add_module :token_authenticatable, :controller => :sessions, :route => { :session => routes }, :no_input => true - s.add_module :rememberable, :no_input => true + s.add_module :database_authenticatable, controller: :sessions, route: { session: routes } + s.add_module :rememberable, no_input: true end # Other authentications - d.add_module :omniauthable, :controller => :omniauth_callbacks, :route => :omniauth_callback + d.add_module :omniauthable, controller: :omniauth_callbacks, route: :omniauth_callback # Misc after routes = [nil, :new, :edit] - d.add_module :recoverable, :controller => :passwords, :route => { :password => routes } - d.add_module :registerable, :controller => :registrations, :route => { :registration => (routes << :cancel) } + d.add_module :recoverable, controller: :passwords, route: { password: routes } + d.add_module :registerable, controller: :registrations, route: { registration: (routes << :cancel) } d.add_module :validatable # The ones which can sign out after routes = [nil, :new] - d.add_module :confirmable, :controller => :confirmations, :route => { :confirmation => routes } - d.add_module :lockable, :controller => :unlocks, :route => { :unlock => routes } + d.add_module :confirmable, controller: :confirmations, route: { confirmation: routes } + d.add_module :lockable, controller: :unlocks, route: { unlock: routes } d.add_module :timeoutable # Stats for last, so we make sure the user is really signed in d.add_module :trackable -end \ No newline at end of file +end diff --git a/lib/devise/omniauth.rb b/lib/devise/omniauth.rb index ff342fd73f..f18df3053c 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 e22d701ce5..2d3749ffdd 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 d7b3a36eae..72eac65ed3 100644 --- a/lib/devise/omniauth/url_helpers.rb +++ b/lib/devise/omniauth/url_helpers.rb @@ -1,17 +1,26 @@ +# frozen_string_literal: true + module Devise module OmniAuth module UrlHelpers - def self.define_helpers(mapping) + def omniauth_authorize_path(resource_or_scope, provider, *args) + scope = Devise::Mapping.find_scope!(resource_or_scope) + _devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_path", *args) + end + + def omniauth_authorize_url(resource_or_scope, provider, *args) + scope = Devise::Mapping.find_scope!(resource_or_scope) + _devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_url", *args) end - def omniauth_authorize_path(resource_or_scope, *args) + def omniauth_callback_path(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) - send("#{scope}_omniauth_authorize_path", *args) + _devise_route_context.send("#{scope}_#{provider}_omniauth_callback_path", *args) end - def omniauth_callback_path(resource_or_scope, *args) + def omniauth_callback_url(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) - send("#{scope}_omniauth_callback_path", *args) + _devise_route_context.send("#{scope}_#{provider}_omniauth_callback_url", *args) end end end diff --git a/lib/devise/orm.rb b/lib/devise/orm.rb new file mode 100644 index 0000000000..3f3ac86db7 --- /dev/null +++ b/lib/devise/orm.rb @@ -0,0 +1,69 @@ +# 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_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_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 52343d4f31..0fecf64e3f 100644 --- a/lib/devise/orm/active_record.rb +++ b/lib/devise/orm/active_record.rb @@ -1,3 +1,7 @@ +# frozen_string_literal: true + require 'orm_adapter/adapters/active_record' -ActiveRecord::Base.extend Devise::Models \ No newline at end of file +ActiveSupport.on_load(:active_record) do + extend Devise::Models +end diff --git a/lib/devise/orm/mongoid.rb b/lib/devise/orm/mongoid.rb index 858a915617..034501eff4 100644 --- a/lib/devise/orm/mongoid.rb +++ b/lib/devise/orm/mongoid.rb @@ -1,3 +1,7 @@ -require 'orm_adapter/adapters/mongoid' +# frozen_string_literal: true -Mongoid::Document::ClassMethods.send :include, Devise::Models \ No newline at end of file +ActiveSupport.on_load(:mongoid) do + require 'orm_adapter/adapters/mongoid' + + Mongoid::Document::ClassMethods.send :include, Devise::Models +end diff --git a/lib/devise/param_filter.rb b/lib/devise/parameter_filter.rb similarity index 56% rename from lib/devise/param_filter.rb rename to lib/devise/parameter_filter.rb index 5d0534928f..11e6f9c051 100644 --- a/lib/devise/param_filter.rb +++ b/lib/devise/parameter_filter.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + module Devise - class ParamFilter + class ParameterFilter def initialize(case_insensitive_keys, strip_whitespace_keys) @case_insensitive_keys = case_insensitive_keys || [] @strip_whitespace_keys = strip_whitespace_keys || [] @@ -8,16 +10,18 @@ def initialize(case_insensitive_keys, strip_whitespace_keys) def filter(conditions) conditions = stringify_params(conditions.dup) - @case_insensitive_keys.each do |k| - value = conditions[k] - next unless value.respond_to?(:downcase) - conditions[k] = value.downcase - end + conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :downcase, @case_insensitive_keys)) + conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :strip, @strip_whitespace_keys)) + + conditions + end + + def filtered_hash_by_method_for_given_keys(conditions, method, condition_keys) + condition_keys.each do |k| + next unless conditions.key?(k) - @strip_whitespace_keys.each do |k| value = conditions[k] - next unless value.respond_to?(:strip) - conditions[k] = value.strip + conditions[k] = value.send(method) if value.respond_to?(method) end conditions @@ -33,9 +37,8 @@ def stringify_params(conditions) private - # Determine which values should be transformed to string or passed as-is to the query builder underneath def param_requires_string_conversion?(value) - [Fixnum, TrueClass, FalseClass, Regexp].none? {|clz| value.is_a? clz } + true end end end diff --git a/lib/devise/parameter_sanitizer.rb b/lib/devise/parameter_sanitizer.rb new file mode 100644 index 0000000000..6d9523a4f5 --- /dev/null +++ b/lib/devise/parameter_sanitizer.rb @@ -0,0 +1,172 @@ +# frozen_string_literal: true + +module Devise + # The +ParameterSanitizer+ deals with permitting specific parameters values + # for each +Devise+ scope in the application. + # + # The sanitizer knows about Devise default parameters (like +password+ and + # +password_confirmation+ for the `RegistrationsController`), and you can + # extend or change the permitted parameters list on your controllers. + # + # === Permitting new parameters + # + # You can add new parameters to the permitted list using the +permit+ method + # in a +before_action+ method, for instance. + # + # class ApplicationController < ActionController::Base + # before_action :configure_permitted_parameters, if: :devise_controller? + # + # protected + # + # def configure_permitted_parameters + # # Permit the `subscribe_newsletter` parameter along with the other + # # sign up parameters. + # devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) + # end + # end + # + # Using a block yields an +ActionController::Parameters+ object so you can + # permit nested parameters and have more control over how the parameters are + # permitted in your controller. + # + # def configure_permitted_parameters + # devise_parameter_sanitizer.permit(:sign_up) do |user| + # user.permit(newsletter_preferences: []) + # end + # end + class ParameterSanitizer + DEFAULT_PERMITTED_ATTRIBUTES = { + sign_in: [:password, :remember_me], + sign_up: [:password, :password_confirmation], + account_update: [:password, :password_confirmation, :current_password] + } + + def initialize(resource_class, resource_name, params) + @auth_keys = extract_auth_keys(resource_class) + @params = params + @resource_name = resource_name + @permitted = {} + + DEFAULT_PERMITTED_ATTRIBUTES.each_pair do |action, keys| + permit(action, keys: keys) + end + end + + # Sanitize the parameters for a specific +action+. + # + # === Arguments + # + # * +action+ - A +Symbol+ with the action that the controller is + # performing, like +sign_up+, +sign_in+, etc. + # + # === Examples + # + # # Inside the `RegistrationsController#create` action. + # resource = build_resource(devise_parameter_sanitizer.sanitize(:sign_up)) + # resource.save + # + # Returns an +ActiveSupport::HashWithIndifferentAccess+ with the permitted + # attributes. + def sanitize(action) + permissions = @permitted[action] + + if permissions.respond_to?(:call) + cast_to_hash permissions.call(default_params) + elsif permissions.present? + cast_to_hash permit_keys(default_params, permissions) + else + unknown_action!(action) + end + end + + # Add or remove new parameters to the permitted list of an +action+. + # + # === Arguments + # + # * +action+ - A +Symbol+ with the action that the controller is + # performing, like +sign_up+, +sign_in+, etc. + # * +keys:+ - An +Array+ of keys that also should be permitted. + # * +except:+ - An +Array+ of keys that shouldn't be permitted. + # * +block+ - A block that should be used to permit the action + # parameters instead of the +Array+ based approach. The block will be + # called with an +ActionController::Parameters+ instance. + # + # === Examples + # + # # Adding new parameters to be permitted in the `sign_up` action. + # devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) + # + # # Removing the `password` parameter from the `account_update` action. + # devise_parameter_sanitizer.permit(:account_update, except: [:password]) + # + # # Using the block form to completely override how we permit the + # # parameters for the `sign_up` action. + # devise_parameter_sanitizer.permit(:sign_up) do |user| + # user.permit(:email, :password, :password_confirmation) + # end + # + # + # Returns nothing. + def permit(action, keys: nil, except: nil, &block) + if block_given? + @permitted[action] = block + end + + if keys.present? + @permitted[action] ||= @auth_keys.dup + @permitted[action].concat(keys) + end + + if except.present? + @permitted[action] ||= @auth_keys.dup + @permitted[action] = @permitted[action] - except + end + end + + private + + # Cast a sanitized +ActionController::Parameters+ to a +HashWithIndifferentAccess+ + # that can be used elsewhere. + # + # Returns an +ActiveSupport::HashWithIndifferentAccess+. + def cast_to_hash(params) + params && params.to_h + end + + def default_params + 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) + parameters.permit(*keys) + end + + def extract_auth_keys(klass) + auth_keys = klass.authentication_keys + + auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys + end + + def unknown_action!(action) + raise NotImplementedError, <<-MESSAGE.strip_heredoc + "Devise doesn't know how to sanitize parameters for '#{action}'". + If you want to define a new set of parameters to be sanitized use the + `permit` method first: + + devise_parameter_sanitizer.permit(:#{action}, keys: [:param1, :param2, :param3]) + MESSAGE + end + end +end diff --git a/lib/devise/rails.rb b/lib/devise/rails.rb index 24a5f9241e..b5738853fe 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' @@ -11,13 +13,19 @@ class Engine < ::Rails::Engine end # Force routes to be loaded if we are doing any eager load. - config.before_eager_load { |app| app.reload_routes! } + config.before_eager_load do |app| + 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 - initializer "devise.omniauth" do |app| + initializer "devise.omniauth", after: :load_config_initializers, before: :build_middleware_stack do |app| Devise.omniauth_configs.each do |provider, config| app.middleware.use config.strategy_class, *config.args do |strategy| config.strategy = strategy @@ -29,25 +37,20 @@ class Engine < ::Rails::Engine end end - initializer "devise.mongoid_version_warning" do - if defined?(Mongoid) - require 'mongoid/version' - if Mongoid::VERSION.to_f < 2.1 - puts "\n[DEVISE] Please note that Mongoid versions prior to 2.1 handle dirty model " \ - "object attributes in such a way that the Devise `validatable` module will not apply " \ - "its usual uniqueness and format validations for the email field. It is recommended " \ - "that you upgrade to Mongoid 2.1+ for this and other fixes, but if for some reason you " \ - "are unable to do so, you should add these validations manually.\n" + initializer "devise.secret_key" do |app| + Devise.secret_key ||= app.secret_key_base + + Devise.token_generator ||= + if secret_key = Devise.secret_key + Devise::TokenGenerator.new( + ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key)) + ) end - end end - initializer "devise.fix_routes_proxy_missing_respond_to_bug" do - # We can get rid of this once we support only Rails > 3.2 - ActionDispatch::Routing::RoutesProxy.class_eval do - def respond_to?(method, include_private = false) - super || routes.url_helpers.respond_to?(method) - 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 diff --git a/lib/devise/rails/routes.rb b/lib/devise/rails/routes.rb index 440a2a8d80..f43e62fea7 100644 --- a/lib/devise/rails/routes.rb +++ b/lib/devise/rails/routes.rb @@ -1,13 +1,12 @@ +# frozen_string_literal: true + require "active_support/core_ext/object/try" require "active_support/core_ext/hash/slice" -module ActionDispatch::Routing - class RouteSet #:nodoc: - # Ensure Devise modules are included only after loading routes, because we - # need devise_for mappings already declared to create filters and helpers. - def finalize_with_devise! - result = finalize_without_devise! - +module Devise + module RouteSet + def finalize! + result = super @devise_finalized ||= begin if Devise.router_name.nil? && defined?(@devise_finalized) && self != Rails.application.try(:routes) warn "[DEVISE] We have detected that you are using devise_for inside engine routes. " \ @@ -21,10 +20,16 @@ def finalize_with_devise! Devise.regenerate_helpers! true end - result end - alias_method_chain :finalize!, :devise + end +end + +module ActionDispatch::Routing + class RouteSet #:nodoc: + # Ensure Devise modules are included only after loading routes, because we + # need devise_for mappings already declared to create filters and helpers. + prepend Devise::RouteSet end class Mapper @@ -43,103 +48,132 @@ class Mapper # needed routes: # # # Session routes for Authenticatable (default) - # new_user_session GET /users/sign_in {:controller=>"devise/sessions", :action=>"new"} - # user_session POST /users/sign_in {:controller=>"devise/sessions", :action=>"create"} - # destroy_user_session DELETE /users/sign_out {:controller=>"devise/sessions", :action=>"destroy"} + # new_user_session GET /users/sign_in {controller:"devise/sessions", action:"new"} + # user_session POST /users/sign_in {controller:"devise/sessions", action:"create"} + # destroy_user_session DELETE /users/sign_out {controller:"devise/sessions", action:"destroy"} # # # Password routes for Recoverable, if User model has :recoverable configured - # new_user_password GET /users/password/new(.:format) {:controller=>"devise/passwords", :action=>"new"} - # edit_user_password GET /users/password/edit(.:format) {:controller=>"devise/passwords", :action=>"edit"} - # user_password PUT /users/password(.:format) {:controller=>"devise/passwords", :action=>"update"} - # POST /users/password(.:format) {:controller=>"devise/passwords", :action=>"create"} + # new_user_password GET /users/password/new(.:format) {controller:"devise/passwords", action:"new"} + # edit_user_password GET /users/password/edit(.:format) {controller:"devise/passwords", action:"edit"} + # user_password PUT /users/password(.:format) {controller:"devise/passwords", action:"update"} + # POST /users/password(.:format) {controller:"devise/passwords", action:"create"} # # # Confirmation routes for Confirmable, if User model has :confirmable configured - # new_user_confirmation GET /users/confirmation/new(.:format) {:controller=>"devise/confirmations", :action=>"new"} - # user_confirmation GET /users/confirmation(.:format) {:controller=>"devise/confirmations", :action=>"show"} - # POST /users/confirmation(.:format) {:controller=>"devise/confirmations", :action=>"create"} + # new_user_confirmation GET /users/confirmation/new(.:format) {controller:"devise/confirmations", action:"new"} + # user_confirmation GET /users/confirmation(.:format) {controller:"devise/confirmations", action:"show"} + # POST /users/confirmation(.:format) {controller:"devise/confirmations", action:"create"} + # + # ==== Routes integration + # + # +devise_for+ is meant to play nicely with other routes methods. For example, + # by calling +devise_for+ inside a namespace, it automatically nests your devise + # controllers: + # + # namespace :publisher do + # devise_for :account + # end + # + # The snippet above will use publisher/sessions controller instead of devise/sessions + # controller. You can revert this change or configure it directly by passing the :module + # option described below to +devise_for+. + # + # Also note that when you use a namespace it will affect all the helpers and methods + # for controllers and views. For example, using the above setup you'll end with + # following methods: current_publisher_account, authenticate_publisher_account!, + # publisher_account_signed_in, etc. + # + # The only aspect not affect by the router configuration is the model name. The + # model name can be explicitly set via the :class_name option. # # ==== Options # # You can configure your routes with some options: # - # * :class_name => setup a different class to be looked up by devise, if it cannot be + # * class_name: set up a different class to be looked up by devise, if it cannot be # properly found by the route name. # - # devise_for :users, :class_name => 'Account' + # devise_for :users, class_name: 'Account' # - # * :path => allows you to setup path name that will be used, as rails routes does. - # The following route configuration would setup your route as /accounts instead of /users: + # * path: allows you to set up path name that will be used, as rails routes does. + # The following route configuration would set up your route as /accounts instead of /users: # - # devise_for :users, :path => 'accounts' + # devise_for :users, path: 'accounts' + # + # * singular: set up the singular name for the given resource. This is used as the helper methods + # names in controller ("authenticate_#{singular}!", "#{singular}_signed_in?", "current_#{singular}" + # and "#{singular}_session"), as the scope name in routes and as the scope given to warden. + # + # devise_for :admins, singular: :manager + # + # devise_scope :manager do + # ... + # end # - # * :singular => setup the singular name for the given resource. This is used as the instance variable - # name in controller, as the name in routes and the scope given to warden. + # class ManagerController < ApplicationController + # before_action authenticate_manager! # - # devise_for :users, :singular => :user + # def show + # @manager = current_manager + # ... + # end + # end # - # * :path_names => configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up, + # * path_names: configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up, # :password, :confirmation, :unlock. # - # devise_for :users, :path_names => { :sign_in => 'login', :sign_out => 'logout', :password => 'secret', :confirmation => 'verification' } + # devise_for :users, path_names: { + # sign_in: 'login', sign_out: 'logout', + # password: 'secret', confirmation: 'verification', + # registration: 'register', edit: 'edit/profile' + # } # - # * :controllers => the controller which should be used. All routes by default points to Devise controllers. + # * controllers: the controller which should be used. All routes by default points to Devise controllers. # However, if you want them to point to custom controller, you should do: # - # devise_for :users, :controllers => { :sessions => "users/sessions" } + # devise_for :users, controllers: { sessions: "users/sessions" } # - # * :failure_app => a rack app which is invoked whenever there is a failure. Strings representing a given + # * 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. # - # * :module => the namespace to find controllers (default: "devise", thus + # * module: the namespace to find controllers (default: "devise", thus # accessing devise/sessions, devise/registrations, and so on). If you want # to namespace all at once, use module: # - # devise_for :users, :module => "users" - # - # Notice that whenever you use namespace in the router DSL, it automatically sets the module. - # So the following setup: - # - # namespace :publisher do - # devise_for :account - # end - # - # Will use publisher/sessions controller instead of devise/sessions controller. You can revert - # this by providing the :module option to devise_for. - # - # Also pay attention that when you use a namespace it will affect all the helpers and methods for controllers - # and views. For example, using the above setup you'll end with following methods: - # current_publisher_account, authenticate_publisher_account!, publisher_account_signed_in, etc. + # devise_for :users, module: "users" # - # * :skip => tell which controller you want to skip routes from being created: + # * skip: tell which controller you want to skip routes from being created. + # It accepts :all as an option, meaning it will not generate any route at all: # - # devise_for :users, :skip => :sessions + # devise_for :users, skip: :sessions # - # * :only => the opposite of :skip, tell which controllers only to generate routes to: + # * only: the opposite of :skip, tell which controllers only to generate routes to: # - # devise_for :users, :only => :sessions + # devise_for :users, only: :sessions # - # * :skip_helpers => skip generating Devise url helpers like new_session_path(@user). + # * skip_helpers: skip generating Devise url helpers like new_session_path(@user). # This is useful to avoid conflicts with previous routes and is false by default. # It accepts true as option, meaning it will skip all the helpers for the controllers # given in :skip but it also accepts specific helpers to be skipped: # - # devise_for :users, :skip => [:registrations, :confirmations], :skip_helpers => true - # devise_for :users, :skip_helpers => [:registrations, :confirmations] + # devise_for :users, skip: [:registrations, :confirmations], skip_helpers: true + # devise_for :users, skip_helpers: [:registrations, :confirmations] # - # * :format => include "(.:format)" in the generated routes? true by default, set to false to disable: + # * format: include "(.:format)" in the generated routes? true by default, set to false to disable: # - # devise_for :users, :format => false + # devise_for :users, format: false # - # * :constraints => works the same as Rails' constraints + # * constraints: works the same as Rails' constraints # - # * :defaults => works the same as Rails' defaults + # * defaults: works the same as Rails' defaults + # + # * router_name: allows application level router name to be overwritten for the current scope # # ==== Scoping # @@ -161,7 +195,7 @@ class Mapper # # class ApplicationController < ActionController::Base # def self.default_url_options - # { :locale => I18n.locale } + # { locale: I18n.locale } # end # end # @@ -186,11 +220,12 @@ class Mapper # In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this: # # devise_scope :owner do - # post "deactivate", :to => "registrations#deactivate", :as => "deactivate_registration" + # post "deactivate", to: "registrations#deactivate", as: "deactivate_registration" # end # def devise_for(*resources) @devise_finalized = false + raise_no_secret_key unless Devise.secret_key options = resources.extract_options! options[:as] ||= @scope[:as] if @scope[:as].present? @@ -200,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) @@ -211,7 +245,7 @@ def devise_for(*resources) raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise) rescue NameError => e raise unless mapping.class_name == resource.to_s.classify - warn "[WARNING] You provided devise_for #{resource.inspect} but there is " << + warn "[WARNING] You provided devise_for #{resource.inspect} but there is " \ "no model #{mapping.class_name} defined in your application" next rescue NoMethodError => e @@ -219,17 +253,16 @@ def devise_for(*resources) raise_no_devise_method_error!(mapping.class_name) end - routes = mapping.used_routes - - devise_scope mapping.name do - if block_given? - ActiveSupport::Deprecation.warn "Passing a block to devise_for is deprecated. " \ - "Please remove the block from devise_for (only the block, the call to " \ - "devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " \ - "with the block instead", caller - yield + if options[:controllers] && options[:controllers][:omniauth_callbacks] + unless mapping.omniauthable? + raise ArgumentError, "Mapping omniauth_callbacks on a resource that is not omniauthable\n" \ + "Please add `devise :omniauthable` to the `#{mapping.class_name}` model" end + end + + routes = mapping.used_routes + devise_scope mapping.name do with_devise_exclusive_scope mapping.fullpath, mapping.name, options do routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) } end @@ -250,15 +283,11 @@ def devise_for(*resources) # end # # authenticate :user, lambda {|u| u.role == "admin"} do - # root :to => "admin/dashboard#show" + # root to: "admin/dashboard#show", as: :user_root # end # - def authenticate(scope=nil, block=nil) - constraint = lambda do |request| - request.env["warden"].authenticate!(:scope => scope) && (block.nil? || block.call(request.env["warden"].user(scope))) - end - - constraints(constraint) do + def authenticate(scope = nil, block = nil) + constraints_for(:authenticate!, scope, block) do yield end end @@ -268,25 +297,21 @@ def authenticate(scope=nil, block=nil) # a model and allows extra constraints to be done on the instance. # # authenticated :admin do - # root :to => 'admin/dashboard#show' + # root to: 'admin/dashboard#show', as: :admin_root # end # # authenticated do - # root :to => 'dashboard#show' + # root to: 'dashboard#show', as: :authenticated_root # end # # authenticated :user, lambda {|u| u.role == "admin"} do - # root :to => "admin/dashboard#show" + # root to: "admin/dashboard#show", as: :user_root # end # - # root :to => 'landing#show' + # root to: 'landing#show' # - def authenticated(scope=nil, block=nil) - constraint = lambda do |request| - request.env["warden"].authenticate?(:scope => scope) && (block.nil? || block.call(request.env["warden"].user(scope))) - end - - constraints(constraint) do + def authenticated(scope = nil, block = nil) + constraints_for(:authenticate?, scope, block) do yield end end @@ -296,15 +321,15 @@ def authenticated(scope=nil, block=nil) # # unauthenticated do # as :user do - # root :to => 'devise/registrations#new' + # root to: 'devise/registrations#new' # end # end # - # root :to => 'dashboard#show' + # root to: 'dashboard#show' # - def unauthenticated(scope=nil) + def unauthenticated(scope = nil) constraint = lambda do |request| - not request.env["warden"].authenticate? :scope => scope + not request.env["warden"].authenticate? scope: scope end constraints(constraint) do @@ -314,10 +339,10 @@ def unauthenticated(scope=nil) # Sets the devise scope to be used in the controller. If you have custom routes, # you are required to call this method (also aliased as :as) in order to specify - # to which controller it is targetted. + # to which controller it is targeted. # # as :user do - # get "sign_in", :to => "devise/sessions#new" + # get "sign_in", to: "devise/sessions#new" # end # # Notice you cannot have two scopes mapping to the same URL. And remember, if @@ -329,7 +354,7 @@ def unauthenticated(scope=nil) # good and working example. # # devise_scope :user do - # match "/some/route" => "some_devise_controller" + # get "/some/route" => "some_devise_controller" # end # devise_for :users # @@ -349,81 +374,114 @@ def devise_scope(scope) protected def devise_session(mapping, controllers) #:nodoc: - resource :session, :only => [], :controller => controllers[:sessions], :path => "" do - get :new, :path => mapping.path_names[:sign_in], :as => "new" - post :create, :path => mapping.path_names[:sign_in] - match :destroy, :path => mapping.path_names[:sign_out], :as => "destroy", :via => mapping.sign_out_via + resource :session, only: [], controller: controllers[:sessions], path: "" do + get :new, path: mapping.path_names[:sign_in], as: "new" + post :create, path: mapping.path_names[:sign_in] + match :destroy, path: mapping.path_names[:sign_out], as: "destroy", via: mapping.sign_out_via end end def devise_password(mapping, controllers) #:nodoc: - resource :password, :only => [:new, :create, :edit, :update], - :path => mapping.path_names[:password], :controller => controllers[:passwords] + resource :password, only: [:new, :create, :edit, :update], + path: mapping.path_names[:password], controller: controllers[:passwords] end def devise_confirmation(mapping, controllers) #:nodoc: - resource :confirmation, :only => [:new, :create, :show], - :path => mapping.path_names[:confirmation], :controller => controllers[:confirmations] + resource :confirmation, only: [:new, :create, :show], + path: mapping.path_names[:confirmation], controller: controllers[:confirmations] end def devise_unlock(mapping, controllers) #:nodoc: if mapping.to.unlock_strategy_enabled?(:email) - resource :unlock, :only => [:new, :create, :show], - :path => mapping.path_names[:unlock], :controller => controllers[:unlocks] + resource :unlock, only: [:new, :create, :show], + path: mapping.path_names[:unlock], controller: controllers[:unlocks] end end def devise_registration(mapping, controllers) #:nodoc: path_names = { - :new => mapping.path_names[:sign_up], - :cancel => mapping.path_names[:cancel] + new: mapping.path_names[:sign_up], + edit: mapping.path_names[:edit], + cancel: mapping.path_names[:cancel] } options = { - :only => [:new, :create, :edit, :update, :destroy], - :path => mapping.path_names[:registration], - :path_names => path_names, - :controller => controllers[:registrations] + only: [:new, :create, :edit, :update, :destroy], + path: mapping.path_names[:registration], + path_names: path_names, + controller: controllers[:registrations] } - resource :registration, options do + resource :registration, **options do get :cancel end end def devise_omniauth_callback(mapping, controllers) #:nodoc: - path, @scope[:path] = @scope[:path], nil - path_prefix = Devise.omniauth_path_prefix || "/#{mapping.path}/auth".squeeze("/") - set_omniauth_path_prefix!(path_prefix) + if mapping.fullpath =~ /:[a-zA-Z_]/ + raise <<-ERROR +Devise does not support scoping OmniAuth callbacks under a dynamic segment +and you have set #{mapping.fullpath.inspect}. You can work around by passing +`skip: :omniauth_callbacks` to the `devise_for` call and extract omniauth +options to another `devise_for` call outside the scope. Here is an example: - providers = Regexp.union(mapping.to.omniauth_providers.map(&:to_s)) + devise_for :users, only: :omniauth_callbacks, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'} - match "#{path_prefix}/:provider", - :constraints => { :provider => providers }, - :to => "#{controllers[:omniauth_callbacks]}#passthru", - :as => :omniauth_authorize + scope '/(:locale)', locale: /ru|en/ do + devise_for :users, skip: :omniauth_callbacks + end +ERROR + end + current_scope = @scope.dup + if @scope.respond_to? :new + @scope = @scope.new path: nil + else + @scope[:path] = nil + end + path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/") - match "#{path_prefix}/:action/callback", - :constraints => { :action => providers }, - :to => controllers[:omniauth_callbacks], - :as => :omniauth_callback + set_omniauth_path_prefix!(path_prefix) + + mapping.to.omniauth_providers.each do |provider| + match "#{path_prefix}/#{provider}", + to: "#{controllers[:omniauth_callbacks]}#passthru", + as: "#{provider}_omniauth_authorize", + via: OmniAuth.config.allowed_request_methods + + match "#{path_prefix}/#{provider}/callback", + to: "#{controllers[:omniauth_callbacks]}##{provider}", + as: "#{provider}_omniauth_callback", + via: [:get, :post] + end ensure - @scope[:path] = path + @scope = current_scope end - DEVISE_SCOPE_KEYS = [:as, :path, :module, :constraints, :defaults, :options] - def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc: - old = {} - DEVISE_SCOPE_KEYS.each { |k| old[k] = @scope[k] } + current_scope = @scope.dup - new = { :as => new_as, :path => new_path, :module => nil } - new.merge!(options.slice(:constraints, :defaults, :options)) + exclusive = { as: new_as, path: new_path, module: nil } + exclusive.merge!(options.slice(:constraints, :format, :defaults, :options)) - @scope.merge!(new) + if @scope.respond_to? :new + @scope = @scope.new exclusive + else + exclusive.each_pair { |key, value| @scope[key] = value } + end yield ensure - @scope.merge!(old) + @scope = current_scope + end + + 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))) + end + + constraints(constraint) do + yield + end end def set_omniauth_path_prefix!(path_prefix) #:nodoc: @@ -437,6 +495,16 @@ def set_omniauth_path_prefix!(path_prefix) #:nodoc: end end + def raise_no_secret_key #:nodoc: + raise <<-ERROR +Devise.secret_key was not set. Please add the following to your Devise initializer: + + config.secret_key = '#{SecureRandom.hex(64)}' + +Please ensure you restarted your application after installing Devise or setting the key. +ERROR + end + def raise_no_devise_method_error!(klass) #:nodoc: raise "#{klass} does not respond to 'devise' method. This usually means you haven't " \ "loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' " \ diff --git a/lib/devise/rails/warden_compat.rb b/lib/devise/rails/warden_compat.rb index d1861b3d58..3db7ecaeaf 100644 --- a/lib/devise/rails/warden_compat.rb +++ b/lib/devise/rails/warden_compat.rb @@ -1,9 +1,10 @@ +# frozen_string_literal: true + module Warden::Mixins::Common def request @request ||= ActionDispatch::Request.new(env) end - # This is called internally by Warden on logout def reset_session! request.reset_session end @@ -12,32 +13,3 @@ def cookies request.cookie_jar end end - -class Warden::SessionSerializer - def serialize(record) - klass = record.class - array = klass.serialize_into_session(record) - array.unshift(klass.name) - end - - def deserialize(keys) - klass_name, *args = keys - - begin - klass = ActiveSupport::Inflector.constantize(klass_name) - if klass.respond_to? :serialize_from_session - klass.serialize_from_session(*args) - else - Rails.logger.warn "[Devise] Stored serialized class #{klass_name} seems not to be Devise enabled anymore. Did you do that on purpose?" - nil - end - rescue NameError => e - if e.message =~ /uninitialized constant/ - Rails.logger.debug "[Devise] Trying to deserialize invalid class #{klass_name}" - nil - else - raise - end - end - end -end diff --git a/lib/devise/strategies/authenticatable.rb b/lib/devise/strategies/authenticatable.rb index e57ba9b3f8..2af7a741cf 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 @@ -16,32 +18,26 @@ def valid? valid_for_params_auth? || valid_for_http_auth? end + # Override and set to false for things like OmniAuth that technically + # run through Authentication (user_set) very often, which would normally + # reset CSRF data in the session + def clean_up_csrf? + true + end + 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 - # given as parameter. Check Devise::Models::Authenticable.valid_for_authentication? + # A block that will be triggered while validating can be optionally + # given as parameter. Check Devise::Models::Authenticatable.valid_for_authentication? # for more information. # # In case the resource can't be validated, it will fail with the given # unauthenticated_message. def validate(resource, &block) - unless resource - ActiveSupport::Deprecation.warn "an empty resource was given to #{self.class.name}#validate. " \ - "Please ensure the resource is not nil", caller - end - result = resource && resource.valid_for_authentication?(&block) - case result - when Symbol, String - ActiveSupport::Deprecation.warn "valid_for_authentication? should return a boolean value" - fail!(result) - return false - end - if result - decorate(resource) true else if resource @@ -52,7 +48,7 @@ def validate(resource, &block) end # Get values from params and set in the resource. - def decorate(resource) + def remember_me(resource) resource.remember_me = remember_me? if resource.respond_to?(:remember_me=) end @@ -61,9 +57,9 @@ def remember_me? valid_params? && Devise::TRUE_VALUES.include?(params_auth_hash[:remember_me]) end - # Check if this is strategy is valid for http authentication by: + # Check if this is a valid strategy for http authentication by: # - # * Validating if the model allows params authentication; + # * Validating if the model allows http authentication; # * If any of the authorization headers were sent; # * If all authentication keys are present; # @@ -71,7 +67,7 @@ def valid_for_http_auth? http_authenticatable? && request.authorization && with_authentication_hash(:http_auth, http_auth_hash) end - # Check if this is strategy is valid for params authentication by: + # Check if this is a valid strategy for params authentication by: # # * Validating if the model allows params authentication; # * If the request hits the sessions controller through POST; @@ -100,7 +96,7 @@ def params_auth_hash # Extract a hash with attributes:values from the http params. def http_auth_hash - keys = [authentication_keys.first, :password] + keys = [http_authentication_key, :password] Hash[*keys.zip(decode_credentials).flatten] end @@ -114,14 +110,17 @@ def valid_params? params_auth_hash.is_a?(Hash) end - # Check if password is present and is not equal to "X" (default value for token). + # Note: unlike `Model.valid_password?`, this method does not actually + # ensure that the password in the params matches the password stored in + # the database. It only checks if the password is *present*. Do not rely + # on this method for validating that a given password is correct. def valid_password? - password.present? && password != "X" + password.present? end # Helper to decode credentials from HTTP. def decode_credentials - return [] unless request.authorization && request.authorization =~ /^Basic (.*)/m + return [] unless request.authorization && request.authorization =~ /^Basic (.*)/mi Base64.decode64($1).split(/:/, 2) end @@ -134,24 +133,27 @@ def with_authentication_hash(auth_type, auth_values) parse_authentication_key_values(request_values, request_keys) end - # Holds the authentication keys. def authentication_keys @authentication_keys ||= mapping.to.authentication_keys end - # Holds request keys. + def http_authentication_key + @http_authentication_key ||= mapping.to.http_authentication_key || case authentication_keys + when Array then authentication_keys.first + when Hash then authentication_keys.keys.first + end + end + def request_keys @request_keys ||= mapping.to.request_keys end - # Returns values from the request object. def request_values keys = request_keys.respond_to?(:keys) ? request_keys.keys : request_keys values = keys.map { |k| self.request.send(k) } Hash[keys.zip(values)] end - # Parse authentication keys considering if they should be enforced or not. def parse_authentication_key_values(hash, keys) keys.each do |key, enforce| value = hash[key].presence diff --git a/lib/devise/strategies/base.rb b/lib/devise/strategies/base.rb index 6f18211335..998e6a367f 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. @@ -17,4 +19,4 @@ def mapping end end end -end \ No newline at end of file +end diff --git a/lib/devise/strategies/database_authenticatable.rb b/lib/devise/strategies/database_authenticatable.rb index 4552d7a396..f7e007d144 100644 --- a/lib/devise/strategies/database_authenticatable.rb +++ b/lib/devise/strategies/database_authenticatable.rb @@ -1,17 +1,28 @@ +# frozen_string_literal: true + require 'devise/strategies/authenticatable' module Devise module Strategies - # Default strategy for signing in a user, based on his email and password in the database. + # Default strategy for signing in a user, based on their email and password in the database. class DatabaseAuthenticatable < Authenticatable def authenticate! - resource = valid_password? && mapping.to.find_for_database_authentication(authentication_hash) - return fail(:invalid) unless resource + resource = password.present? && mapping.to.find_for_database_authentication(authentication_hash) + hashed = false - if validate(resource){ resource.valid_password?(password) } + if validate(resource){ hashed = true; resource.valid_password?(password) } + remember_me(resource) resource.after_database_authentication 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 + 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 68b91b1c48..fe20804f68 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 @@ -25,15 +27,25 @@ def authenticate! end if validate(resource) + remember_me(resource) if extend_remember_me?(resource) + resource.after_remembered success!(resource) end end + # No need to clean up the CSRF when using rememberable. + # In fact, cleaning it up here would be a bug because + # rememberable is triggered on GET requests which means + # we would render a page on first access with all csrf + # tokens expired. + def clean_up_csrf? + false + end + private - def decorate(resource) - super - resource.extend_remember_period = mapping.to.extend_remember_period if resource.respond_to?(:extend_remember_period=) + def extend_remember_me?(resource) + resource.respond_to?(:extend_remember_period) && resource.extend_remember_period end def remember_me? @@ -41,7 +53,7 @@ def remember_me? end def remember_key - "remember_#{scope}_token" + mapping.to.rememberable_options.fetch(:key, "remember_#{scope}_token") end def remember_cookie @@ -52,4 +64,4 @@ def remember_cookie end end -Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable) \ No newline at end of file +Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable) diff --git a/lib/devise/strategies/token_authenticatable.rb b/lib/devise/strategies/token_authenticatable.rb deleted file mode 100644 index 6a9df2232c..0000000000 --- a/lib/devise/strategies/token_authenticatable.rb +++ /dev/null @@ -1,56 +0,0 @@ -require 'devise/strategies/base' - -module Devise - module Strategies - # Strategy for signing in a user, based on a authenticatable token. This works for both params - # and http. For the former, all you need to do is to pass the params in the URL: - # - # http://myapp.example.com/?user_token=SECRET - # - # For HTTP, you can pass the token as username and blank password. Since some clients may require - # a password, you can pass "X" as password and it will simply be ignored. - class TokenAuthenticatable < Authenticatable - def store? - super && !mapping.to.skip_session_storage.include?(:token_auth) - end - - def authenticate! - resource = mapping.to.find_for_token_authentication(authentication_hash) - return fail(:invalid_token) unless resource - - if validate(resource) - resource.after_token_authentication - success!(resource) - end - end - - private - - # Token Authenticatable can be authenticated with params in any controller and any verb. - def valid_params_request? - true - end - - # Do not use remember_me behavior with token. - def remember_me? - false - end - - # Try both scoped and non scoped keys. - def params_auth_hash - if params[scope].kind_of?(Hash) && params[scope].has_key?(authentication_keys.first) - params[scope] - else - params - end - end - - # Overwrite authentication keys to use token_authentication_key. - def authentication_keys - @authentication_keys ||= [mapping.to.token_authentication_key] - end - end - end -end - -Warden::Strategies.add(:token_authenticatable, Devise::Strategies::TokenAuthenticatable) diff --git a/lib/devise/test/controller_helpers.rb b/lib/devise/test/controller_helpers.rb new file mode 100644 index 0000000000..d3522a3466 --- /dev/null +++ b/lib/devise/test/controller_helpers.rb @@ -0,0 +1,156 @@ +# frozen_string_literal: true + +module Devise + module Test + # `Devise::Test::ControllerHelpers` provides a facility to test controllers + # in isolation when using `ActionController::TestCase` allowing you to + # quickly sign_in or sign_out a user. Do not use + # `Devise::Test::ControllerHelpers` in integration tests. + # + # Examples + # + # class PostsTest < ActionController::TestCase + # include Devise::Test::ControllerHelpers + # + # test 'authenticated users can GET index' do + # sign_in users(:bob) + # + # get :index + # assert_response :success + # end + # end + # + # Important: you should not test Warden specific behavior (like callbacks) + # using `Devise::Test::ControllerHelpers` since it is a stub of the actual + # behavior. Such callbacks should be tested in your integration suite instead. + module ControllerHelpers + extend ActiveSupport::Concern + + included do + setup :setup_controller_for_warden, :warden + end + + # Override process to consider warden. + def process(*) + _catch_warden { super } + + @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 + end + + # Quick access to Warden::Proxy. + def warden #:nodoc: + @request.env['warden'] ||= begin + manager = Warden::Manager.new(nil) do |config| + config.merge! Devise.warden_config + end + Warden::Proxy.new(@request.env, manager) + end + end + + # sign_in a given resource by storing its keys in the session. + # This method bypass any warden authentication callback. + # + # * +resource+ - The resource that should be authenticated + # * +scope+ - An optional +Symbol+ with the scope where the resource + # should be signed in with. + # Examples: + # + # sign_in users(:alice) + # sign_in users(:alice), scope: :admin + def sign_in(resource, scope: nil) + scope ||= Devise::Mapping.find_scope!(resource) + + warden.instance_variable_get(:@users).delete(scope) + warden.session_serializer.store(resource, scope) + end + + # Sign out a given resource or scope by calling logout on Warden. + # This method bypass any warden logout callback. + # + # Examples: + # + # sign_out :user # sign_out(scope) + # sign_out @user # sign_out(resource) + # + def sign_out(resource_or_scope) + scope = Devise::Mapping.find_scope!(resource_or_scope) + @controller.instance_variable_set(:"@current_#{scope}", nil) + user = warden.instance_variable_get(:@users).delete(scope) + warden.session_serializer.delete(scope, user) + end + + protected + + # Catch warden continuations and handle like the middleware would. + # Returns nil when interrupted, otherwise the normal result of the block. + def _catch_warden(&block) + result = catch(:warden, &block) + + env = @controller.request.env + + result ||= {} + + # Set the response. In production, the rack result is returned + # from Warden::Manager#call, which the following is modelled on. + case result + when Array + if result.first == 401 && intercept_401?(env) # does this happen during testing? + _process_unauthenticated(env) + else + result + end + when Hash + _process_unauthenticated(env, result) + else + result + end + end + + def _process_unauthenticated(env, options = {}) + options[:action] ||= :unauthenticated + proxy = request.env['warden'] + result = options[:result] || proxy.result + + ret = case result + when :redirect + body = proxy.message || "You are being redirected to #{proxy.headers['Location']}" + [proxy.status, proxy.headers, [body]] + when :custom + proxy.custom_response + else + request.env["PATH_INFO"] = "/#{options[:action]}" + request.env["warden.options"] = options + Warden::Manager._run_callbacks(:before_failure, 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 + nil # causes process return @response + end + + # ensure that the controller response is set up. In production, this is + # not necessary since warden returns the results to rack. However, at + # testing time, we want the response to be available to the testing + # framework to verify what would be returned to rack. + if ret.is_a?(Array) + status, headers, body = *ret + # ensure the controller response is set to our response. + @controller.response ||= @response + @response.status = status + @response.headers.merge!(headers) + @response.body = body + end + + ret + end + end + end +end diff --git a/lib/devise/test/integration_helpers.rb b/lib/devise/test/integration_helpers.rb new file mode 100644 index 0000000000..0c7c910a71 --- /dev/null +++ b/lib/devise/test/integration_helpers.rb @@ -0,0 +1,63 @@ +# 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 + # signin in or signin out a record. + # + # Examples + # + # class PostsTest < ActionDispatch::IntegrationTest + # include Devise::Test::IntegrationHelpers + # + # test 'authenticated users can see posts' do + # sign_in users(:bob) + # + # get '/posts' + # assert_response :success + # end + # end + module Test + module IntegrationHelpers + def self.included(base) + base.class_eval do + include Warden::Test::Helpers + + setup :setup_integration_for_devise + teardown :teardown_integration_for_devise + end + end + + # Signs in a specific resource, mimicking a successful sign in + # operation through +Devise::SessionsController#create+. + # + # * +resource+ - The resource that should be authenticated + # * +scope+ - An optional +Symbol+ with the scope where the resource + # should be signed in with. + def sign_in(resource, scope: nil) + scope ||= Devise::Mapping.find_scope!(resource) + + login_as(resource, scope: scope) + end + + # Signs out a specific scope from the session. + # + # * +resource_or_scope+ - The resource or scope that should be signed out. + def sign_out(resource_or_scope) + scope = Devise::Mapping.find_scope!(resource_or_scope) + + logout scope + end + + protected + + def setup_integration_for_devise + Warden.test_mode! + end + + def teardown_integration_for_devise + Warden.test_reset! + end + end + end +end diff --git a/lib/devise/test_helpers.rb b/lib/devise/test_helpers.rb deleted file mode 100644 index 9aa7c2397c..0000000000 --- a/lib/devise/test_helpers.rb +++ /dev/null @@ -1,131 +0,0 @@ -module Devise - # Devise::TestHelpers provides a facility to test controllers in isolation - # when using ActionController::TestCase allowing you to quickly sign_in or - # sign_out a user. Do not use Devise::TestHelpers in integration tests. - # - # Notice you should not test Warden specific behavior (like Warden callbacks) - # using Devise::TestHelpers since it is a stub of the actual behavior. Such - # callbacks should be tested in your integration suite instead. - module TestHelpers - def self.included(base) - base.class_eval do - setup :setup_controller_for_warden, :warden if respond_to?(:setup) - end - end - - # Override process to consider warden. - def process(*) - # Make sure we always return @response, a la ActionController::TestCase::Behaviour#process, even if warden interrupts - _catch_warden { super } || @response - end - - # We need to setup the environment variables and the response in the controller. - def setup_controller_for_warden #:nodoc: - @request.env['action_controller.instance'] = @controller - end - - # Quick access to Warden::Proxy. - def warden #:nodoc: - @warden ||= begin - manager = Warden::Manager.new(nil) do |config| - config.merge! Devise.warden_config - end - @request.env['warden'] = Warden::Proxy.new(@request.env, manager) - end - end - - # sign_in a given resource by storing its keys in the session. - # This method bypass any warden authentication callback. - # - # Examples: - # - # sign_in :user, @user # sign_in(scope, resource) - # sign_in @user # sign_in(resource) - # - def sign_in(resource_or_scope, resource=nil) - scope ||= Devise::Mapping.find_scope!(resource_or_scope) - resource ||= resource_or_scope - warden.instance_variable_get(:@users).delete(scope) - warden.session_serializer.store(resource, scope) - end - - # Sign out a given resource or scope by calling logout on Warden. - # This method bypass any warden logout callback. - # - # Examples: - # - # sign_out :user # sign_out(scope) - # sign_out @user # sign_out(resource) - # - def sign_out(resource_or_scope) - scope = Devise::Mapping.find_scope!(resource_or_scope) - @controller.instance_variable_set(:"@current_#{scope}", nil) - user = warden.instance_variable_get(:@users).delete(scope) - warden.session_serializer.delete(scope, user) - end - - protected - - # Catch warden continuations and handle like the middleware would. - # Returns nil when interrupted, otherwise the normal result of the block. - def _catch_warden(&block) - result = catch(:warden, &block) - - env = @controller.request.env - - result ||= {} - - # Set the response. In production, the rack result is returned - # from Warden::Manager#call, which the following is modelled on. - case result - when Array - if result.first == 401 && intercept_401?(env) # does this happen during testing? - _process_unauthenticated(env) - else - result - end - when Hash - _process_unauthenticated(env, result) - else - result - end - end - - def _process_unauthenticated(env, options = {}) - options[:action] ||= :unauthenticated - proxy = env['warden'] - result = options[:result] || proxy.result - - ret = case result - when :redirect - body = proxy.message || "You are being redirected to #{proxy.headers['Location']}" - [proxy.status, proxy.headers, [body]] - when :custom - proxy.custom_response - else - env["PATH_INFO"] = "/#{options[:action]}" - env["warden.options"] = options - Warden::Manager._run_callbacks(:before_failure, env, options) - - status, headers, body = Devise.warden_config[:failure_app].call(env).to_a - @controller.send :render, :status => status, :text => body, - :content_type => headers["Content-Type"], :location => headers["Location"] - nil # causes process return @response - end - - # ensure that the controller response is set up. In production, this is - # not necessary since warden returns the results to rack. However, at - # testing time, we want the response to be available to the testing - # framework to verify what would be returned to rack. - if ret.is_a?(Array) - # ensure the controller response is set to our response. - @controller.response ||= @response - @response.status = ret.first - @response.headers = ret.second - @response.body = ret.third - end - - ret - end - end -end diff --git a/lib/devise/time_inflector.rb b/lib/devise/time_inflector.rb index 5d09ce80f6..db3f655803 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 @@ -6,9 +8,9 @@ class TimeInflector class << self attr_reader :instance - delegate :time_ago_in_words, :to => :instance + delegate :time_ago_in_words, to: :instance end @instance = new end -end \ No newline at end of file +end diff --git a/lib/devise/token_generator.rb b/lib/devise/token_generator.rb new file mode 100644 index 0000000000..9eb74a046a --- /dev/null +++ b/lib/devise/token_generator.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require 'openssl' + +module Devise + class TokenGenerator + def initialize(key_generator, digest = "SHA256") + @key_generator = key_generator + @digest = digest + end + + def digest(klass, column, value) + value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s) + end + + def generate(klass, column) + key = key_for(column) + + loop do + raw = Devise.friendly_token + enc = OpenSSL::HMAC.hexdigest(@digest, key, raw) + break [raw, enc] unless klass.to_adapter.find_first({ column => enc }) + end + end + + private + + def key_for(column) + @key_generator.generate_key("Devise #{column}") + end + end +end diff --git a/lib/devise/version.rb b/lib/devise/version.rb index e5d6e9f62e..d1c8e77f5d 100644 --- a/lib/devise/version.rb +++ b/lib/devise/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Devise - VERSION = "2.1.2".freeze + VERSION = "5.0.0".freeze end diff --git a/lib/generators/active_record/devise_generator.rb b/lib/generators/active_record/devise_generator.rb index ba55d7ec02..89b2f94ddb 100644 --- a/lib/generators/active_record/devise_generator.rb +++ b/lib/generators/active_record/devise_generator.rb @@ -1,33 +1,38 @@ +# frozen_string_literal: true + require 'rails/generators/active_record' require 'generators/devise/orm_helpers' module ActiveRecord module Generators - class DeviseGenerator < ActiveRecord::Generators::Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + 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}" + 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}" + migration_template "migration.rb", "#{migration_path}/devise_create_#{table_name}.rb", migration_version: migration_version end end def generate_model - invoke "active_record:model", [name], :migration => false unless model_exists? && behavior == :invoke + invoke "active_record:model", [name], migration: false unless model_exists? && behavior == :invoke end def inject_devise_content - content = model_contents + < false, :default => "" - t.string :encrypted_password, :null => false, :default => "" + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token @@ -49,11 +54,11 @@ def migration_data t.datetime :remember_created_at ## Trackable - t.integer :sign_in_count, :default => 0 - t.datetime :current_sign_in_at - t.datetime :last_sign_in_at - t.string :current_sign_in_ip - t.string :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 @@ -62,14 +67,53 @@ def migration_data # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable - # t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at - - ## Token authenticatable - # t.string :authentication_token RUBY end + + def ip_column + # Padded with spaces so it aligns nicely with the rest of the columns. + "%-8s" % (inet? ? "inet" : "string") + end + + def inet? + postgresql? + end + + def rails61_and_up? + Rails::VERSION::MAJOR > 6 || (Rails::VERSION::MAJOR == 6 && Rails::VERSION::MINOR >= 1) + end + + def 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 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 end diff --git a/lib/generators/active_record/templates/migration.rb b/lib/generators/active_record/templates/migration.rb index e2cef1a945..ad85124972 100644 --- a/lib/generators/active_record/templates/migration.rb +++ b/lib/generators/active_record/templates/migration.rb @@ -1,19 +1,20 @@ -class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration +# 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| -%> t.<%= attribute.type %> :<%= attribute.name %> <% end -%> - t.timestamps + t.timestamps null: false end - add_index :<%= table_name %>, :email, :unique => true - add_index :<%= table_name %>, :reset_password_token, :unique => true - # add_index :<%= table_name %>, :confirmation_token, :unique => true - # add_index :<%= table_name %>, :unlock_token, :unique => true - # add_index :<%= table_name %>, :authentication_token, :unique => true + add_index :<%= table_name %>, :email, unique: true + add_index :<%= table_name %>, :reset_password_token, unique: true + # add_index :<%= table_name %>, :confirmation_token, unique: true + # add_index :<%= table_name %>, :unlock_token, unique: true end end diff --git a/lib/generators/active_record/templates/migration_existing.rb b/lib/generators/active_record/templates/migration_existing.rb index 1eda9aeae7..a44e5413e7 100644 --- a/lib/generators/active_record/templates/migration_existing.rb +++ b/lib/generators/active_record/templates/migration_existing.rb @@ -1,6 +1,8 @@ -class AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration +# frozen_string_literal: true + +class AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> def self.up - change_table(:<%= table_name %>) do |t| + change_table :<%= table_name %> do |t| <%= migration_data -%> <% attributes.each do |attribute| -%> @@ -8,14 +10,13 @@ def self.up <% end -%> # Uncomment below if timestamps were not included in your original model. - # t.timestamps + # t.timestamps null: false end - add_index :<%= table_name %>, :email, :unique => true - add_index :<%= table_name %>, :reset_password_token, :unique => true - # add_index :<%= table_name %>, :confirmation_token, :unique => true - # add_index :<%= table_name %>, :unlock_token, :unique => true - # add_index :<%= table_name %>, :authentication_token, :unique => true + add_index :<%= table_name %>, :email, unique: true + add_index :<%= table_name %>, :reset_password_token, unique: true + # add_index :<%= table_name %>, :confirmation_token, unique: true + # add_index :<%= table_name %>, :unlock_token, unique: true end def self.down diff --git a/lib/generators/devise/controllers_generator.rb b/lib/generators/devise/controllers_generator.rb new file mode 100644 index 0000000000..d96d3d33ee --- /dev/null +++ b/lib/generators/devise/controllers_generator.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require 'rails/generators/base' + +module Devise + module Generators + class ControllersGenerator < Rails::Generators::Base + CONTROLLERS = %w(confirmations passwords registrations sessions unlocks omniauth_callbacks).freeze + + desc <<-DESC.strip_heredoc + Create inherited Devise controllers in your app/controllers folder. + + Use -c to specify which controller you want to overwrite. + 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::SessionsController < Devise::SessionsController + content... + end + DESC + + source_root File.expand_path("../../templates/controllers", __FILE__) + argument :scope, required: true, + desc: "The scope to create controllers in, e.g. users, admins" + class_option :controllers, aliases: "-c", type: :array, + desc: "Select specific controllers to generate (#{CONTROLLERS.join(', ')})" + + def create_controllers + @scope_prefix = scope.blank? ? '' : (scope.camelize + '::') + controllers = options[:controllers] || CONTROLLERS + controllers.each do |name| + template "#{name}_controller.rb", + "app/controllers/#{scope}/#{name}_controller.rb" + end + end + + def show_readme + readme "README" if behavior == :invoke + end + end + end +end diff --git a/lib/generators/devise/devise_generator.rb b/lib/generators/devise/devise_generator.rb index ad459ced14..560d0da773 100644 --- a/lib/generators/devise/devise_generator.rb +++ b/lib/generators/devise/devise_generator.rb @@ -1,3 +1,7 @@ +# frozen_string_literal: true + +require 'rails/generators/named_base' + module Devise module Generators class DeviseGenerator < Rails::Generators::NamedBase @@ -6,17 +10,17 @@ 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 + class_option :routes, desc: "Generate routes", type: :boolean, default: true def add_devise_routes - devise_route = "devise_for :#{plural_name}" - devise_route << %Q(, :class_name => "#{class_name}") if class_name.include?("::") - devise_route << %Q(, :skip => :all) unless options.routes? + 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 end end diff --git a/lib/generators/devise/install_generator.rb b/lib/generators/devise/install_generator.rb index dd432f1398..78f3303d6e 100644 --- a/lib/generators/devise/install_generator.rb +++ b/lib/generators/devise/install_generator.rb @@ -1,14 +1,32 @@ +# frozen_string_literal: true + +require 'rails/generators/base' require 'securerandom' module Devise module Generators + MissingORMError = Class.new(Thor::Error) + 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] + raise MissingORMError, <<-ERROR.strip_heredoc + An ORM must be set to install Devise in your application. + + Be sure to have an ORM like Active Record or Mongoid loaded in your + app or configure your own at `config/application.rb`. + + config.generators do |g| + g.orm :your_orm_gem + end + ERROR + end + template "devise.rb", "config/initializers/devise.rb" end diff --git a/lib/generators/devise/orm_helpers.rb b/lib/generators/devise/orm_helpers.rb index 97c23887f5..067eb36f5b 100644 --- a/lib/generators/devise/orm_helpers.rb +++ b/lib/generators/devise/orm_helpers.rb @@ -1,27 +1,35 @@ +# frozen_string_literal: true + module Devise module Generators module OrmHelpers def model_contents -<<-CONTENT + buffer = <<-CONTENT # Include default devise modules. Others available are: - # :token_authenticatable, :confirmable, - # :lockable, :timeoutable and :omniauthable + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, - :recoverable, :rememberable, :trackable, :validatable + :recoverable, :rememberable, :validatable CONTENT + buffer end + private + def model_exists? - File.exists?(File.join(destination_root, model_path)) + File.exist?(File.join(destination_root, model_path)) end - + def migration_exists?(table_name) Dir.glob("#{File.join(destination_root, migration_path)}/[0-9]*_*.rb").grep(/\d+_add_devise_to_#{table_name}.rb$/).first end - + def migration_path - @migration_path ||= File.join("db", "migrate") + if Rails.version >= '5.0.3' + db_migrate_path + else + @migration_path ||= File.join("db", "migrate") + end end def model_path @@ -29,4 +37,4 @@ def model_path end end end -end \ No newline at end of file +end diff --git a/lib/generators/devise/views_generator.rb b/lib/generators/devise/views_generator.rb index cf52b14aa0..bc271743cf 100644 --- a/lib/generators/devise/views_generator.rb +++ b/lib/generators/devise/views_generator.rb @@ -1,3 +1,7 @@ +# frozen_string_literal: true + +require 'rails/generators/base' + module Devise module Generators # Include this module in your generator to generate Devise views. @@ -7,40 +11,50 @@ module ViewPathTemplates #:nodoc: extend ActiveSupport::Concern included do - argument :scope, :required => false, :default => nil, - :desc => "The scope to copy views to" + argument :scope, required: false, default: nil, + desc: "The scope to copy views to" # Le sigh, ensure Thor won't handle opts as args # It should be fixed in future Rails releases - class_option :form_builder, :aliases => "-b" + class_option :form_builder, aliases: "-b" class_option :markerb + class_option :views, aliases: "-v", type: :array, desc: "Select specific view directories to generate (confirmations, passwords, registrations, sessions, unlocks, mailer)" public_task :copy_views end - # TODO: Add this to Rails itslef - module ClassMethods - def hide! - Rails::Generators.hide_namespace self.namespace - end - end - def copy_views - view_directory :confirmations - view_directory :passwords - view_directory :registrations - view_directory :sessions - view_directory :unlocks + if options[:views] + options[:views].each do |directory| + view_directory directory.to_sym + end + else + view_directory :confirmations + view_directory :passwords + view_directory :registrations + view_directory :sessions + view_directory :unlocks + end end protected def view_directory(name, _target_path = nil) - directory name.to_s, _target_path || "#{target_path}/#{name}" + directory name.to_s, _target_path || "#{target_path}/#{name}" do |content| + if scope + content.gsub("devise/shared", "#{plural_scope}/shared") + else + content + end + end end def target_path - @target_path ||= "app/views/#{scope || :devise}" + @target_path ||= "app/views/#{plural_scope || :devise}" + end + + def plural_scope + @plural_scope ||= scope.presence && scope.underscore.pluralize end end @@ -68,6 +82,13 @@ class SimpleFormForGenerator < Rails::Generators::Base #:nodoc: source_root File.expand_path("../../templates/simple_form_for", __FILE__) desc "Copies simple form enabled views to your application." hide! + + def copy_views + if options[:views] + options[:views].delete('mailer') + end + super + end end class ErbGenerator < Rails::Generators::Base #:nodoc: @@ -77,7 +98,9 @@ class ErbGenerator < Rails::Generators::Base #:nodoc: hide! def copy_views - view_directory :mailer + if !options[:views] || options[:views].include?('mailer') + view_directory :mailer + end end end @@ -88,29 +111,35 @@ class MarkerbGenerator < Rails::Generators::Base #:nodoc: hide! def copy_views - view_directory :markerb, target_path + if !options[:views] || options[:views].include?('mailer') + view_directory :markerb, target_path + end end def target_path - "app/views/#{scope || :devise}/mailer" + "app/views/#{plural_scope || :devise}/mailer" end end class ViewsGenerator < Rails::Generators::Base desc "Copies Devise views to your application." - argument :scope, :required => false, :default => nil, - :desc => "The scope to copy views to" + argument :scope, required: false, default: nil, + desc: "The scope to copy views to" invoke SharedViewsGenerator - hook_for :form_builder, :aliases => "-b", - :desc => "Form builder to be used", - :default => defined?(SimpleForm) ? "simple_form_for" : "form_for" + hook_for :form_builder, aliases: "-b", + desc: "Form builder to be used", + default: defined?(SimpleForm) ? "simple_form_for" : "form_for" + + hook_for :markerb, desc: "Generate markerb instead of erb mail views", + default: defined?(Markerb), + type: :boolean - hook_for :markerb, :desc => "Generate markerb instead of erb mail views", - :default => defined?(Markerb) ? :markerb : :erb, - :type => :boolean + hook_for :erb, desc: "Generate erb mail views", + default: !defined?(Markerb), + type: :boolean end end end diff --git a/lib/generators/mongoid/devise_generator.rb b/lib/generators/mongoid/devise_generator.rb index d59a844ed4..777f3d6bc6 100644 --- a/lib/generators/mongoid/devise_generator.rb +++ b/lib/generators/mongoid/devise_generator.rb @@ -1,3 +1,6 @@ +# frozen_string_literal: true + +require 'rails/generators/named_base' require 'generators/devise/orm_helpers' module Mongoid @@ -10,51 +13,45 @@ def generate_model end def inject_field_types - inject_into_file model_path, migration_data, :after => "include Mongoid::Document\n" if model_exists? + inject_into_file model_path, migration_data, after: "include Mongoid::Document\n" if model_exists? end def inject_devise_content - inject_into_file model_path, model_contents, :after => "include Mongoid::Document\n" if model_exists? + inject_into_file model_path, model_contents, after: "include Mongoid::Document\n" if model_exists? end def migration_data < String, :default => "" - field :encrypted_password, :type => String, :default => "" + field :email, type: String, default: "" + field :encrypted_password, type: String, default: "" - validates_presence_of :email - validates_presence_of :encrypted_password - ## Recoverable - field :reset_password_token, :type => String - field :reset_password_sent_at, :type => Time + field :reset_password_token, type: String + field :reset_password_sent_at, type: Time ## Rememberable - field :remember_created_at, :type => Time + 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 - # field :confirmed_at, :type => Time - # field :confirmation_sent_at, :type => Time - # field :unconfirmed_email, :type => String # Only if using reconfirmable + # field :confirmation_token, type: String + # field :confirmed_at, type: Time + # field :confirmation_sent_at, type: Time + # field :unconfirmed_email, type: String # Only if using reconfirmable ## 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 - - ## Token authenticatable - # field :authentication_token, :type => String + # 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 RUBY end end end -end \ No newline at end of file +end diff --git a/lib/generators/templates/README b/lib/generators/templates/README index d2a26945ab..c89920b0c6 100644 --- a/lib/generators/templates/README +++ b/lib/generators/templates/README @@ -1,19 +1,23 @@ =============================================================================== -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 + 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 in config/environments/development.rb: - config.action_mailer.default_url_options = { :host => 'localhost:3000' } + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } 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" + 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,11 +25,12 @@ Some setup you must do manually if you haven't yet:

<%= notice %>

<%= alert %>

- 4. If you are deploying Rails 3.1 on Heroku, you may want to set: + * Not required for API-only Applications * - config.assets.initialize_on_precompile = false + 4. You can copy Devise views (for customization) to your app by running: - On config/application.rb forcing your application to not access the DB - or load models when precompiling your assets. + rails g devise:views + + * Not required * =============================================================================== diff --git a/lib/generators/templates/controllers/README b/lib/generators/templates/controllers/README new file mode 100644 index 0000000000..8671bbb280 --- /dev/null +++ b/lib/generators/templates/controllers/README @@ -0,0 +1,14 @@ +=============================================================================== + +Some setup you must do manually if you haven't yet: + + Ensure you have overridden routes for generated controllers in your routes.rb. + For example: + + Rails.application.routes.draw do + devise_for :users, controllers: { + sessions: 'users/sessions' + } + end + +=============================================================================== diff --git a/lib/generators/templates/controllers/confirmations_controller.rb b/lib/generators/templates/controllers/confirmations_controller.rb new file mode 100644 index 0000000000..e0466111c8 --- /dev/null +++ b/lib/generators/templates/controllers/confirmations_controller.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +class <%= @scope_prefix %>ConfirmationsController < Devise::ConfirmationsController + # GET /resource/confirmation/new + # def new + # super + # end + + # POST /resource/confirmation + # def create + # super + # end + + # GET /resource/confirmation?confirmation_token=abcdef + # def show + # super + # end + + # protected + + # The path used after resending confirmation instructions. + # def after_resending_confirmation_instructions_path_for(resource_name) + # super(resource_name) + # end + + # The path used after confirmation. + # def after_confirmation_path_for(resource_name, resource) + # super(resource_name, resource) + # end +end diff --git a/lib/generators/templates/controllers/omniauth_callbacks_controller.rb b/lib/generators/templates/controllers/omniauth_callbacks_controller.rb new file mode 100644 index 0000000000..29556cf6e9 --- /dev/null +++ b/lib/generators/templates/controllers/omniauth_callbacks_controller.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +class <%= @scope_prefix %>OmniauthCallbacksController < Devise::OmniauthCallbacksController + # You should configure your model like this: + # devise :omniauthable, omniauth_providers: [:twitter] + + # You should also create an action method in this controller like this: + # def twitter + # end + + # More info at: + # https://github.com/heartcombo/devise#omniauth + + # GET|POST /resource/auth/twitter + # def passthru + # super + # end + + # GET|POST /users/auth/twitter/callback + # def failure + # super + # end + + # protected + + # The path used when OmniAuth fails + # def after_omniauth_failure_path_for(scope) + # super(scope) + # end +end diff --git a/lib/generators/templates/controllers/passwords_controller.rb b/lib/generators/templates/controllers/passwords_controller.rb new file mode 100644 index 0000000000..afd468cc1d --- /dev/null +++ b/lib/generators/templates/controllers/passwords_controller.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +class <%= @scope_prefix %>PasswordsController < Devise::PasswordsController + # GET /resource/password/new + # def new + # super + # end + + # POST /resource/password + # def create + # super + # end + + # GET /resource/password/edit?reset_password_token=abcdef + # def edit + # super + # end + + # PUT /resource/password + # def update + # super + # end + + # protected + + # def after_resetting_password_path_for(resource) + # super(resource) + # end + + # The path used after sending reset password instructions + # def after_sending_reset_password_instructions_path_for(resource_name) + # super(resource_name) + # end +end diff --git a/lib/generators/templates/controllers/registrations_controller.rb b/lib/generators/templates/controllers/registrations_controller.rb new file mode 100644 index 0000000000..cdd91acc12 --- /dev/null +++ b/lib/generators/templates/controllers/registrations_controller.rb @@ -0,0 +1,62 @@ +# 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] + + # GET /resource/sign_up + # def new + # super + # end + + # POST /resource + # def create + # super + # end + + # GET /resource/edit + # def edit + # super + # end + + # PUT /resource + # def update + # super + # end + + # DELETE /resource + # def destroy + # super + # end + + # GET /resource/cancel + # Forces the session data which is usually expired after sign + # in to be expired now. This is useful if the user wants to + # cancel oauth signing in/up in the middle of the process, + # removing all OAuth session data. + # def cancel + # super + # end + + # protected + + # If you have extra params to permit, append them to the sanitizer. + # def configure_sign_up_params + # devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) + # end + + # If you have extra params to permit, append them to the sanitizer. + # def configure_account_update_params + # devise_parameter_sanitizer.permit(:account_update, keys: [:attribute]) + # end + + # The path used after sign up. + # def after_sign_up_path_for(resource) + # super(resource) + # end + + # The path used after sign up for inactive accounts. + # def after_inactive_sign_up_path_for(resource) + # super(resource) + # end +end diff --git a/lib/generators/templates/controllers/sessions_controller.rb b/lib/generators/templates/controllers/sessions_controller.rb new file mode 100644 index 0000000000..f229c9b4a0 --- /dev/null +++ b/lib/generators/templates/controllers/sessions_controller.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +class <%= @scope_prefix %>SessionsController < Devise::SessionsController + # before_action :configure_sign_in_params, only: [:create] + + # GET /resource/sign_in + # def new + # super + # end + + # POST /resource/sign_in + # def create + # super + # end + + # DELETE /resource/sign_out + # def destroy + # super + # end + + # protected + + # If you have extra params to permit, append them to the sanitizer. + # def configure_sign_in_params + # devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute]) + # end +end diff --git a/lib/generators/templates/controllers/unlocks_controller.rb b/lib/generators/templates/controllers/unlocks_controller.rb new file mode 100644 index 0000000000..0eadbbf65b --- /dev/null +++ b/lib/generators/templates/controllers/unlocks_controller.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +class <%= @scope_prefix %>UnlocksController < Devise::UnlocksController + # GET /resource/unlock/new + # def new + # super + # end + + # POST /resource/unlock + # def create + # super + # end + + # GET /resource/unlock?unlock_token=abcdef + # def show + # super + # end + + # protected + + # The path used after sending unlock password instructions + # def after_sending_unlock_instructions_path_for(resource) + # super(resource) + # end + + # The path used after unlocking the resource + # def after_unlock_path_for(resource) + # super(resource) + # end +end diff --git a/lib/generators/templates/devise.rb b/lib/generators/templates/devise.rb index 3836a61c66..b36f281f25 100644 --- a/lib/generators/templates/devise.rb +++ b/lib/generators/templates/devise.rb @@ -1,13 +1,36 @@ +# 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| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` as its `secret_key` + # 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 with default "from" parameter. - config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com" + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. - # config.mailer = "Devise::Mailer" + # config.mailer = 'Devise::Mailer' + + # Configure the parent class responsible to send e-mails. + # config.parent_mailer = 'ActionMailer::Base' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and @@ -23,7 +46,7 @@ # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. - # config.authentication_keys = [ :email ] + # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the @@ -35,12 +58,12 @@ # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. - config.case_insensitive_keys = [ :email ] + config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. - config.strip_whitespace_keys = [ :email ] + config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the @@ -48,17 +71,21 @@ # enable it only for database (email + password) authentication. # config.params_authenticatable = true - # Tell if authentication through HTTP Basic Auth is enabled. False by default. + # 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 = [:token]` will - # enable it only for token authentication. + # given strategies, for example, `config.http_authenticatable = [:database]` will + # 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 - # If http headers should be returned for AJAX requests. True by default. + # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true - # The realm used in Http Basic Authentication. "Application" by default. - # config.http_authentication_realm = "Application" + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. @@ -66,30 +93,56 @@ # config.paranoid = true # By default Devise will store the user in session. You can skip storage for - # :http_auth and :token_auth by adding those symbols to the array below. + # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by - # passing :skip => :sessions to `devise_for` in your config/routes.rb + # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + # config.reload_routes = true + # ==> Configuration for :database_authenticatable - # For bcrypt, this is the cost for hashing the password and defaults to 10. If - # using other encryptors, it sets how many times you want the password re-encrypted. + # 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. - config.stretches = Rails.env.test? ? 1 : 10 + # 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 : 12 + + # Set up a pepper to generate the hashed password. + # config.pepper = '<%= SecureRandom.hex(64) %>' + + # Send a notification to the original email when the user's email is changed. + # config.send_email_changed_notification = false - # Setup a pepper to generate the encrypted password. - # config.pepper = <%= SecureRandom.hex(64).inspect %> + # Send a notification email when the user's password is changed. + # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without - # confirming his account. For instance, if set to 2.days, the user will be - # able to access the website for two days without confirming his account, - # access will be blocked just in the third day. Default is 0.days, meaning - # the user cannot access the website without confirming his account. + # 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. + # 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 @@ -102,41 +155,44 @@ # If true, requires any email changes to be confirmed (exactly the same way as # 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. + # 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 - # config.confirmation_keys = [ :email ] + # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set - # :secure => true in order to force SSL only cookies. + # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable - # Range for password length. Default is 8..128. - config.password_length = 8..128 + # Range for password length. + config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that - # an one (and only one) @ exists in the given string. This is mainly + # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. - # config.email_regexp = /\A[^@]+@[^@]+\z/ + config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes - # If true, expires auth token on session timeout. - # config.expire_auth_token_on_timeout = false - # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. @@ -144,7 +200,7 @@ # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account - # config.unlock_keys = [ :email ] + # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email @@ -160,28 +216,33 @@ # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account - # config.reset_password_keys = [ :email ] + # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + # ==> Configuration for :encryptable - # Allow you to use another encryption algorithm besides bcrypt (default). You can use - # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, - # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) - # and :restful_authentication_sha1 (then you should set stretches to 10, and copy - # REST_AUTH_SITE_KEY to pepper) + # Allow you to use another hashing or encryption algorithm besides bcrypt (default). + # You can use :sha1, :sha512 or algorithms from others authentication tools as + # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 + # for default behavior) and :restful_authentication_sha1 (then you should set + # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 - # ==> Configuration for :token_authenticatable - # Defines name of the authentication token params key - # config.token_authentication_key = :auth_token - # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you @@ -198,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 @@ -213,15 +274,15 @@ # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. - # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # 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 @@ -229,12 +290,27 @@ # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # - # mount MyEngine, at: "/my_engine" + # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # - # When using omniauth, Devise cannot automatically set Omniauth path, + # 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" + # 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/markerb/confirmation_instructions.markerb b/lib/generators/templates/markerb/confirmation_instructions.markerb index 84665383ec..48ebb86739 100644 --- a/lib/generators/templates/markerb/confirmation_instructions.markerb +++ b/lib/generators/templates/markerb/confirmation_instructions.markerb @@ -1,5 +1,5 @@ -Welcome <%= @resource.email %>! +Welcome <%= @email %>! You can confirm your account through the link below: -<%= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token => @resource.confirmation_token) %> +[Confirm my account](<%= confirmation_url(@resource, confirmation_token: @token) %>) diff --git a/lib/generators/templates/markerb/email_changed.markerb b/lib/generators/templates/markerb/email_changed.markerb new file mode 100644 index 0000000000..5416b2a534 --- /dev/null +++ b/lib/generators/templates/markerb/email_changed.markerb @@ -0,0 +1,7 @@ +Hello <%= @email %>! + +<% if @resource.try(:unconfirmed_email?) %> +We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>. +<% else %> +We're contacting you to notify you that your email has been changed to <%= @resource.email %>. +<% end %> diff --git a/lib/generators/templates/markerb/password_change.markerb b/lib/generators/templates/markerb/password_change.markerb new file mode 100644 index 0000000000..4f9f96203a --- /dev/null +++ b/lib/generators/templates/markerb/password_change.markerb @@ -0,0 +1,3 @@ +Hello <%= @resource.email %>! + +We're contacting you to notify you that your password has been changed. diff --git a/lib/generators/templates/markerb/reset_password_instructions.markerb b/lib/generators/templates/markerb/reset_password_instructions.markerb index 5587598d89..eead40a09a 100644 --- a/lib/generators/templates/markerb/reset_password_instructions.markerb +++ b/lib/generators/templates/markerb/reset_password_instructions.markerb @@ -2,7 +2,7 @@ Hello <%= @resource.email %>! Someone has requested a link to change your password, and you can do this through the link below. -<%= link_to 'Change my password', edit_password_url(@resource, :reset_password_token => @resource.reset_password_token) %> +[Change my password](<%= edit_password_url(@resource, reset_password_token: @token) %>) If you didn't request this, please ignore this email. Your password won't change until you access the link above and create a new one. diff --git a/lib/generators/templates/markerb/unlock_instructions.markerb b/lib/generators/templates/markerb/unlock_instructions.markerb index 9bab190438..ff0d9c38dd 100644 --- a/lib/generators/templates/markerb/unlock_instructions.markerb +++ b/lib/generators/templates/markerb/unlock_instructions.markerb @@ -1,7 +1,7 @@ Hello <%= @resource.email %>! -Your account has been locked due to an excessive amount of unsuccessful sign in attempts. +Your account has been locked due to an excessive number of unsuccessful sign in attempts. Click the link below to unlock your account: -<%= link_to 'Unlock my account', unlock_url(@resource, :unlock_token => @resource.unlock_token) %> +[Unlock my account](<%= unlock_url(@resource, unlock_token: @token) %>) 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 c2387ac49a..f7b4a65c50 100644 --- a/lib/generators/templates/simple_form_for/confirmations/new.html.erb +++ b/lib/generators/templates/simple_form_for/confirmations/new.html.erb @@ -1,10 +1,15 @@

Resend confirmation instructions

-<%= simple_form_for(resource, :as => resource_name, :url => confirmation_path(resource_name), :html => { :method => :post }) do |f| %> +<%= simple_form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %> + <%= 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 5a2442a692..591cd8c85a 100644 --- a/lib/generators/templates/simple_form_for/passwords/edit.html.erb +++ b/lib/generators/templates/simple_form_for/passwords/edit.html.erb @@ -1,14 +1,22 @@

Change your password

-<%= simple_form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :put }) do |f| %> +<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> <%= f.error_notification %> - <%= f.input :reset_password_token, :as => :hidden %> + <%= f.input :reset_password_token, as: :hidden %> <%= f.full_error :reset_password_token %>
- <%= f.input :password, :label => "New password", :required => true, :autofocus => true %> - <%= 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 b196bc90e2..01ce0b8b9b 100644 --- a/lib/generators/templates/simple_form_for/passwords/new.html.erb +++ b/lib/generators/templates/simple_form_for/passwords/new.html.erb @@ -1,10 +1,13 @@

Forgot your password?

-<%= simple_form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :post }) do |f| %> +<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %>
- <%= f.input :email, :required => true, :autofocus => true %> + <%= f.input :email, + required: true, + autofocus: true, + input_html: { autocomplete: "email" } %>
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 6a9a4b390c..b3c0089adb 100644 --- a/lib/generators/templates/simple_form_for/registrations/edit.html.erb +++ b/lib/generators/templates/simple_form_for/registrations/edit.html.erb @@ -1,13 +1,26 @@

Edit <%= resource_name.to_s.humanize %>

-<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %> +<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> <%= f.error_notification %>
- <%= f.input :email, :required => true, :autofocus => true %> - <%= 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 :email, required: true, autofocus: true %> + + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +

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

+ <% end %> + + <%= 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" } %>
@@ -17,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 2665b08174..5dafdd7601 100644 --- a/lib/generators/templates/simple_form_for/registrations/new.html.erb +++ b/lib/generators/templates/simple_form_for/registrations/new.html.erb @@ -1,12 +1,20 @@

Sign up

-<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> +<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= f.error_notification %>
- <%= f.input :email, :required => true, :autofocus => true %> - <%= f.input :password, :required => true %> - <%= 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 fa53ea87cc..e542e61827 100644 --- a/lib/generators/templates/simple_form_for/sessions/new.html.erb +++ b/lib/generators/templates/simple_form_for/sessions/new.html.erb @@ -1,14 +1,19 @@ -

Sign in

+

Log in

-<%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %> +<%= 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 :remember_me, :as => :boolean if devise_mapping.rememberable? %> + <%= 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? %>
- <%= f.button :submit, "Sign in" %> + <%= f.button :submit, "Log in" %>
<% end %> 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 bf39643a01..c42de1738e 100644 --- a/lib/generators/templates/simple_form_for/unlocks/new.html.erb +++ b/lib/generators/templates/simple_form_for/unlocks/new.html.erb @@ -1,10 +1,14 @@

Resend unlock instructions

-<%= simple_form_for(resource, :as => resource_name, :url => unlock_path(resource_name), :html => { :method => :post }) do |f| %> +<%= simple_form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %> + <%= 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 new file mode 100644 index 0000000000..683322ebf8 --- /dev/null +++ b/test/controllers/custom_registrations_controller_test.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +require 'test_helper' + +class CustomRegistrationsControllerTest < Devise::ControllerTestCase + tests Custom::RegistrationsController + + include Devise::Test::ControllerHelpers + + setup do + request.env["devise.mapping"] = Devise.mappings[:user] + @password = 'password' + @user = create_user(password: @password, password_confirmation: @password).tap(&:confirm) + end + + test "yield resource to block on create success" do + post :create, params: { user: { email: "user@example.org", password: "password", password_confirmation: "password" } } + assert @controller.create_block_called?, "create failed to yield resource to provided block" + end + + test "yield resource to block on create failure" do + post :create, params: { user: { } } + assert @controller.create_block_called?, "create failed to yield resource to provided block" + end + + test "yield resource to block on update success" do + sign_in @user + put :update, params: { user: { current_password: @password } } + assert @controller.update_block_called?, "update failed to yield resource to provided block" + end + + test "yield resource to block on update failure" do + sign_in @user + put :update, params: { user: { } } + assert @controller.update_block_called?, "update failed to yield resource to provided block" + end + + test "yield resource to block on new" do + get :new + assert @controller.new_block_called?, "new failed to yield resource to provided block" + end +end diff --git a/test/controllers/custom_strategy_test.rb b/test/controllers/custom_strategy_test.rb index 798ca77724..1c96812640 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 @@ -24,10 +26,10 @@ def authenticate! end end -class CustomStrategyTest < ActionController::TestCase +class CustomStrategyTest < Devise::ControllerTestCase tests CustomStrategyController - include Devise::TestHelpers + include Devise::Test::ControllerHelpers setup do Warden::Strategies.add(:custom_strategy, CustomStrategy) @@ -40,9 +42,8 @@ class CustomStrategyTest < ActionController::TestCase 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 # for verification. In production, the above array would be delivered directly to Rack. @@ -52,11 +53,10 @@ class CustomStrategyTest < ActionController::TestCase 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 new file mode 100644 index 0000000000..998cab6fb4 --- /dev/null +++ b/test/controllers/helper_methods_test.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require 'test_helper' + +class ApiController < ActionController::Metal + include Devise::Controllers::Helpers +end + +class HelperMethodsTest < Devise::ControllerTestCase + tests ApiController + + test 'includes Devise::Controllers::Helpers' do + assert_includes @controller.class.ancestors, Devise::Controllers::Helpers + end + + test 'does not respond_to helper or helper_method' do + assert_not_respond_to @controller.class, :helper + assert_not_respond_to @controller.class, :helper_method + end + + test 'defines methods like current_user' do + assert_respond_to @controller, :current_user + end +end diff --git a/test/controllers/helpers_test.rb b/test/controllers/helpers_test.rb index 8036b5462b..57acdba9c3 100644 --- a/test/controllers/helpers_test.rb +++ b/test/controllers/helpers_test.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'test_helper' require 'ostruct' -class ControllerAuthenticatableTest < ActionController::TestCase +class ControllerAuthenticatableTest < Devise::ControllerTestCase tests ApplicationController def setup @@ -14,81 +16,110 @@ def setup end test 'proxy signed_in?(scope) to authenticate?' do - @mock_warden.expects(:authenticate?).with(:scope => :my_scope) + @mock_warden.expects(:authenticate?).with(scope: :my_scope) @controller.signed_in?(:my_scope) end test 'proxy signed_in?(nil) to authenticate?' do Devise.mappings.keys.each do |scope| # :user, :admin, :manager - @mock_warden.expects(:authenticate?).with(:scope => scope) + @mock_warden.expects(:authenticate?).with(scope: scope) end @controller.signed_in? end + test 'proxy [group]_signed_in? to authenticate? with each scope' do + [:user, :admin].each do |scope| + @mock_warden.expects(:authenticate?).with(scope: scope).returns(false) + end + @controller.commenter_signed_in? + end + test 'proxy current_user to authenticate with user scope' do - @mock_warden.expects(:authenticate).with(:scope => :user) + @mock_warden.expects(:authenticate).with(scope: :user) @controller.current_user end test 'proxy current_admin to authenticate with admin scope' do - @mock_warden.expects(:authenticate).with(:scope => :admin) + @mock_warden.expects(:authenticate).with(scope: :admin) @controller.current_admin end + test 'proxy current_[group] to authenticate with each scope' do + [:user, :admin].each do |scope| + @mock_warden.expects(:authenticate).with(scope: scope).returns(nil) + end + @controller.current_commenter + end + + test 'proxy current_[plural_group] to authenticate with each scope' do + [:user, :admin].each do |scope| + @mock_warden.expects(:authenticate).with(scope: scope) + end + @controller.current_commenters + end + test 'proxy current_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) @controller.current_publisher_account 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") - @controller.authenticate_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, 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 test 'proxy user_signed_in? to authenticate with user scope' do - @mock_warden.expects(:authenticate).with(:scope => :user).returns("user") + @mock_warden.expects(:authenticate).with(scope: :user).returns("user") assert @controller.user_signed_in? end test 'proxy admin_signed_in? to authenticatewith admin scope' do - @mock_warden.expects(:authenticate).with(:scope => :admin) + @mock_warden.expects(:authenticate).with(scope: :admin) assert_not @controller.admin_signed_in? end test 'proxy publisher_account_signed_in? to authenticate with namespaced publisher account scope' do - @mock_warden.expects(:authenticate).with(:scope => :publisher_account) + @mock_warden.expects(:authenticate).with(scope: :publisher_account) @controller.publisher_account_signed_in? end test 'proxy user_session to session scope in warden' do - @mock_warden.expects(:authenticate).with(:scope => :user).returns(true) + @mock_warden.expects(:authenticate).with(scope: :user).returns(true) @mock_warden.expects(:session).with(:user).returns({}) @controller.user_session end test 'proxy admin_session to session scope in warden' do - @mock_warden.expects(:authenticate).with(:scope => :admin).returns(true) + @mock_warden.expects(:authenticate).with(scope: :admin).returns(true) @mock_warden.expects(:session).with(:admin).returns({}) @controller.admin_session end test 'proxy publisher_account_session from namespaced scope to session scope in warden' do - @mock_warden.expects(:authenticate).with(:scope => :publisher_account).returns(true) + @mock_warden.expects(:authenticate).with(scope: :publisher_account).returns(true) @mock_warden.expects(:session).with(:publisher_account).returns({}) @controller.publisher_account_session end @@ -96,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 @@ -117,15 +148,15 @@ 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) - @controller.sign_in(user, :force => true) + @mock_warden.expects(:set_user).with(user, { scope: :user }).returns(true) + @controller.sign_in(user, force: true) end - test 'sign in accepts bypass as option' do + test 'bypass the sign in' do user = User.new @mock_warden.expects(:session_serializer).returns(serializer = mock()) serializer.expects(:store).with(user, :user) - @controller.sign_in(user, :bypass => true) + @controller.bypass_sign_in(user) end test 'sign out clears up any signed in user from all scopes' do @@ -135,24 +166,24 @@ def setup @controller.instance_variable_set(:@current_user, user) @controller.instance_variable_set(:@current_admin, user) @controller.sign_out - assert_equal nil, @controller.instance_variable_get(:@current_user) - assert_equal nil, @controller.instance_variable_get(:@current_admin) + assert_nil @controller.instance_variable_get(:@current_user) + assert_nil @controller.instance_variable_get(:@current_admin) end test 'sign out logs out and clears up any signed in user by scope' do user = User.new - @mock_warden.expects(:user).with(:scope => :user, :run_callbacks => false).returns(user) + @mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(user) @mock_warden.expects(:logout).with(:user).returns(true) - @mock_warden.expects(:clear_strategies_cache!).with(:scope => :user).returns(true) + @mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true) @controller.instance_variable_set(:@current_user, user) @controller.sign_out(:user) - assert_equal nil, @controller.instance_variable_get(:@current_user) + assert_nil @controller.instance_variable_get(:@current_user) end test 'sign out accepts a resource as argument' do - @mock_warden.expects(:user).with(:scope => :user, :run_callbacks => false).returns(true) + @mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(true) @mock_warden.expects(:logout).with(:user).returns(true) - @mock_warden.expects(:clear_strategies_cache!).with(:scope => :user).returns(true) + @mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true) @controller.sign_out(User.new) end @@ -187,6 +218,40 @@ def setup assert_nil @controller.session[:"user_return_to"] end + test 'store location for stores a location to redirect back to' do + assert_nil @controller.stored_location_for(:user) + @controller.store_location_for(:user, "/foo.bar") + 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) + end + + test 'store location for accepts a resource as argument' do + @controller.store_location_for(User.new, "/foo.bar") + assert_equal "/foo.bar", @controller.stored_location_for(User.new) + end + + test 'store location for stores paths' do + @controller.store_location_for(:user, "//host/foo.bar") + assert_equal "/foo.bar", @controller.stored_location_for(:user) + @controller.store_location_for(:user, "///foo.bar") + assert_equal "/foo.bar", @controller.stored_location_for(:user) + end + + test 'store location for stores query string' do + @controller.store_location_for(:user, "/foo?bar=baz") + assert_equal "/foo?bar=baz", @controller.stored_location_for(:user) + end + + test 'store location for stores fragments' do + @controller.store_location_for(:user, "/foo#bar") + assert_equal "/foo#bar", @controller.stored_location_for(:user) + end + test 'after sign in path defaults to root path if none by was specified for the given scope' do assert_equal root_path, @controller.after_sign_in_path_for(:user) end @@ -202,9 +267,9 @@ def setup test 'sign in and redirect uses the stored location' do user = User.new - @controller.session[:"user_return_to"] = "/foo.bar" + @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 @@ -212,7 +277,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 @@ -226,10 +291,10 @@ def setup end test 'sign out and redirect uses the configured after sign out path when signing out only the current scope' do - swap Devise, :sign_out_all_scopes => false do - @mock_warden.expects(:user).with(:scope => :admin, :run_callbacks => false).returns(true) + swap Devise, sign_out_all_scopes: false do + @mock_warden.expects(:user).with(scope: :admin, run_callbacks: false).returns(true) @mock_warden.expects(:logout).with(:admin).returns(true) - @mock_warden.expects(:clear_strategies_cache!).with(:scope => :admin).returns(true) + @mock_warden.expects(:clear_strategies_cache!).with(scope: :admin).returns(true) @controller.expects(:redirect_to).with(admin_root_path) @controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end" @controller.sign_out_and_redirect(:admin) @@ -237,7 +302,7 @@ def setup end test 'sign out and redirect uses the configured after sign out path when signing out all scopes' do - swap Devise, :sign_out_all_scopes => true do + swap Devise, sign_out_all_scopes: true do @mock_warden.expects(:user).times(Devise.mappings.size) @mock_warden.expects(:logout).with().returns(true) @mock_warden.expects(:clear_strategies_cache!).with().returns(true) @@ -247,6 +312,16 @@ 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 assert_not @controller.devise_controller? end diff --git a/test/controllers/inherited_controller_i18n_messages_test.rb b/test/controllers/inherited_controller_i18n_messages_test.rb new file mode 100644 index 0000000000..f5d142d218 --- /dev/null +++ b/test/controllers/inherited_controller_i18n_messages_test.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +require 'test_helper' + +class SessionsInheritedController < Devise::SessionsController + def test_i18n_scope + set_flash_message(:notice, :signed_in) + end +end + +class AnotherInheritedController < SessionsInheritedController + protected + + def translation_scope + 'another' + end +end + +class InheritedControllerTest < Devise::ControllerTestCase + tests SessionsInheritedController + + def setup + @mock_warden = OpenStruct.new + @controller.request.env['warden'] = @mock_warden + @controller.request.env['devise.mapping'] = Devise.mappings[:user] + end + + test 'I18n scope is inherited from Devise::Sessions' do + I18n.expects(:t).with do |message, options| + message == 'user.signed_in' && + options[:scope] == 'devise.sessions' + end + @controller.test_i18n_scope + end +end + +class AnotherInheritedControllerTest < Devise::ControllerTestCase + tests AnotherInheritedController + + def setup + @mock_warden = OpenStruct.new + @controller.request.env['warden'] = @mock_warden + @controller.request.env['devise.mapping'] = Devise.mappings[:user] + end + + test 'I18n scope is overridden' do + I18n.expects(:t).with do |message, options| + message == 'user.signed_in' && + options[:scope] == 'another' + end + @controller.test_i18n_scope + end +end diff --git a/test/controllers/internal_helpers_test.rb b/test/controllers/internal_helpers_test.rb index 504aa90b7c..124c8df06d 100644 --- a/test/controllers/internal_helpers_test.rb +++ b/test/controllers/internal_helpers_test.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'test_helper' class MyController < DeviseController end -class HelpersTest < ActionController::TestCase +class HelpersTest < Devise::ControllerTestCase tests MyController def setup @@ -13,16 +15,16 @@ def setup end test 'get resource name from env' do - assert_equal :user, @controller.resource_name + assert_equal :user, @controller.send(:resource_name) end test 'get resource class from env' do - assert_equal User, @controller.resource_class + assert_equal User, @controller.send(:resource_class) end test 'get resource instance variable from env' do @controller.instance_variable_set(:@user, user = User.new) - assert_equal user, @controller.resource + assert_equal user, @controller.send(:resource) end test 'set resource instance variable from env' do @@ -34,18 +36,26 @@ def setup end test 'get resource params from request params using resource name as key' do - user_params = {'name' => 'Shirley Templar'} - @controller.stubs(:params).returns(HashWithIndifferentAccess.new({'user' => user_params})) + user_params = {'email' => 'shirley@templar.com'} + + # Stub controller name so strong parameters can filter properly. + # DeviseController does not allow any parameters by default. + @controller.stubs(:controller_name).returns(:sessions_controller) - assert_equal user_params, @controller.resource_params + params = ActionController::Parameters.new({'user' => user_params}) + + @controller.stubs(:params).returns(params) + + res_params = @controller.send(:resource_params).permit!.to_h + assert_equal user_params, res_params end test 'resources methods are not controller actions' do - assert @controller.class.action_methods.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, :token_authenticatable, :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 @@ -61,7 +71,7 @@ def setup end test 'require no authentication sets a flash message' do - @mock_warden.expects(:authenticate?).with(:rememberable, :token_authenticatable, :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,8 +79,8 @@ def setup end test 'signed in resource returns signed in resource for current scope' do - @mock_warden.expects(:authenticate).with(:scope => :user).returns(User.new) - assert_kind_of User, @controller.signed_in_resource + @mock_warden.expects(:authenticate).with(scope: :user).returns(User.new) + assert_kind_of User, @controller.send(:signed_in_resource) end test 'is a devise controller' do @@ -89,16 +99,31 @@ def setup assert_equal 'non-blank', flash[:notice] end + test 'issues non-blank flash.now messages normally' do + I18n.stubs(:t).returns('non-blank') + @controller.send :set_flash_message, :notice, :send_instructions, { now: true } + assert_equal 'non-blank', flash.now[:notice] + end + test 'uses custom i18n options' do - @controller.stubs(:devise_i18n_options).returns(:default => "devise custom options") + @controller.stubs(:devise_i18n_options).returns(default: "devise custom options") @controller.send :set_flash_message, :notice, :invalid_i18n_messagesend_instructions assert_equal 'devise custom options', flash[:notice] end + test 'allows custom i18n options to override resource_name' do + I18n.expects(:t).with("custom_resource_name.confirmed", anything) + @controller.stubs(:devise_i18n_options).returns(resource_name: "custom_resource_name") + @controller.send :set_flash_message, :notice, :confirmed + end + test 'navigational_formats not returning a wild card' do MyController.send(:public, :navigational_formats) - Devise.navigational_formats = [:"*/*", :html] - assert_not @controller.navigational_formats.include?(:"*/*") + + swap Devise, navigational_formats: ['*/*', :html] do + assert_not @controller.navigational_formats.include?("*/*") + end + MyController.send(:protected, :navigational_formats) end end diff --git a/test/controllers/load_hooks_controller_test.rb b/test/controllers/load_hooks_controller_test.rb new file mode 100644 index 0000000000..63720c2e2b --- /dev/null +++ b/test/controllers/load_hooks_controller_test.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +require 'test_helper' + +class LoadHooksControllerTest < Devise::ControllerTestCase + setup do + ActiveSupport.on_load(:devise_controller) do + define_method :defined_by_load_hook do + puts 'I am defined dynamically by activesupport load hook' + end + end + end + + teardown do + DeviseController.class_eval { undef :defined_by_load_hook } + end + + test 'load hook called when controller is loaded' do + assert_includes DeviseController.instance_methods, :defined_by_load_hook + end +end diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb new file mode 100644 index 0000000000..8561027d98 --- /dev/null +++ b/test/controllers/passwords_controller_test.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +require 'test_helper' + +class PasswordsControllerTest < Devise::ControllerTestCase + tests Devise::PasswordsController + include Devise::Test::ControllerHelpers + + setup do + request.env["devise.mapping"] = Devise.mappings[:user] + @user = create_user.tap(&:confirm) + @raw = @user.send_reset_password_instructions + end + + def put_update_with_params + put :update, params: { "user" => { + "reset_password_token" => @raw, "password" => "1234567", "password_confirmation" => "1234567" + } + } + end + + test 'redirect to after_sign_in_path_for if after_resetting_password_path_for is not overridden' do + put_update_with_params + assert_redirected_to "http://test.host/" + end + + test 'redirect accordingly if after_resetting_password_path_for is overridden' do + custom_path = "http://custom.path/" + Devise::PasswordsController.any_instance.stubs(:after_resetting_password_path_for).with(@user).returns(custom_path) + + 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 3818d9ccb6..9c970ab5d4 100644 --- a/test/controllers/sessions_controller_test.rb +++ b/test/controllers/sessions_controller_test.rb @@ -1,11 +1,32 @@ +# frozen_string_literal: true + require 'test_helper' -class SessionsControllerTest < ActionController::TestCase +class SessionsControllerTest < Devise::ControllerTestCase tests Devise::SessionsController - include Devise::TestHelpers + include Devise::Test::ControllerHelpers + + test "#create doesn't raise unpermitted params when sign in fails" do + begin + subscriber = ActiveSupport::Notifications.subscribe %r{unpermitted_parameters} do |name, start, finish, id, payload| + flunk "Unpermitted params: #{payload}" + end + request.env["devise.mapping"] = Devise.mappings[:user] + request.session["user_return_to"] = 'foo.bar' + create_user + post :create, params: { user: { + email: "wrong@email.com", + password: "wrongpassword" + } + } + assert_equal 200, @response.status + ensure + ActiveSupport::Notifications.unsubscribe(subscriber) + end + end test "#create works even with scoped views" do - swap Devise, :scoped_views => true do + swap Devise, scoped_views: true do request.env["devise.mapping"] = Devise.mappings[:user] post :create assert_equal 200, @response.status @@ -13,45 +34,69 @@ class SessionsControllerTest < ActionController::TestCase end end + test "#create delete the url stored in the session if the requested format is navigational" do + request.env["devise.mapping"] = Devise.mappings[:user] + request.session["user_return_to"] = 'foo.bar' + + user = create_user + user.confirm + post :create, params: { user: { + email: user.email, + password: user.password + } + } + assert_nil request.session["user_return_to"] + end + + test "#create doesn't delete the url stored in the session if the requested format is not navigational" do + request.env["devise.mapping"] = Devise.mappings[:user] + request.session["user_return_to"] = 'foo.bar' + + user = create_user + user.confirm + post :create, params: { format: 'json', user: { + email: user.email, + password: user.password + } + } + + assert_equal 'foo.bar', request.session["user_return_to"] + end + test "#create doesn't raise exception after Warden authentication fails when TestHelpers included" do request.env["devise.mapping"] = Devise.mappings[:user] - post :create, :user => { - :email => "nosuchuser@example.com", - :password => "wevdude" + post :create, params: { user: { + email: "nosuchuser@example.com", + password: "wevdude" + } } assert_equal 200, @response.status 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! - post :create, :format => 'json', :user => { - :email => user.email, - :password => user.password + user.confirm + post :create, params: { format: 'json', user: { + email: user.email, + password: user.password + } } - - delete :destroy, :format => 'json' + delete :destroy, format: 'json' assert flash[:notice].blank?, "flash[:notice] should be blank, not #{flash[:notice].inspect}" 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 ActiveModel::MassAssignmentSecurity::Error 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 \ No newline at end of file +end diff --git a/test/controllers/url_helpers_test.rb b/test/controllers/url_helpers_test.rb index 1b82bb8fff..e4b6a30933 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 < ActionController::TestCase +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 @@ -13,11 +15,17 @@ def assert_path_and_url(name, prepend_path=nil) assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user), send(:"#{prepend_path}user_#{name}_url") + # With string + assert_equal @controller.send(:"#{prepend_path}#{name}_path", "user"), + send(:"#{prepend_path}user_#{name}_path") + assert_equal @controller.send(:"#{prepend_path}#{name}_url", "user"), + send(:"#{prepend_path}user_#{name}_url") + # Default url params - assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user, :param => 123), - send(:"#{prepend_path}user_#{name}_path", :param => 123) - assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user, :param => 123), - send(:"#{prepend_path}user_#{name}_url", :param => 123) + assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user, param: 123), + send(:"#{prepend_path}user_#{name}_path", param: 123) + assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user, param: 123), + send(:"#{prepend_path}user_#{name}_url", param: 123) @request.path = nil # With an object diff --git a/test/delegator_test.rb b/test/delegator_test.rb index 1618be1053..851afbca0e 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 @@ -14,6 +16,6 @@ def delegator end test 'failure_app returns associated failure app by scope in the given environment' do - assert_kind_of Proc, delegator.failure_app({"warden.options" => {:scope => "manager"}}) + assert_kind_of Proc, delegator.failure_app({"warden.options" => {scope: "manager"}}) end end diff --git a/test/devise_test.rb b/test/devise_test.rb index 1b0746d73f..a46be0d527 100644 --- a/test/devise_test.rb +++ b/test/devise_test.rb @@ -1,18 +1,31 @@ +# frozen_string_literal: true + require 'test_helper' module Devise def self.yield_and_restore @@warden_configured = nil - c, b = @@warden_config, @@warden_config_block + c, b = @@warden_config, @@warden_config_blocks yield ensure - @@warden_config, @@warden_config_block = c, b + @@warden_config, @@warden_config_blocks = c, b end end class DeviseTest < ActiveSupport::TestCase + test 'bcrypt on the class' do + password = "super secret" + klass = Struct.new(:pepper, :stretches).new("blahblah", 2) + hash = Devise::Encryptor.digest(klass, password) + assert_equal ::BCrypt::Password.create(hash), hash + + klass = Struct.new(:pepper, :stretches).new("bla", 2) + hash = Devise::Encryptor.digest(klass, password) + assert_not_equal ::BCrypt::Password.new(hash), hash + end + test 'model options can be configured through Devise' do - swap Devise, :allow_unconfirmed_access_for => 113, :pepper => "foo" do + swap Devise, allow_unconfirmed_access_for: 113, pepper: "foo" do assert_equal 113, Devise.allow_unconfirmed_access_for assert_equal "foo", Devise.pepper end @@ -31,42 +44,71 @@ class DeviseTest < ActiveSupport::TestCase test 'warden manager user configuration through a block' do Devise.yield_and_restore do - @executed = false + executed = false Devise.warden do |config| - @executed = true + executed = true assert_kind_of Warden::Config, config end Devise.configure_warden! - assert @executed + assert executed + end + end + + test 'warden manager user configuration through multiple blocks' do + Devise.yield_and_restore do + executed = 0 + + 3.times do + Devise.warden { |config| executed += 1 } + end + + Devise.configure_warden! + assert_equal 3, executed end end test 'add new module using the helper method' do - assert_nothing_raised(Exception) { Devise.add_module(:coconut) } + Devise.add_module(:coconut) assert_equal 1, Devise::ALL.select { |v| v == :coconut }.size assert_not Devise::STRATEGIES.include?(:coconut) assert_not defined?(Devise::Models::Coconut) Devise::ALL.delete(:coconut) - assert_nothing_raised(Exception) { Devise.add_module(:banana, :strategy => :fruits) } + Devise.add_module(:banana, strategy: :fruits) assert_equal :fruits, Devise::STRATEGIES[:banana] Devise::ALL.delete(:banana) Devise::STRATEGIES.delete(:banana) - assert_nothing_raised(Exception) { Devise.add_module(:kivi, :controller => :fruits) } + Devise.add_module(:kivi, controller: :fruits) assert_equal :fruits, Devise::CONTROLLERS[:kivi] Devise::ALL.delete(:kivi) 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| assert_not Devise.secure_compare(empty, "something") assert_not Devise.secure_compare("something", empty) - assert_not Devise.secure_compare(empty, empty) end + 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 + valid_emails = ["test@example.com", "jo@jo.co", "f4$_m@you.com", "testing.example@example.com.ua", "test@tt", "test@valid---domain.com"] + non_valid_emails = ["rex", "test user@example.com", "test_user@example server.com"] + + valid_emails.each do |email| + assert_match Devise.email_regexp, email + end + non_valid_emails.each do |email| + assert_no_match Devise.email_regexp, email + end + end end diff --git a/test/failure_app_test.rb b/test/failure_app_test.rb index 39b0e871de..b57f4e4216 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' @@ -8,24 +10,87 @@ def fake_app end end + class FailureWithSubdomain < RootFailureApp + routes = ActionDispatch::Routing::RouteSet.new + + routes.draw do + scope subdomain: 'sub' do + root to: 'foo#bar' + end + end + + include routes.url_helpers + end + + class FailureWithI18nOptions < Devise::FailureApp + def i18n_options(options) + options.merge(name: 'Steve') + 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 _ + '/user_on_engines/sign_in' + end + end + + def main_app + raise 'main_app router called instead of fake_engine' + end + + def fake_engine + @fake_engine ||= FakeEngine.new + 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), + 'warden.options' => { scope: :user }, + 'action_dispatch.request.formats' => Array(env_params.delete('formats') || Mime[:html]), 'rack.input' => "", - 'warden' => OpenStruct.new(:message => nil) + 'warden' => OpenStruct.new(message: nil) }.merge!(env_params) + # Passing nil for action_dispatch.request.formats prevents the default from being used in Rails 5, need to remove it + if env.has_key?('action_dispatch.request.formats') && env['action_dispatch.request.formats'].nil? + env.delete 'action_dispatch.request.formats' unless env['action_dispatch.request.formats'] + 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 @@ -36,6 +101,13 @@ def call_failure(env_params={}) assert_equal 'http://test.host/users/sign_in', @response.second['Location'] end + test 'returns to the default redirect location considering subdomain' do + call_failure('warden.options' => { scope: :subdomain_user }) + assert_equal 302, @response.first + assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] + assert_equal 'http://sub.test.host/subdomain_users/sign_in', @response.second['Location'] + end + test 'returns to the default redirect location for wildcard requests' do call_failure 'action_dispatch.request.formats' => nil, 'HTTP_ACCEPT' => '*/*' assert_equal 302, @response.first @@ -43,32 +115,110 @@ def call_failure(env_params={}) end test 'returns to the root path if no session path is available' do - swap Devise, :router_name => :fake_app do - call_failure :app => RootFailureApp + swap Devise, router_name: :fake_app do + call_failure app: RootFailureApp 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 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 + assert_equal 302, @response.first + assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] + assert_equal 'http://sub.test.host/', @response.second['Location'] + end + end + + test 'returns to the default redirect location considering the router for supplied scope' do + call_failure app: FakeEngineApp, 'warden.options' => { scope: :user_on_engine } + 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/user_on_engines/sign_in', @response.second['Location'] + end + if Rails.application.config.respond_to?(:relative_url_root) test 'returns to the default redirect location considering the relative url root' do - swap Rails.application.config, :relative_url_root => "/sample" do + swap Rails.application.config, relative_url_root: "/sample" do call_failure assert_equal 302, @response.first assert_equal 'http://test.host/sample/users/sign_in', @response.second['Location'] end end + + test 'returns to the default redirect location considering the relative url root and subdomain' do + swap Rails.application.config, relative_url_root: "/sample" do + call_failure('warden.options' => { scope: :subdomain_user }) + assert_equal 302, @response.first + assert_equal 'http://sub.test.host/sample/subdomain_users/sign_in', @response.second['Location'] + end + end + end + + if Rails.application.config.action_controller.respond_to?(:relative_url_root) + test "returns to the default redirect location considering action_controller's relative url root" do + swap Rails.application.config.action_controller, relative_url_root: "/sample" do + call_failure + assert_equal 302, @response.first + assert_equal 'http://test.host/sample/users/sign_in', @response.second['Location'] + end + end + + test "returns to the default redirect location considering action_controller's relative url root and subdomain" do + swap Rails.application.config.action_controller, relative_url_root: "/sample" do + call_failure('warden.options' => { scope: :subdomain_user }) + assert_equal 302, @response.first + assert_equal 'http://sub.test.host/sample/subdomain_users/sign_in', @response.second['Location'] + end + end end test 'uses the proxy failure message as symbol' do - call_failure('warden' => OpenStruct.new(:message => :invalid)) + call_failure('warden' => OpenStruct.new(message: :invalid)) 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] + 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"] + end + test 'uses the proxy failure message as string' do - call_failure('warden' => OpenStruct.new(:message => 'Hello world')) + call_failure('warden' => OpenStruct.new(message: 'Hello world')) assert_equal 'Hello world', @request.flash[:alert] assert_equal 'http://test.host/users/sign_in', @response.second["Location"] end @@ -78,23 +228,27 @@ def call_failure(env_params={}) assert_equal 'text/html; charset=utf-8', @response.second['Content-Type'] end - test 'setup a default message' do + 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 test 'redirects the correct format if it is a non-html format request' do - swap Devise, :navigational_formats => [:js] do - call_failure('formats' => Mime::JS) + swap Devise, navigational_formats: [:js] do + call_failure('formats' => Mime[:js]) assert_equal 'http://test.host/users/sign_in.js', @response.second["Location"] end end @@ -102,18 +256,18 @@ 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 test 'return appropriate body for xml' do - call_failure('formats' => Mime::XML) + call_failure('formats' => Mime[:xml]) result = %(\n\n You need to sign in or sign up before continuing.\n\n) assert_equal result, @response.last.body end test 'return appropriate body for json' do - call_failure('formats' => Mime::JSON) + call_failure('formats' => Mime[:json]) result = %({"error":"You need to sign in or sign up before continuing."}) assert_equal result, @response.last.body end @@ -124,42 +278,48 @@ 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) + swap Devise, http_authenticatable: false do + call_failure('formats' => Mime[:json]) assert_nil @response.second["WWW-Authenticate"] end end test 'works for any non navigational format' do - swap Devise, :navigational_formats => [] do - call_failure('formats' => Mime::HTML) + swap Devise, navigational_formats: [] do + call_failure('formats' => Mime[:html]) assert_equal 401, @response.first end end test 'uses the failure message as response body' do - call_failure('formats' => Mime::XML, 'warden' => OpenStruct.new(:message => :invalid)) + call_failure('formats' => Mime[:xml], 'warden' => OpenStruct.new(message: :invalid)) 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 context 'when http_authenticatable_on_xhr is false' do test 'dont return 401 with navigational formats' do - swap Devise, :http_authenticatable_on_xhr => false do - call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') + swap Devise, http_authenticatable_on_xhr: false do + call_failure('formats' => Mime[:html], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_equal 302, @response.first assert_equal 'http://test.host/users/sign_in', @response.second["Location"] end end test 'dont return 401 with non navigational formats' do - swap Devise, :http_authenticatable_on_xhr => false do - call_failure('formats' => Mime::JSON, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') + swap Devise, http_authenticatable_on_xhr: false do + call_failure('formats' => Mime[:json], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_equal 302, @response.first assert_equal 'http://test.host/users/sign_in.json', @response.second["Location"] end @@ -168,15 +328,15 @@ def call_failure(env_params={}) context 'when http_authenticatable_on_xhr is true' do test 'return 401' do - swap Devise, :http_authenticatable_on_xhr => true do - call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') + swap Devise, http_authenticatable_on_xhr: true do + call_failure('formats' => Mime[:html], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_equal 401, @response.first end end test 'skip WWW-Authenticate header' do - swap Devise, :http_authenticatable_on_xhr => true do - call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') + swap Devise, http_authenticatable_on_xhr: true do + call_failure('formats' => Mime[:html], 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_nil @response.second['WWW-Authenticate'] end end @@ -187,35 +347,131 @@ def call_failure(env_params={}) context 'With recall' do test 'calls the original controller if invalid email or password' do env = { - "warden.options" => { :recall => "devise/sessions#new", :attempted_path => "/users/sign_in" }, + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" }, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Sign 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 env = { - "warden.options" => { :recall => "devise/sessions#new", :attempted_path => "/users/sign_in", :message => :unconfirmed }, + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :unconfirmed }, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Sign in

') - assert @response.third.body.include?('You have to confirm your account 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 env = { - "warden.options" => { :recall => "devise/sessions#new", :attempted_path => "/users/sign_in", :message => :inactive }, + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :inactive }, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) - assert @response.third.body.include?('

Sign in

') - assert @response.third.body.include?('Your account was 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) + test 'calls the original controller with the proper environment considering the relative url root' do + swap Rails.application.config, relative_url_root: "/sample" do + env = { + "warden.options" => { recall: "devise/sessions#new", attempted_path: "/sample/users/sign_in"}, + "devise.mapping" => Devise.mappings[:user], + "warden" => stub_everything + } + call_failure(env) + 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 7bf11db871..1c7d8219f4 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 @@ -10,10 +12,24 @@ class ActiveRecordGeneratorTest < Rails::Generators::TestCase test "all files are properly created with rails31 migration syntax" do run_generator %w(monster) - assert_file "app/models/monster.rb", /devise/, /attr_accessible (:[a-z_]+(, )?)+/ 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/ + end + test "update model migration when model exists" do run_generator %w(monster) assert_file "app/models/monster.rb" @@ -21,18 +37,47 @@ 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) assert_migration "db/migrate/devise_create_monsters.rb" assert_migration "db/migrate/add_devise_to_monsters.rb" - run_generator %w(monster), :behavior => :revoke + run_generator %w(monster), behavior: :revoke assert_no_migration "db/migrate/add_devise_to_monsters.rb" assert_migration "db/migrate/devise_create_monsters.rb" - run_generator %w(monster), :behavior => :revoke + run_generator %w(monster), behavior: :revoke assert_no_file "app/models/monster.rb" assert_no_migration "db/migrate/devise_create_monsters.rb" end + + test "use string column type for ip addresses" do + run_generator %w(monster) + 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 @@ -43,11 +88,11 @@ class Engine < Rails::Engine def simulate_inside_engine(engine, namespace) if Rails::Generators.respond_to?(:namespace=) - swap Rails::Generators, :namespace => namespace do + swap Rails::Generators, namespace: namespace do yield end else - swap Rails, :application => engine.instance do + swap Rails, application: engine.instance do yield end end @@ -58,12 +103,16 @@ class ActiveRecordEngineGeneratorTest < Rails::Generators::TestCase destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination - test "all files are properly created" do + test "all files are properly created in rails 4.0" do simulate_inside_engine(RailsEngine::Engine, RailsEngine) do run_generator ["monster"] - assert_file "app/models/rails_engine/monster.rb", /devise/,/attr_accessible (:[a-z_]+(, )?)+/ + assert_file "app/models/rails_engine/monster.rb", /devise/ + assert_file "app/models/rails_engine/monster.rb" do |content| + assert_no_match %r{attr_accessible :email}, content + end end end + end -end \ No newline at end of file +end diff --git a/test/generators/controllers_generator_test.rb b/test/generators/controllers_generator_test.rb new file mode 100644 index 0000000000..01bf970ec3 --- /dev/null +++ b/test/generators/controllers_generator_test.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +require "test_helper" + +class ControllersGeneratorTest < Rails::Generators::TestCase + tests Devise::Generators::ControllersGenerator + destination File.expand_path("../../tmp", __FILE__) + setup :prepare_destination + + test "Assert no controllers are created with no params" do + capture(:stderr) { run_generator } + assert_no_file "app/controllers/sessions_controller.rb" + assert_no_file "app/controllers/registrations_controller.rb" + assert_no_file "app/controllers/confirmations_controller.rb" + assert_no_file "app/controllers/passwords_controller.rb" + assert_no_file "app/controllers/unlocks_controller.rb" + assert_no_file "app/controllers/omniauth_callbacks_controller.rb" + end + + test "Assert all controllers are properly created with scope param" do + run_generator %w(users) + assert_class_names 'users' + + run_generator %w(admins) + assert_class_names 'admins' + end + + test "Assert specified controllers with scope" do + run_generator %w(users -c sessions) + assert_file "app/controllers/users/sessions_controller.rb" + assert_no_file "app/controllers/users/registrations_controller.rb" + assert_no_file "app/controllers/users/confirmations_controller.rb" + assert_no_file "app/controllers/users/passwords_controller.rb" + assert_no_file "app/controllers/users/unlocks_controller.rb" + assert_no_file "app/controllers/users/omniauth_callbacks_controller.rb" + end + + private + + def assert_class_names(scope, options = {}) + base_dir = "app/controllers#{scope.blank? ? '' : ('/' + scope)}" + scope_prefix = scope.blank? ? '' : (scope.camelize + '::') + controllers = options[:controllers] || + %w(confirmations passwords registrations sessions unlocks omniauth_callbacks) + + controllers.each do |c| + assert_file "#{base_dir}/#{c}_controller.rb", /#{scope_prefix + c.camelize}/ + end + end +end diff --git a/test/generators/devise_generator_test.rb b/test/generators/devise_generator_test.rb index 292e0ab2fe..22112c69c5 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" @@ -18,13 +20,13 @@ class DeviseGeneratorTest < Rails::Generators::TestCase test "route generation for namespaced model names" do run_generator %w(monster/goblin name:string) - match = /devise_for :goblins, :class_name => "Monster::Goblin"/ + match = /devise_for :goblins, class_name: "Monster::Goblin"/ assert_file "config/routes.rb", match end test "route generation with skip routes" do run_generator %w(monster name:string --skip-routes) - match = /devise_for :monsters, :skip => :all/ + match = /devise_for :monsters, skip: :all/ assert_file "config/routes.rb", match end @@ -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 db63e23a44..3bb1b00f5c 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 @@ -5,9 +7,28 @@ class InstallGeneratorTest < Rails::Generators::TestCase destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination - test "Assert all files are properly created" do - run_generator - assert_file "config/initializers/devise.rb" + test "assert all files are properly created" do + run_generator(["--orm=active_record"]) + assert_file "config/initializers/devise.rb", /devise\/orm\/active_record/ assert_file "config/locales/devise.en.yml" end + + test "fails if no ORM is specified" do + stderr = capture(:stderr) do + run_generator + end + + assert_match %r{An ORM must be set to install Devise}, stderr + + 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 2302956857..ea20b4cadf 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 @@ -7,15 +9,15 @@ class MongoidGeneratorTest < Rails::Generators::TestCase tests Mongoid::Generators::DeviseGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination - + test "all files are properly created" do run_generator %w(monster) assert_file "app/models/monster.rb", /devise/ end - + test "all files are properly deleted" do run_generator %w(monster) - run_generator %w(monster), :behavior => :revoke + run_generator %w(monster), behavior: :revoke assert_no_file "app/models/monster.rb" end end diff --git a/test/generators/views_generator_test.rb b/test/generators/views_generator_test.rb index 958bae6224..1f8f90f3ca 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 @@ -8,14 +10,20 @@ class ViewsGeneratorTest < Rails::Generators::TestCase test "Assert all views are properly created with no params" do run_generator assert_files + assert_shared_links + assert_error_messages end - test "Assert all views are properly created with scope param param" do + 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 @@ -30,10 +38,46 @@ class ViewsGeneratorTest < Rails::Generators::TestCase test "Assert views with markerb" do run_generator %w(--markerb) - assert_files nil, :mail_template_engine => "markerb" + assert_files nil, mail_template_engine: "markerb" + end + + + test "Assert only views within specified directories" do + run_generator %w(-v sessions registrations) + assert_file "app/views/devise/sessions/new.html.erb" + assert_file "app/views/devise/registrations/new.html.erb" + assert_file "app/views/devise/registrations/edit.html.erb" + assert_no_file "app/views/devise/confirmations/new.html.erb" + assert_no_file "app/views/devise/mailer/confirmation_instructions.html.erb" + end + + test "Assert mailer specific directory with simple form" do + run_generator %w(-v mailer -b simple_form_for) + assert_file "app/views/devise/mailer/confirmation_instructions.html.erb" + assert_file "app/views/devise/mailer/reset_password_instructions.html.erb" + assert_file "app/views/devise/mailer/unlock_instructions.html.erb" + end + + test "Assert specified directories with scope" do + run_generator %w(users -v sessions) + assert_file "app/views/users/sessions/new.html.erb" + assert_no_file "app/views/users/confirmations/new.html.erb" end - def assert_files(scope = nil, options={}) + test "Assert specified directories with simple form" do + run_generator %w(-v registrations -b simple_form_for) + assert_file "app/views/devise/registrations/new.html.erb", /simple_form_for/ + assert_no_file "app/views/devise/confirmations/new.html.erb" + end + + test "Assert specified directories with markerb" do + run_generator %w(--markerb -v passwords mailer) + assert_file "app/views/devise/passwords/new.html.erb" + assert_no_file "app/views/devise/confirmations/new.html.erb" + assert_file "app/views/devise/mailer/reset_password_instructions.markerb" + end + + def assert_files(scope = nil, options = {}) scope = "devise" if scope.nil? mail_template_engine = options[:mail_template_engine] || "html.erb" @@ -46,7 +90,32 @@ def assert_files(scope = nil, options={}) assert_file "app/views/#{scope}/registrations/new.html.erb" 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.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 + + def assert_shared_links(scope = nil) + scope = "devise" if scope.nil? + link = /<%= render \"#{scope}\/shared\/links\" %>/ + + 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}/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 61ad1f7bf0..b9fac7da37 100644 --- a/test/helpers/devise_helper_test.rb +++ b/test/helpers/devise_helper_test.rb @@ -1,51 +1,47 @@ +# frozen_string_literal: true + require 'test_helper' -class DeviseHelperTest < ActionController::IntegrationTest +class DeviseHelperTest < Devise::IntegrationTest setup do - model_labels = { :models => { :user => "utilisateur" } } - - I18n.backend.store_translations :fr, - { - :errors => { :messages => { :not_saved => { - :one => "Erreur lors de l'enregistrement de '%{resource}': 1 erreur.", - :other => "Erreur lors de l'enregistrement de '%{resource}': %{count} erreurs." + model_labels = { models: { user: "the user" } } + translations = { + errors: { messages: { not_saved: { + one: "Can't save %{resource} because of 1 error", + other: "Can't save %{resource} because of %{count} errors", } } }, - :activerecord => model_labels, - :mongoid => model_labels + activerecord: model_labels, + mongoid: model_labels } - I18n.locale = 'fr' + I18n.available_locales + I18n.backend.store_translations(:en, translations) end teardown do - I18n.locale = 'en' + I18n.reload! end test 'test errors.messages.not_saved with single error from i18n' do get new_user_registration_path - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user123' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_have_selector '#error_explanation' - assert_contain "Erreur lors de l'enregistrement de 'utilisateur': 1 erreur" + assert_contain "Can't save the user because of 1 error" 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' - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user321' + fill_in 'email', with: 'invalid_email' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user321' click_button 'Sign up' assert_have_selector '#error_explanation' - assert_contain "Erreur lors de l'enregistrement de 'utilisateur': 2 erreurs" + assert_contain "Can't save the user because of 2 errors" end end - diff --git a/test/indifferent_hash.rb b/test/indifferent_hash.rb deleted file mode 100644 index 43dd752927..0000000000 --- a/test/indifferent_hash.rb +++ /dev/null @@ -1,33 +0,0 @@ -require 'test_helper' - -class IndifferentHashTest < ActiveSupport::TestCase - setup do - @hash = Devise::IndifferentHash.new - end - - test "it overwrites getter and setter" do - @hash[:foo] = "bar" - assert_equal "bar", @hash["foo"] - assert_equal "bar", @hash[:foo] - - @hash["foo"] = "baz" - assert_equal "baz", @hash["foo"] - assert_equal "baz", @hash[:foo] - end - - test "it overwrites update" do - @hash.update :foo => "bar" - assert_equal "bar", @hash["foo"] - assert_equal "bar", @hash[:foo] - - @hash.update "foo" => "baz" - assert_equal "baz", @hash["foo"] - assert_equal "baz", @hash[:foo] - end - - test "it returns a Hash on to_hash" do - @hash[:foo] = "bar" - assert_equal Hash["foo", "bar"], @hash.to_hash - assert_kind_of Hash, @hash.to_hash - end -end if defined?(Devise::IndifferentHash) \ No newline at end of file diff --git a/test/integration/authenticatable_test.rb b/test/integration/authenticatable_test.rb index b2ee55b162..28d00399bb 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 < ActionController::IntegrationTest +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 @@ -27,43 +35,43 @@ class AuthenticationSanityTest < ActionController::IntegrationTest end test 'sign out as user should not touch admin authentication if sign_out_all_scopes is false' do - swap Devise, :sign_out_all_scopes => false do + swap Devise, sign_out_all_scopes: false do sign_in_as_user sign_in_as_admin - get destroy_user_session_path + delete destroy_user_session_path assert_not warden.authenticated?(:user) assert warden.authenticated?(:admin) end end test 'sign out as admin should not touch user authentication if sign_out_all_scopes is false' do - swap Devise, :sign_out_all_scopes => false do + swap Devise, sign_out_all_scopes: false do sign_in_as_user sign_in_as_admin - get destroy_admin_session_path + delete destroy_admin_session_path assert_not warden.authenticated?(:admin) assert warden.authenticated?(:user) end end test 'sign out as user should also sign out admin if sign_out_all_scopes is true' do - swap Devise, :sign_out_all_scopes => true do + swap Devise, sign_out_all_scopes: true do sign_in_as_user sign_in_as_admin - get destroy_user_session_path + delete destroy_user_session_path assert_not warden.authenticated?(:user) assert_not warden.authenticated?(:admin) end end test 'sign out as admin should also sign out user if sign_out_all_scopes is true' do - swap Devise, :sign_out_all_scopes => true do + swap Devise, sign_out_all_scopes: true do sign_in_as_user sign_in_as_admin - get destroy_admin_session_path + delete destroy_admin_session_path assert_not warden.authenticated?(:admin) assert_not warden.authenticated?(:user) end @@ -109,7 +117,7 @@ class AuthenticationSanityTest < ActionController::IntegrationTest sign_in_as_admin assert warden.authenticated?(:admin) - get destroy_admin_session_path + delete destroy_admin_session_path assert_response :redirect assert_redirected_to root_path @@ -118,13 +126,13 @@ class AuthenticationSanityTest < ActionController::IntegrationTest assert_not warden.authenticated?(:admin) end - test 'unauthenticated admin does not set message on sign out' do - get destroy_admin_session_path + test 'unauthenticated admin set message on sign out' do + delete destroy_admin_session_path assert_response :redirect assert_redirected_to root_path get root_path - assert_not_contain 'Signed out successfully' + assert_contain 'Signed out successfully' end test 'scope uses custom failure app' do @@ -134,7 +142,7 @@ class AuthenticationSanityTest < ActionController::IntegrationTest end end -class AuthenticationRoutesRestrictions < ActionController::IntegrationTest +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 @@ -162,7 +170,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest end 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) + sign_in_as_admin(active: false) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) @@ -172,7 +180,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest end 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) + sign_in_as_admin(active: true) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) @@ -191,7 +199,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest get dashboard_path assert_response :success - assert_template 'home/admin' + assert_template 'home/admin_dashboard' assert_contain 'Admin dashboard' end @@ -203,7 +211,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest get dashboard_path assert_response :success - assert_template 'home/user' + assert_template 'home/user_dashboard' assert_contain 'User dashboard' end @@ -214,7 +222,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest end 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) + sign_in_as_admin(active: false) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) @@ -224,7 +232,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest end 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) + sign_in_as_admin(active: true) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) @@ -245,7 +253,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest end end - test 'not signed in users should see unautheticated page (unauthenticated accepted)' do + test 'not signed in users should see unauthenticated page (unauthenticated accepted)' do get join_path assert_response :success @@ -254,7 +262,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest end end -class AuthenticationRedirectTest < ActionController::IntegrationTest +class AuthenticationRedirectTest < Devise::IntegrationTest test 'redirect from warden shows sign in or sign up message' do get admins_path @@ -265,6 +273,15 @@ class AuthenticationRedirectTest < ActionController::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' @@ -277,7 +294,7 @@ class AuthenticationRedirectTest < ActionController::IntegrationTest assert_equal users_path, session[:"user_return_to"] follow_redirect! - sign_in_as_user :visit => false + sign_in_as_user visit: false assert_current_url '/users' assert_nil session[:"user_return_to"] @@ -293,14 +310,14 @@ class AuthenticationRedirectTest < ActionController::IntegrationTest assert_equal users_path, session[:"user_return_to"] follow_redirect! - sign_in_as_user :visit => false + sign_in_as_user visit: false assert_current_url '/users' assert_nil session[:"user_return_to"] end test 'xml http requests does not store urls for redirect' do - get users_path, {}, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' + get users_path, headers: { 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' } assert_equal 401, response.status assert_nil session[:"user_return_to"] end @@ -313,11 +330,19 @@ class AuthenticationRedirectTest < ActionController::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 -class AuthenticationSessionTest < ActionController::IntegrationTest +class AuthenticationSessionTest < Devise::IntegrationTest test 'destroyed account is signed out' do sign_in_as_user get '/users' @@ -327,31 +352,30 @@ class AuthenticationSessionTest < ActionController::IntegrationTest assert_redirected_to new_user_session_path end - test 'allows session to be set for a given scope' do - sign_in_as_user - get '/users' - assert_equal "Cart", @controller.user_session[:cart] - end + test 'refreshes _csrf_token' do + swap ApplicationController, allow_forgery_protection: true do + get new_user_session_path + token_from_session = request.session[:_csrf_token] - test 'does not explode when invalid user class is stored in session' do - klass = User - paths = ActiveSupport::Dependencies.autoload_paths.dup + if Devise::Test.rails71_and_up? + token_from_env = request.env["action_controller.csrf_token"] + end - begin sign_in_as_user - assert warden.authenticated?(:user) + assert_not_equal request.session[:_csrf_token], token_from_session - Object.send :remove_const, :User - ActiveSupport::Dependencies.autoload_paths.clear - - visit "/users" - assert_not warden.authenticated?(:user) - ensure - Object.const_set(:User, klass) - ActiveSupport::Dependencies.autoload_paths.replace(paths) + if Devise::Test.rails71_and_up? + assert_not_equal request.env["action_controller.csrf_token"], token_from_env + end end end + test 'allows session to be set for a given scope' do + sign_in_as_user + get '/users' + assert_equal "Cart", @controller.user_session[:cart] + end + test 'session id is changed on sign in' do get '/users' session_id = request.session["session_id"] @@ -364,32 +388,32 @@ class AuthenticationSessionTest < ActionController::IntegrationTest end end -class AuthenticationWithScopedViewsTest < ActionController::IntegrationTest +class AuthenticationWithScopedViewsTest < Devise::IntegrationTest test 'renders the scoped view if turned on and view is available' do - swap Devise, :scoped_views => true do + swap Devise, scoped_views: true do assert_raise Webrat::NotFoundError do sign_in_as_user end - assert_match /Special user view/, response.body + assert_match %r{Special user view}, response.body 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 sign_in_as_user end - assert_match /Special user view/, response.body - assert !Devise::PasswordsController.scoped_views? + assert_match %r{Special user view}, response.body + assert_not Devise::PasswordsController.scoped_views? ensure Devise::SessionsController.send :remove_instance_variable, :@scoped_views end end test 'does not render the scoped view if turned off' do - swap Devise, :scoped_views => false do + swap Devise, scoped_views: false do assert_nothing_raised do sign_in_as_user end @@ -397,7 +421,7 @@ class AuthenticationWithScopedViewsTest < ActionController::IntegrationTest end test 'does not render the scoped view if not available' do - swap Devise, :scoped_views => true do + swap Devise, scoped_views: true do assert_nothing_raised do sign_in_as_admin end @@ -405,9 +429,9 @@ class AuthenticationWithScopedViewsTest < ActionController::IntegrationTest end end -class AuthenticationOthersTest < ActionController::IntegrationTest +class AuthenticationOthersTest < Devise::IntegrationTest test 'handles unverified requests gets rid of caches' do - swap UsersController, :allow_forgery_protection => true do + swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) assert_not warden.authenticated?(:user) @@ -422,7 +446,7 @@ class AuthenticationOthersTest < ActionController::IntegrationTest test 'uses the custom controller with the custom controller view' do get '/admin_area/sign_in' - assert_contain 'Sign in' + assert_contain 'Log in' assert_contain 'Welcome to "admins/sessions" controller!' assert_contain 'Welcome to "sessions/new" view!' end @@ -446,29 +470,21 @@ class AuthenticationOthersTest < ActionController::IntegrationTest test 'sign in with script name' do assert_nothing_raised do - get new_user_session_path, {}, "SCRIPT_NAME" => "/omg" - fill_in "email", :with => "user@test.com" + get new_user_session_path, headers: { "SCRIPT_NAME" => "/omg" } + fill_in "email", with: "user@test.com" end end - test 'sign in stub in xml format' do - get new_user_session_path(:format => 'xml') - assert_match '', response.body - assert_match /.*<\/user>/m, response.body - assert_match '', response.body - assert_match '', response.body - end - test 'sign in stub in json format' do - get new_user_session_path(:format => 'json') + get new_user_session_path(format: 'json') assert_match '{"user":{', response.body assert_match '"email":""', response.body assert_match '"password":null', response.body end test 'sign in stub in json with non attribute key' do - swap Devise, :authentication_keys => [:other_key] do - get new_user_session_path(:format => 'json') + swap Devise, authentication_keys: [:other_key] do + get new_user_session_path(format: 'json') assert_match '{"user":{', response.body assert_match '"other_key":null', response.body assert_match '"password":null', response.body @@ -476,79 +492,103 @@ class AuthenticationOthersTest < ActionController::IntegrationTest end test 'uses the mapping from router' do - sign_in_as_user :visit => "/as/sign_in" + sign_in_as_user visit: "/as/sign_in" assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) end - test 'sign in with xml format returns xml response' do + test 'sign in with json format returns json response' do create_user - post user_session_path(:format => 'xml'), :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 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'), :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'), :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 xml format returns ok response' do + test 'sign out with html redirects' do sign_in_as_user - get destroy_user_session_path(:format => 'xml') - assert_response :no_content - assert_not warden.authenticated?(:user) + delete destroy_user_session_path + assert_response :redirect + assert_current_url '/' + + sign_in_as_user + delete destroy_user_session_path(format: 'html') + assert_response :redirect + assert_current_url '/' end - test 'sign out with json format returns empty json response' do + test 'sign out with json format returns no content' do sign_in_as_user - get destroy_user_session_path(:format => 'json') + delete destroy_user_session_path(format: 'json') assert_response :no_content assert_not warden.authenticated?(:user) end + + test 'sign out with non-navigational format via XHR does not redirect' do + swap Devise, navigational_formats: ['*/*', :html] do + 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 + assert_not warden.authenticated?(:user) + end + end + + # Belt and braces ... Perhaps this test is not necessary? + test 'sign out with navigational format via XHR does redirect' do + swap Devise, navigational_formats: ['*/*', :html] do + sign_in_as_user + delete destroy_user_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "text/html,*/*" } + assert_response :redirect + assert_not warden.authenticated?(:user) + end + end end -class AuthenticationKeysTest < ActionController::IntegrationTest +class AuthenticationKeysTest < Devise::IntegrationTest test 'missing authentication keys cause authentication to abort' do - swap Devise, :authentication_keys => [:subdomain] do + swap Devise, authentication_keys: [:subdomain] do sign_in_as_user - assert_contain "Invalid email or password." + assert_contain "Invalid subdomain or password." assert_not warden.authenticated?(:user) end end test 'missing authentication keys cause authentication to abort unless marked as not required' do - swap Devise, :authentication_keys => { :email => true, :subdomain => false } do + swap Devise, authentication_keys: { email: true, subdomain: false } do sign_in_as_user assert warden.authenticated?(:user) end end end -class AuthenticationRequestKeysTest < ActionController::IntegrationTest +class AuthenticationRequestKeysTest < Devise::IntegrationTest test 'request keys are used on authentication' do 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) + swap Devise, request_keys: [:subdomain] do + User.expects(:find_for_authentication).with({ subdomain: 'foo', email: 'user@test.com' }).returns(create_user) sign_in_as_user assert warden.authenticated?(:user) end end test 'invalid request keys raises NoMethodError' do - swap Devise, :request_keys => [:unknown_method] do + swap Devise, request_keys: [:unknown_method] do assert_raise NoMethodError do sign_in_as_user end @@ -560,7 +600,7 @@ class AuthenticationRequestKeysTest < ActionController::IntegrationTest test 'blank request keys cause authentication to abort' do host! 'test.com' - swap Devise, :request_keys => [:subdomain] do + swap Devise, request_keys: [:subdomain] do sign_in_as_user assert_contain "Invalid email or password." assert_not warden.authenticated?(:user) @@ -570,16 +610,16 @@ class AuthenticationRequestKeysTest < ActionController::IntegrationTest test 'blank request keys cause authentication to abort unless if marked as not required' do host! 'test.com' - swap Devise, :request_keys => { :subdomain => false } do + swap Devise, request_keys: { subdomain: false } do sign_in_as_user assert warden.authenticated?(:user) end end end -class AuthenticationSignOutViaTest < ActionController::IntegrationTest +class AuthenticationSignOutViaTest < Devise::IntegrationTest def sign_in!(scope) - sign_in_as_admin(:visit => send("new_#{scope}_session_path")) + sign_in_as_admin(visit: send("new_#{scope}_session_path")) assert warden.authenticated?(scope) end @@ -631,3 +671,42 @@ def sign_in!(scope) assert warden.authenticated?(:sign_out_via_delete_or_post) end end + +class DoubleAuthenticationRedirectTest < Devise::IntegrationTest + test 'signed in as user redirects when visiting user sign in page' do + sign_in_as_user + get new_user_session_path(format: :html) + assert_redirected_to '/' + end + + test 'signed in as admin redirects when visiting admin sign in page' do + sign_in_as_admin + get new_admin_session_path(format: :html) + assert_redirected_to '/admin_area/home' + end + + test 'signed in as both user and admin redirects when visiting admin sign in page' do + sign_in_as_user + sign_in_as_admin + get new_user_session_path(format: :html) + assert_redirected_to '/' + get new_admin_session_path(format: :html) + assert_redirected_to '/admin_area/home' + end +end + +class DoubleSignOutRedirectTest < Devise::IntegrationTest + test 'sign out after already having signed out redirects to sign in' do + sign_in_as_user + + post destroy_sign_out_via_delete_or_post_session_path + + get root_path + assert_contain 'Signed out successfully.' + + post destroy_sign_out_via_delete_or_post_session_path + + get root_path + assert_contain 'Signed out successfully.' + end +end diff --git a/test/integration/confirmable_test.rb b/test/integration/confirmable_test.rb index 9acd99eae3..8e6f68ef2d 100644 --- a/test/integration/confirmable_test.rb +++ b/test/integration/confirmable_test.rb @@ -1,19 +1,21 @@ +# frozen_string_literal: true + require 'test_helper' -class ConfirmationTest < ActionController::IntegrationTest +class ConfirmationTest < Devise::IntegrationTest def visit_user_confirmation_with_token(confirmation_token) - visit user_confirmation_path(:confirmation_token => confirmation_token) + visit user_confirmation_path(confirmation_token: confirmation_token) end def resend_confirmation - user = create_user(:confirm => false) + user = create_user(confirm: false) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive confirmation instructions?" - fill_in 'email', :with => user.email + fill_in 'email', with: user.email click_button 'Resend confirmation instructions' end @@ -21,55 +23,74 @@ def resend_confirmation resend_confirmation assert_current_url '/users/sign_in' - assert_contain 'You will receive an email with instructions about how to confirm your account in a few minutes' + assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes' assert_equal 1, ActionMailer::Base.deliveries.size assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from end test 'user should receive a confirmation from a custom mailer' do User.any_instance.stubs(:devise_mailer).returns(Users::Mailer) - resend_confirmation - assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from end test 'user with invalid confirmation token should not be able to confirm an account' do visit_user_confirmation_with_token('invalid_confirmation') assert_have_selector '#error_explanation' - assert_contain /Confirmation token(.*)invalid/ - end - - test 'user with valid confirmation token should be able to confirm an account' do - user = create_user(:confirm => false) - assert_not user.confirmed? - visit_user_confirmation_with_token(user.confirmation_token) - - assert_contain 'Your account was successfully confirmed.' - assert_current_url '/' - assert user.reload.confirmed? + assert_contain %r{Confirmation token(.*)invalid} end 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) + swap Devise, confirm_within: 3.days do + user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) assert_not user.confirmed? - visit_user_confirmation_with_token(user.confirmation_token) + visit_user_confirmation_with_token(user.raw_confirmation_token) assert_have_selector '#error_explanation' - assert_contain /needs to be confirmed within 3 days/ + assert_contain %r{needs to be confirmed within 3 days} assert_not user.reload.confirmed? + assert_current_url "/users/confirmation?confirmation_token=#{user.raw_confirmation_token}" + end + end + + test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine it should raise an error' do + user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) + + swap Devise, confirm_within: 3.days, router_name: :fake_engine do + assert_raise ActionView::Template::Error do + visit_user_confirmation_with_token(user.raw_confirmation_token) + end + end + end + + test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine and route overrides back to main it shows the path' do + user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) + + swap Devise, confirm_within: 3.days, router_name: :fake_engine do + visit user_on_main_app_confirmation_path(confirmation_token: user.raw_confirmation_token) + + assert_current_url "/user_on_main_apps/confirmation?confirmation_token=#{user.raw_confirmation_token}" + end + end + + test 'user with valid confirmation token where the token has expired with router overrides different engine it shows the path' do + user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) + + swap Devise, confirm_within: 3.days do + visit user_on_engine_confirmation_path(confirmation_token: user.raw_confirmation_token) + + assert_current_url "/user_on_engines/confirmation?confirmation_token=#{user.raw_confirmation_token}" end end 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) + swap Devise, confirm_within: 3.days do + user = create_user(confirm: false, confirmation_sent_at: 2.days.ago) assert_not user.confirmed? - visit_user_confirmation_with_token(user.confirmation_token) + visit_user_confirmation_with_token(user.raw_confirmation_token) - assert_contain 'Your account was successfully confirmed.' - assert_current_url '/' + assert_contain 'Your email address has been successfully confirmed.' + assert_current_url '/users/sign_in' assert user.reload.confirmed? end end @@ -77,63 +98,57 @@ def resend_confirmation test 'user should be redirected to a custom path after confirmation' do Devise::ConfirmationsController.any_instance.stubs(:after_confirmation_path_for).returns("/?custom=1") - user = create_user(:confirm => false) - visit_user_confirmation_with_token(user.confirmation_token) + user = create_user(confirm: false) + visit_user_confirmation_with_token(user.raw_confirmation_token) assert_current_url "/?custom=1" end test 'already confirmed user should not be able to confirm the account again' do - user = create_user(:confirm => false) + user = create_user(confirm: false) user.confirmed_at = Time.now user.save - visit_user_confirmation_with_token(user.confirmation_token) + visit_user_confirmation_with_token(user.raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain 'already confirmed' end test 'already confirmed user should not be able to confirm the account again neither request confirmation' do - user = create_user(:confirm => false) + user = create_user(confirm: false) user.confirmed_at = Time.now user.save - visit_user_confirmation_with_token(user.confirmation_token) + visit_user_confirmation_with_token(user.raw_confirmation_token) assert_contain 'already confirmed' - fill_in 'email', :with => user.email + fill_in 'email', with: user.email click_button 'Resend confirmation instructions' assert_contain 'already confirmed' end - test 'sign in user automatically after confirming its email' do - user = create_user(:confirm => false) - visit_user_confirmation_with_token(user.confirmation_token) - - assert warden.authenticated?(:user) - end - - test 'increases sign count when signed in through confirmation' do - user = create_user(:confirm => false) - visit_user_confirmation_with_token(user.confirmation_token) + test 'not confirmed user with setup to block without confirmation should not be able to sign in' do + swap Devise, allow_unconfirmed_access_for: 0.days do + sign_in_as_user(confirm: false) - user.reload - assert_equal 1, user.sign_in_count + assert_contain 'You have to confirm your email address before continuing' + assert_not warden.authenticated?(:user) + end end - test 'not confirmed user with setup to block without confirmation should not be able to sign in' do - swap Devise, :allow_unconfirmed_access_for => 0.days do - sign_in_as_user(:confirm => false) + 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 'You have to confirm your account before continuing' + assert_contain 'Você precisa confirmar seu email para continuar' assert_not warden.authenticated?(:user) end end test 'not confirmed user should not see confirmation message if invalid credentials are given' do - swap Devise, :allow_unconfirmed_access_for => 0.days do - sign_in_as_user(:confirm => false) do - fill_in 'password', :with => 'invalid' + swap Devise, allow_unconfirmed_access_for: 0.days do + sign_in_as_user(confirm: false) do + fill_in 'password', with: 'invalid' end assert_contain 'Invalid email or password' @@ -142,157 +157,201 @@ def resend_confirmation end test 'not confirmed user but configured with some days to confirm should be able to sign in' do - swap Devise, :allow_unconfirmed_access_for => 1.day do - sign_in_as_user(:confirm => false) + swap Devise, allow_unconfirmed_access_for: 1.day do + sign_in_as_user(confirm: false) assert_response :success assert warden.authenticated?(:user) end end + test 'unconfirmed but signed in user should be redirected to their root path' do + swap Devise, allow_unconfirmed_access_for: 1.day do + user = sign_in_as_user(confirm: false) + + visit_user_confirmation_with_token(user.raw_confirmation_token) + assert_contain 'Your email address has been successfully confirmed.' + assert_current_url '/' + end + end + + test 'user should be redirected to sign in page whenever signed in as another resource at same session already' do + sign_in_as_admin + + user = create_user(confirm: false) + visit_user_confirmation_with_token(user.raw_confirmation_token) + + 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" } } + store_translations :en, devise: { + failure: { user: { unconfirmed: "Not confirmed user" } } } do - sign_in_as_user(:confirm => false) + sign_in_as_user(confirm: false) assert_contain 'Not confirmed user' end end - test 'resent confirmation token with valid E-Mail in XML format should return valid response' do - user = create_user(:confirm => false) - post user_confirmation_path(:format => 'xml'), :user => { :email => user.email } + 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: '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 - user = create_user(:confirm => false) - post user_confirmation_path(:format => 'xml'), :user => { :email => 'invalid.test@test.com' } + 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: '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 - user = create_user(:confirm => false) - get user_confirmation_path(:confirmation_token => user.confirmation_token, :format => 'xml') + 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: '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 - user = create_user(:confirm => false) - get user_confirmation_path(:confirmation_token => 'invalid_confirmation', :format => 'xml') + 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: '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, :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 - swap Devise, :paranoid => true do - user = create_user(:confirm => false) + swap Devise, paranoid: true do + user = create_user(confirm: false) visit new_user_session_path click_link "Didn't receive confirmation instructions?" - fill_in 'email', :with => user.email + fill_in 'email', with: user.email click_button 'Resend confirmation instructions' - assert_contain "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes." + assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." assert_current_url "/users/sign_in" end end test "when in paranoid mode and with a invalid e-mail, should not say that the e-mail is invalid" do - swap Devise, :paranoid => true do + swap Devise, paranoid: true do visit new_user_session_path click_link "Didn't receive confirmation instructions?" - fill_in 'email', :with => "idonthavethisemail@gmail.com" + fill_in 'email', with: "idonthavethisemail@gmail.com" click_button 'Resend confirmation instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" - assert_contain "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes." + assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." assert_current_url "/users/sign_in" end end end -class ConfirmationOnChangeTest < ActionController::IntegrationTest - def create_second_admin(options={}) +class ConfirmationOnChangeTest < Devise::IntegrationTest + def create_second_admin(options = {}) @admin = nil create_admin(options) end def visit_admin_confirmation_with_token(confirmation_token) - visit admin_confirmation_path(:confirmation_token => confirmation_token) + visit admin_confirmation_path(confirmation_token: confirmation_token) end 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?" - fill_in 'email', :with => admin.unconfirmed_email + fill_in 'email', with: admin.unconfirmed_email assert_difference "ActionMailer::Base.deliveries.size" do click_button 'Resend confirmation instructions' end assert_current_url '/admin_area/sign_in' - assert_contain 'You will receive an email with instructions about how to confirm your account in a few minutes' + assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes' end 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.confirmation_token) + visit_admin_confirmation_with_token(admin.raw_confirmation_token) - assert_contain 'Your account was successfully confirmed.' - assert_current_url '/admin_area/home' + assert_contain 'Your email address has been successfully confirmed.' + assert_current_url '/admin_area/sign_in' assert admin.reload.confirmed? 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 - confirmation_token = admin.confirmation_token - admin.update_attributes(:email => 'second_test@example.com') + + raw_confirmation_token = admin.raw_confirmation_token + admin = Admin.find(admin.id) + + admin.update(email: 'second_test@example.com') assert_equal 'second_test@example.com', admin.unconfirmed_email - visit_admin_confirmation_with_token(confirmation_token) + visit_admin_confirmation_with_token(raw_confirmation_token) assert_have_selector '#error_explanation' - assert_contain /Confirmation token(.*)invalid/ + assert_contain(/Confirmation token(.*)invalid/) - visit_admin_confirmation_with_token(admin.confirmation_token) - assert_contain 'Your account was successfully confirmed.' - assert_current_url '/admin_area/home' + 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? 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") + create_second_admin(email: "new_admin_test@example.com") - visit_admin_confirmation_with_token(admin.confirmation_token) + visit_admin_confirmation_with_token(admin.raw_confirmation_token) assert_have_selector '#error_explanation' - assert_contain /Email.*already.*taken/ + assert_contain(/Email.*already.*taken/) assert admin.reload.pending_reconfirmation? end end diff --git a/test/integration/database_authenticatable_test.rb b/test/integration/database_authenticatable_test.rb index 51074d3ab6..08011fe288 100644 --- a/test/integration/database_authenticatable_test.rb +++ b/test/integration/database_authenticatable_test.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'test_helper' -class DatabaseAuthenticationTest < ActionController::IntegrationTest +class DatabaseAuthenticationTest < Devise::IntegrationTest test 'sign in with email of different case should succeed when email is in the list of case insensitive keys' do - create_user(:email => 'Foo@Bar.com') + create_user(email: 'Foo@Bar.com') sign_in_as_user do - fill_in 'email', :with => 'foo@bar.com' + fill_in 'email', with: 'foo@bar.com' end assert warden.authenticated?(:user) end test 'sign in with email of different case should fail when email is NOT the list of case insensitive keys' do - swap Devise, :case_insensitive_keys => [] do - create_user(:email => 'Foo@Bar.com') + swap Devise, case_insensitive_keys: [] do + create_user(email: 'Foo@Bar.com') sign_in_as_user do - fill_in 'email', :with => 'foo@bar.com' + fill_in 'email', with: 'foo@bar.com' end assert_not warden.authenticated?(:user) @@ -24,21 +26,21 @@ class DatabaseAuthenticationTest < ActionController::IntegrationTest end test 'sign in with email including extra spaces should succeed when email is in the list of strip whitespace keys' do - create_user(:email => ' foo@bar.com ') + create_user(email: ' foo@bar.com ') sign_in_as_user do - fill_in 'email', :with => 'foo@bar.com' + fill_in 'email', with: 'foo@bar.com' end assert warden.authenticated?(:user) end test 'sign in with email including extra spaces should fail when email is NOT the list of strip whitespace keys' do - swap Devise, :strip_whitespace_keys => [] do - create_user(:email => 'foo@bar.com') + swap Devise, strip_whitespace_keys: [] do + create_user(email: 'foo@bar.com') sign_in_as_user do - fill_in 'email', :with => ' foo@bar.com ' + fill_in 'email', with: ' foo@bar.com ' end assert_not warden.authenticated?(:user) @@ -46,37 +48,63 @@ class DatabaseAuthenticationTest < ActionController::IntegrationTest end test 'sign in should not authenticate if not using proper authentication keys' do - swap Devise, :authentication_keys => [:username] do + swap Devise, authentication_keys: [:username] do sign_in_as_user assert_not warden.authenticated?(:user) end end test 'sign in with invalid email should return to sign in form with error message' do - sign_in_as_admin do - fill_in 'email', :with => 'wrongemail@test.com' - end + store_translations :en, devise: { failure: { admin: { not_found_in_database: 'Invalid email address' } } } do + sign_in_as_admin do + fill_in 'email', with: 'wrongemail@test.com' + end - assert_contain 'Invalid email or password' - assert_not warden.authenticated?(:admin) + assert_contain 'Invalid email address' + 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' + fill_in 'password', with: 'abcdef' end 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 - store_translations :en, :devise => { :failure => { :admin => { :invalid => "Invalid credentials" } } } do + store_translations :en, devise: { failure: { admin: { invalid: "Invalid credentials" } } } do sign_in_as_admin do - fill_in 'password', :with => 'abcdef' + fill_in 'password', with: 'abcdef' end assert_contain 'Invalid credentials' end end + + test 'valid sign in calls after_database_authentication callback' do + user = create_user(email: ' foo@bar.com ') + + User.expects(:find_for_database_authentication).returns user + user.expects :after_database_authentication + + sign_in_as_user do + fill_in 'email', with: 'foo@bar.com' + end + end end diff --git a/test/integration/http_authenticatable_test.rb b/test/integration/http_authenticatable_test.rb index 1227c19c07..11e3733203 100644 --- a/test/integration/http_authenticatable_test.rb +++ b/test/integration/http_authenticatable_test.rb @@ -1,33 +1,43 @@ +# frozen_string_literal: true + require 'test_helper' -class HttpAuthenticationTest < ActionController::IntegrationTest +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 UsersController, :allow_forgery_protection => true do + swap ApplicationController, allow_forgery_protection: true do create_user - post exhibit_user_url(1), {}, "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("user@test.com:12345678")}" + post exhibit_user_url(1), headers: { "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("user@test.com:12345678")}" } assert warden.authenticated?(:user) assert_equal "User is authenticated", response.body end end test 'sign in should authenticate with http' do - sign_in_as_new_user_with_http - assert_response 200 - assert_match 'user@test.com', response.body - assert warden.authenticated?(:user) + swap Devise, skip_session_storage: [] do + sign_in_as_new_user_with_http + assert_response 200 + assert_match '"email":"user@test.com"', response.body + assert warden.authenticated?(:user) - get users_path(:format => :xml) - assert_response 200 + get users_path(format: :json) + assert_response 200 + end end test 'sign in should authenticate with http but not emit a cookie if skipping session storage' do - swap Devise, :skip_session_storage => [:http_auth] do + 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 @@ -41,12 +51,12 @@ class HttpAuthenticationTest < ActionController::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 - swap Devise, :http_authentication_realm => "MyApp" do + swap Devise, http_authentication_realm: "MyApp" do sign_in_as_new_user_with_http("unknown") assert_equal 401, status assert_equal 'Basic realm="MyApp"', headers["WWW-Authenticate"] @@ -54,44 +64,50 @@ class HttpAuthenticationTest < ActionController::IntegrationTest end test 'sign in should authenticate with http even with specific authentication keys' do - swap Devise, :authentication_keys => [:username] do + 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 + + test 'it uses appropriate authentication_keys when configured with hash' do + swap Devise, authentication_keys: { username: false, email: false } do + sign_in_as_new_user_with_http("usertest") + assert_response :success + assert_match '"email":"user@test.com"', response.body + assert warden.authenticated?(:user) + end + end + + test 'it uses the appropriate key when configured explicitly' do + 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 '"email":"user@test.com"', response.body assert warden.authenticated?(:user) end end test 'test request with oauth2 header doesnt get mistaken for basic authentication' do - swap Devise, :http_authenticatable => true do + swap Devise, http_authenticatable: true do add_oauth2_header assert_equal 401, status assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"] end end - test 'sign in should authenticate with really long token' do - token = "token_containing_so_many_characters_that_the_base64_encoding_will_wrap" - user = create_user - user.update_attribute :authentication_token, token - get users_path(:format => :xml), {}, "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("#{token}:x")}" - assert_response :success - assert_match "user@test.com", response.body - assert warden.authenticated?(:user) - 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), {}, "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), {}, "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 cbea8755b3..e5dd5ee08b 100644 --- a/test/integration/lockable_test.rb +++ b/test/integration/lockable_test.rb @@ -1,19 +1,22 @@ +# frozen_string_literal: true + require 'test_helper' -class LockTest < ActionController::IntegrationTest +class LockTest < Devise::IntegrationTest def visit_user_unlock_with_token(unlock_token) - visit user_unlock_path(:unlock_token => unlock_token) + visit user_unlock_path(unlock_token: unlock_token) end def send_unlock_request - user = create_user(:locked => true) + user = create_user(locked: true) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive unlock instructions?" - fill_in 'email', :with => user.email + Devise.stubs(:friendly_token).returns("abcdef") + fill_in 'email', with: user.email click_button 'Resend unlock instructions' end @@ -21,9 +24,12 @@ def send_unlock_request send_unlock_request assert_template 'sessions/new' - assert_contain 'You will receive an email with instructions about how to unlock your account in a few minutes' + assert_contain 'You will receive an email with instructions for how to unlock your account in a few minutes' + + mail = ActionMailer::Base.deliveries.last assert_equal 1, ActionMailer::Base.deliveries.size - assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from + assert_equal ['please-change-me@config-initializers-devise.com'], mail.from + assert_match user_unlock_path(unlock_token: 'abcdef'), mail.body.encoded end test 'user should receive the instructions from a custom mailer' do @@ -35,13 +41,13 @@ def send_unlock_request end test 'unlocked user should not be able to request a unlock token' do - user = create_user(:locked => false) + user = create_user(locked: false) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive unlock instructions?" - fill_in 'email', :with => user.email + fill_in 'email', with: user.email click_button 'Resend unlock instructions' assert_template 'unlocks/new' @@ -71,153 +77,156 @@ def send_unlock_request assert_response :success assert_current_url '/users/unlock?unlock_token=invalid_token' assert_have_selector '#error_explanation' - assert_contain /Unlock token(.*)invalid/ + assert_contain %r{Unlock token(.*)invalid} end test "locked user should be able to unlock account" do - user = create_user(:locked => true) - assert user.access_locked? - - visit_user_unlock_with_token(user.unlock_token) + user = create_user + raw = user.lock_access! + visit_user_unlock_with_token(raw) assert_current_url "/users/sign_in" assert_contain 'Your account has been unlocked successfully. Please sign in to continue.' - assert_not user.reload.access_locked? end - test "redirect user to sign in page after unlocking its account" do - user = create_user(:locked => true) - visit_user_unlock_with_token(user.unlock_token) - assert_not warden.authenticated?(:user) - end - test "user should not send a new e-mail if already locked" do - user = create_user(:locked => true) + user = create_user(locked: true) user.failed_attempts = User.maximum_attempts + 1 user.save! ActionMailer::Base.deliveries.clear - sign_in_as_user(:password => "invalid") + 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 - store_translations :en, :devise => { - :failure => {:user => {:locked => "You are locked!"}} + store_translations :en, devise: { + failure: {user: {locked: "You are locked!"}} } do - user = create_user(:locked => true) + user = create_user(locked: true) user.failed_attempts = User.maximum_attempts + 1 user.save! - sign_in_as_user(:password => "invalid") + sign_in_as_user(password: "invalid") assert_contain "You are locked!" end end test "user should not be able to sign in when locked" do - store_translations :en, :devise => { - :failure => {:user => {:locked => "You are locked!"}} + store_translations :en, devise: { + failure: {user: {locked: "You are locked!"}} } do - user = create_user(:locked => true) + user = create_user(locked: true) user.failed_attempts = User.maximum_attempts + 1 user.save! - sign_in_as_user(:password => "123456") + sign_in_as_user(password: "123456") assert_contain "You are locked!" end end - test 'user should be able to request a new unlock token via XML request' do - user = create_user(:locked => true) + 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'), :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 - user = create_user(:locked => false) + 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'), :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 - user = create_user(:locked => true) + 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 => user.unlock_token) + 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) + assert_includes response.body, '{"unlock_token":[' 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 - 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 - swap Devise, :paranoid => true do - user = create_user(:locked => true) + 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) visit new_user_session_path click_link "Didn't receive unlock instructions?" - fill_in 'email', :with => user.email + fill_in 'email', with: user.email click_button 'Resend unlock instructions' assert_current_url "/users/sign_in" - assert_contain "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes." + assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 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 - swap Devise, :paranoid => true do - user = create_user(:locked => false) + 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) visit new_user_session_path click_link "Didn't receive unlock instructions?" - fill_in 'email', :with => user.email + fill_in 'email', with: user.email click_button 'Resend unlock instructions' assert_current_url "/users/sign_in" - assert_contain "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes." + assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 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 - swap Devise, :paranoid => true 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?" - fill_in 'email', :with => "arandomemail@hotmail.com" + fill_in 'email', with: "arandomemail@hotmail.com" click_button 'Resend unlock instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" assert_current_url "/users/sign_in" - assert_contain "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes." + assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." + + end + end + + test "in paranoid mode, when locking a user that exists it should not say that the user was locked" do + swap Devise, paranoid: true, maximum_attempts: 1 do + user = create_user(locked: false) + visit new_user_session_path + fill_in 'email', with: user.email + fill_in 'password', with: "abadpassword" + click_button 'Log in' + + fill_in 'email', with: user.email + fill_in 'password', with: "abadpassword" + click_button 'Log in' + + assert_current_url "/users/sign_in" + assert_not_contain "locked" end end diff --git a/test/integration/mounted_engine_test.rb b/test/integration/mounted_engine_test.rb new file mode 100644 index 0000000000..0ac47e335a --- /dev/null +++ b/test/integration/mounted_engine_test.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +require 'test_helper' + +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 +Rails.application.routes.disable_clear_and_finalize = true + +Rails.application.routes.draw do + authenticate(:user) do + mount MyMountableEngine::Engine, at: '/mountable_engine' + end +end + +class AuthenticatedMountedEngineTest < Devise::IntegrationTest + test 'redirects to the sign in page when not authenticated' do + get '/mountable_engine' + follow_redirect! + + assert_response :ok + assert_contain 'You need to sign in or sign up before continuing.' + end + + test 'renders the mounted engine when authenticated' do + sign_in_as_user + get '/mountable_engine' + + assert_response :success + 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 2d55ebc6ea..72a59dbfbf 100644 --- a/test/integration/omniauthable_test.rb +++ b/test/integration/omniauthable_test.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require 'test_helper' -class OmniauthableIntegrationTest < ActionController::IntegrationTest +class OmniauthableIntegrationTest < Devise::IntegrationTest FACEBOOK_INFO = { "id" => '12345', "link" => 'http://facebook.com/josevalim', @@ -20,9 +22,14 @@ class OmniauthableIntegrationTest < ActionController::IntegrationTest "credentials" => {"token" => 'plataformatec'}, "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 + OmniAuth.config.camelizations.delete('facebook') OmniAuth.config.test_mode = false end @@ -38,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) @@ -53,16 +71,16 @@ 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"] assert_difference "User.count" do visit "/users/sign_up" - fill_in "Password", :with => "12345678" - fill_in "Password confirmation", :with => "12345678" + fill_in "Password", with: "12345678" + fill_in "Password confirmation", with: "12345678" click_button "Sign up" end @@ -74,60 +92,91 @@ def stub_action!(name) 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"] - user = sign_in_as_user - assert !session["devise.facebook_data"] + sign_in_as_user + 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 OmniAuth.config.mock_auth[:facebook] = :access_denied visit "/users/auth/facebook/callback?error=access_denied" assert_current_url "/users/sign_in" - assert_contain 'Could not authenticate you from Facebook because "Access denied".' + assert_contain 'Could not authenticate you from FaceBook because "Access denied".' end - test "handles other exceptions from omniauth" do + 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".' + 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 9dbadd0ac3..c391b0b2eb 100644 --- a/test/integration/recoverable_test.rb +++ b/test/integration/recoverable_test.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'test_helper' -class PasswordTest < ActionController::IntegrationTest +class PasswordTest < Devise::IntegrationTest def visit_new_password_path visit new_user_session_path @@ -12,48 +14,66 @@ def request_forgot_password(&block) assert_response :success assert_not warden.authenticated?(:user) - fill_in 'email', :with => 'user@test.com' + fill_in 'email', with: 'user@test.com' yield if block_given? - click_button 'Send me reset password instructions' + + Devise.stubs(:friendly_token).returns("abcdef") + click_button 'Send me password reset instructions' end - def reset_password(options={}, &block) - visit edit_user_password_path(:reset_password_token => options[:reset_password_token]) unless options[:visit] == false - assert_response :success + 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 + end - fill_in 'New password', :with => '987654321' - fill_in 'Confirm new password', :with => '987654321' + fill_in 'New password', with: '987654321' + fill_in 'Confirm new password', with: '987654321' yield if block_given? 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') + create_user(email: 'Foo@Bar.com') request_forgot_password do - fill_in 'email', :with => 'foo@bar.com' + fill_in 'email', with: 'foo@bar.com' end assert_current_url '/users/sign_in' - assert_contain 'You will receive an email with instructions about how to reset your password in a few minutes.' + assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.' end test 'reset password with email should send an email from a custom mailer' do - create_user(:email => 'Foo@Bar.com') + create_user(email: 'Foo@Bar.com') User.any_instance.stubs(:devise_mailer).returns(Users::Mailer) request_forgot_password do - fill_in 'email', :with => 'foo@bar.com' + fill_in 'email', with: 'foo@bar.com' end - assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.last.from + + mail = ActionMailer::Base.deliveries.last + assert_equal ['custom@example.com'], mail.from + assert_match edit_user_password_path(reset_password_token: 'abcdef'), mail.body.encoded end test 'reset password with email of different case should fail when email is NOT the list of case insensitive keys' do - swap Devise, :case_insensitive_keys => [] do - create_user(:email => 'Foo@Bar.com') + swap Devise, case_insensitive_keys: [] do + create_user(email: 'Foo@Bar.com') request_forgot_password do - fill_in 'email', :with => 'foo@bar.com' + fill_in 'email', with: 'foo@bar.com' end assert_response :success @@ -64,22 +84,22 @@ def reset_password(options={}, &block) end test 'reset password with email with extra whitespace should succeed when email is in the list of strip whitespace keys' do - create_user(:email => 'foo@bar.com') + create_user(email: 'foo@bar.com') request_forgot_password do - fill_in 'email', :with => ' foo@bar.com ' + fill_in 'email', with: ' foo@bar.com ' end assert_current_url '/users/sign_in' - assert_contain 'You will receive an email with instructions about how to reset your password in a few minutes.' + assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.' end test 'reset password with email with extra whitespace should fail when email is NOT the list of strip whitespace keys' do - swap Devise, :strip_whitespace_keys => [] do - create_user(:email => 'foo@bar.com') + swap Devise, strip_whitespace_keys: [] do + create_user(email: 'foo@bar.com') request_forgot_password do - fill_in 'email', :with => ' foo@bar.com ' + fill_in 'email', with: ' foo@bar.com ' end assert_response :success @@ -104,12 +124,12 @@ def reset_password(options={}, &block) request_forgot_password assert_current_url '/users/sign_in' - assert_contain 'You will receive an email with instructions about how to reset your password in a few minutes.' + assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.' end test 'not authenticated user with invalid email should receive an error message' do request_forgot_password do - fill_in 'email', :with => 'invalid.test@test.com' + fill_in 'email', with: 'invalid.test@test.com' end assert_response :success @@ -132,145 +152,194 @@ def reset_password(options={}, &block) assert_redirected_to "/users/sign_in" end - test 'not authenticated user with invalid reset password token should not be able to change his password' do + test 'not authenticated user with invalid reset password token should not be able to change their password' do user = create_user - reset_password :reset_password_token => 'invalid_reset_password' + reset_password reset_password_token: 'invalid_reset_password' assert_response :success assert_current_url '/users/password' assert_have_selector '#error_explanation' - assert_contain /Reset password token(.*)invalid/ + assert_contain %r{Reset password token(.*)invalid} 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 his password' do + test 'not authenticated user with valid reset password token but invalid password should not be able to change their password' do user = create_user request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token do - fill_in 'Confirm new password', :with => 'other_password' + reset_password do + fill_in 'Confirm new password', with: 'other_password' end assert_response :success assert_current_url '/users/password' assert_have_selector '#error_explanation' - assert_contain 'Password doesn\'t match confirmation' + 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 his password' do + test 'not authenticated user with valid data should be able to change their password' do user = create_user request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token + reset_password assert_current_url '/' - assert_contain 'Your password was changed successfully. You are now signed in.' + assert_contain 'Your password has been changed successfully. You are now signed in.' assert user.reload.valid_password?('987654321') end - test 'after entering invalid data user should still be able to change his password' do + test 'after entering invalid data user should still be able to change their password' do user = create_user request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token do - fill_in 'Confirm new password', :with => 'other_password' - end + + reset_password { fill_in 'Confirm new password', with: 'other_password' } assert_response :success assert_have_selector '#error_explanation' assert_not user.reload.valid_password?('987654321') - reset_password :reset_password_token => user.reload.reset_password_token, :visit => false - assert_contain 'Your password was changed successfully.' + reset_password visit: false + assert_contain 'Your password has been changed successfully.' assert user.reload.valid_password?('987654321') end test 'sign in user automatically after changing its password' do - user = create_user + create_user request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token + reset_password assert warden.authenticated?(:user) end - test 'does not sign in user automatically after changing its password if it\'s locked' do - user = create_user(:locked => true) - request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token + test 'does not sign in user automatically after changing its password if config.sign_in_after_reset_password is false' do + swap Devise, sign_in_after_reset_password: false do + create_user + request_forgot_password + reset_password - assert_contain 'Your password was changed successfully.' - assert_not_contain 'You are now signed in.' - assert_equal new_user_session_path, @request.path - assert !warden.authenticated?(:user) + 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 and confirm after changing its password if it\'s not confirmed' do - user = create_user(:confirm => false) - request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token + 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 warden.authenticated?(:user) - assert user.reload.confirmed? + 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 'reset password request with valid E-Mail in XML format should return valid response' do + 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 + + test 'does not sign in user automatically after changing its password if it\'s locked and unlock strategy is :none or :time' do + [:none, :time].each do |strategy| + swap Devise, unlock_strategy: strategy do + create_user(locked: true) + 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 + end + + test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :email' do + swap Devise, unlock_strategy: :email do + user = create_user(locked: true) + request_forgot_password + reset_password + + assert_contain 'Your password has been changed successfully.' + assert_not user.reload.access_locked? + assert warden.authenticated?(:user) + end + end + + test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :both' do + swap Devise, unlock_strategy: :both do + user = create_user(locked: true) + request_forgot_password + reset_password + + assert_contain 'Your password has been changed successfully.' + assert_not user.reload.access_locked? + assert warden.authenticated?(:user) + end + end + + 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'), :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'), :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 - swap Devise, :paranoid => true 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'), :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 - user = create_user + 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'), :user => {:reset_password_token => user.reload.reset_password_token, :password => '987654321', :password_confirmation => '987654321'} + 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 - user = create_user + 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'), :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'), :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), :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 + swap Devise, paranoid: true do visit_new_password_path - fill_in "email", :with => "arandomemail@test.com" - click_button 'Send me reset password instructions' + fill_in "email", with: "arandomemail@test.com" + click_button 'Send me password reset instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" @@ -280,11 +349,11 @@ def reset_password(options={}, &block) end test "when in paranoid mode and with a valid e-mail, asking to reset password should display a message that does not indicates that the email exists in the database and redirect to the failure route" do - swap Devise, :paranoid => true do + swap Devise, paranoid: true do user = create_user visit_new_password_path - fill_in 'email', :with => user.email - click_button 'Send me reset password instructions' + fill_in 'email', with: user.email + 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" @@ -297,7 +366,7 @@ def reset_password(options={}, &block) assert_equal 10, user.failed_attempts request_forgot_password - reset_password :reset_password_token => user.reload.reset_password_token + reset_password assert warden.authenticated?(:user) user.reload diff --git a/test/integration/registerable_test.rb b/test/integration/registerable_test.rb index 39d3ba7a28..ad0f3bec05 100644 --- a/test/integration/registerable_test.rb +++ b/test/integration/registerable_test.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'test_helper' -class RegistrationTest < ActionController::IntegrationTest +class RegistrationTest < Devise::IntegrationTest test 'a guest admin should be able to sign in successfully' do get new_admin_session_path @@ -8,17 +10,17 @@ class RegistrationTest < ActionController::IntegrationTest assert_template 'registrations/new' - fill_in 'email', :with => 'new_user@test.com' - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user123' + fill_in 'email', with: 'new_user@test.com' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_contain 'You have signed up successfully' assert warden.authenticated?(:admin) assert_current_url "/admin_area/home" - admin = Admin.last :order => "id" - assert_equal admin.email, 'new_user@test.com' + admin = Admin.to_adapter.find_first(order: [:id, :desc]) + 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 @@ -26,9 +28,9 @@ class RegistrationTest < ActionController::IntegrationTest get new_admin_session_path click_link 'Sign up' - fill_in 'email', :with => 'new_user@test.com' - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user123' + fill_in 'email', with: 'new_user@test.com' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_contain 'Welcome! You have signed up successfully.' @@ -36,28 +38,38 @@ class RegistrationTest < ActionController::IntegrationTest assert_current_url "/?custom=1" end + test 'a guest admin should not see a warning about minimum password length' do + get new_admin_session_path + assert_not_contain 'characters minimum' + end + def user_sign_up ActionMailer::Base.deliveries.clear get new_user_registration_path - fill_in 'email', :with => 'new_user@test.com' - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user123' + fill_in 'email', with: 'new_user@test.com' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' end + test 'a guest user should see a warning about minimum password length' do + get new_user_registration_path + assert_contain '7 characters minimum' + end + test 'a guest user should be able to sign up successfully and be blocked by confirmation' do user_sign_up - assert_contain 'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.' + assert_contain 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.' assert_not_contain 'You have to confirm your account before continuing' assert_current_url "/" assert_not warden.authenticated?(:user) - user = User.last :order => "id" - assert_equal user.email, 'new_user@test.com' + user = User.to_adapter.find_first(order: [:id, :desc]) + assert_equal 'new_user@test.com', user.email assert_not user.confirmed? end @@ -76,9 +88,9 @@ def user_sign_up Devise::RegistrationsController.any_instance.stubs(:after_inactive_sign_up_path_for).returns("/?custom=1") get new_user_registration_path - fill_in 'email', :with => 'new_user@test.com' - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user123' + fill_in 'email', with: 'new_user@test.com' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_current_url "/?custom=1" @@ -86,38 +98,30 @@ def user_sign_up 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' - fill_in 'password', :with => 'new_user123' - fill_in 'password confirmation', :with => 'new_user321' + fill_in 'email', with: 'invalid_email' + fill_in 'password', with: 'new_user123' + fill_in 'password confirmation', with: 'new_user321' click_button 'Sign up' assert_template 'registrations/new' assert_have_selector '#error_explanation' assert_contain "Email is invalid" - assert_contain "Password doesn't match confirmation" + assert_contain %r{Password confirmation doesn['’]t match Password} assert_contain "2 errors prohibited" - assert_nil User.first + assert_nil User.to_adapter.find_first 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 - - user = create_user + create_user get new_user_registration_path - fill_in 'email', :with => 'user@test.com' - fill_in 'password', :with => '123456' - fill_in 'password confirmation', :with => '123456' + fill_in 'email', with: 'user@test.com' + fill_in 'password', with: '123456' + fill_in 'password confirmation', with: '123456' click_button 'Sign up' assert_current_url '/users' @@ -139,85 +143,124 @@ def user_sign_up assert_redirected_to root_path end - test 'a signed in user should be able to edit his account' do + test 'a signed in user should be able to edit their account' do sign_in_as_user get edit_user_registration_path - fill_in 'email', :with => 'user.new@example.com' - fill_in 'current password', :with => '12345678' + fill_in 'email', with: 'user.new@example.com' + fill_in 'current password', with: '12345678' click_button 'Update' assert_current_url '/' - assert_contain 'You updated your account successfully.' + assert_contain 'Your account has been updated successfully.' - assert_equal "user.new@example.com", User.first.email + assert_equal "user.new@example.com", User.to_adapter.find_first.email end - test 'a signed in user should still be able to use the website after changing his password' do + test 'a signed in user should still be able to use the website after changing their password' 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' + fill_in 'password', with: '1234567890' + fill_in 'password confirmation', with: '1234567890' + fill_in 'current password', with: '12345678' click_button 'Update' - assert_contain 'You updated your account successfully.' + assert_contain 'Your account has been updated successfully.' get users_path assert warden.authenticated?(:user) end - test 'a signed in user should not change his current user with invalid password' do + 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 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 - fill_in 'email', :with => 'user.new@example.com' - fill_in 'current password', :with => 'invalid' + fill_in 'email', with: 'user.new@example.com' + fill_in 'current password', with: 'invalid' click_button 'Update' assert_template 'registrations/edit' assert_contain 'user@test.com' assert_have_selector 'form input[value="user.new@example.com"]' - assert_equal "user@test.com", User.first.email + assert_equal "user@test.com", User.to_adapter.find_first.email end - test 'a signed in user should be able to edit his password' do + test 'a signed in user should be able to edit their password' do sign_in_as_user get edit_user_registration_path - fill_in 'password', :with => 'pass1234' - fill_in 'password confirmation', :with => 'pass1234' - fill_in 'current password', :with => '12345678' + fill_in 'password', with: 'pass1234' + fill_in 'password confirmation', with: 'pass1234' + fill_in 'current password', with: '12345678' click_button 'Update' assert_current_url '/' - assert_contain 'You updated your account successfully.' + assert_contain 'Your account has been updated successfully.' - assert User.first.valid_password?('pass1234') + assert User.to_adapter.find_first.valid_password?('pass1234') end - test 'a signed in user should not be able to edit his password with invalid confirmation' do + test 'a signed in user should not be able to edit their password with invalid confirmation' do sign_in_as_user get edit_user_registration_path - fill_in 'password', :with => 'pas123' - fill_in 'password confirmation', :with => '' - fill_in 'current password', :with => '123456' + fill_in 'password', with: 'pas123' + fill_in 'password confirmation', with: '' + fill_in 'current password', with: '12345678' click_button 'Update' - assert_contain "Password doesn't match confirmation" - assert_not User.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 + assert_contain 'characters minimum' end - test 'a signed in user should be able to cancel his account' do + test 'a signed in user should be able to cancel their account' do sign_in_as_user get edit_user_registration_path - click_link "Cancel my account", :method => :delete - assert_contain "Bye! Your account was successfully cancelled. We hope to see you again soon." + click_button "Cancel my account" + assert_contain "Bye! Your account has been successfully cancelled. We hope to see you again soon." - assert User.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 @@ -232,114 +275,109 @@ 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(/ 'json') + get new_user_registration_path(format: 'json') assert_response :success assert_match %({"user":), response.body assert_no_match(/"confirmation_token"/, response.body) end - test 'an admin sign up with valid information in XML format should return valid response' do - post admin_registration_path(:format => 'xml'), :admin => { :email => 'new_user@test.com', :password => 'new_user123', :password_confirmation => 'new_user123' } + test 'an admin sign up with valid information in JSON format should return valid response' do + post admin_registration_path(format: 'json'), params: { admin: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'new_user123' } } assert_response :success - assert response.body.include? %(\n) + assert_includes response.body, '{"admin":{' - admin = Admin.last :order => "id" - assert_equal admin.email, 'new_user@test.com' + admin = Admin.to_adapter.find_first(order: [:id, :desc]) + 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'), :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.last :order => "id" - assert_equal user.email, 'new_user@test.com' + user = User.to_adapter.find_first(order: [:id, :desc]) + 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'), :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'), :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'), :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 his account in XML format should return valid response' do - user = sign_in_as_user - delete user_registration_path(:format => 'xml') + test 'a user cancel their account in JSON format should return valid response' do + sign_in_as_user + delete user_registration_path(format: 'json') assert_response :success - assert_equal User.count, 0 + assert_equal 0, User.to_adapter.find_all.size end end -class ReconfirmableRegistrationTest < ActionController::IntegrationTest - test 'a signed in admin should see a more appropriate flash message when editing his account if reconfirmable is enabled' do +class ReconfirmableRegistrationTest < Devise::IntegrationTest + test 'a signed in admin should see a more appropriate flash message when editing their account if reconfirmable is enabled' do sign_in_as_admin get edit_admin_registration_path - fill_in 'email', :with => 'admin.new@example.com' - fill_in 'current password', :with => '123456' + fill_in 'email', with: 'admin.new@example.com' + fill_in 'current password', with: '123456' click_button 'Update' assert_current_url '/admin_area/home' assert_contain 'but we need to verify your new email address' + assert_equal 'admin.new@example.com', Admin.to_adapter.find_first.unconfirmed_email - assert_equal "admin.new@example.com", Admin.first.unconfirmed_email + get edit_admin_registration_path + assert_contain 'Currently waiting confirmation for: admin.new@example.com' end test 'a signed in admin should not see a reconfirmation message if they did not change their password' do sign_in_as_admin get edit_admin_registration_path - fill_in 'password', :with => 'pas123' - fill_in 'password confirmation', :with => 'pas123' - fill_in 'current password', :with => '123456' + fill_in 'password', with: 'pas123' + fill_in 'password confirmation', with: 'pas123' + fill_in 'current password', with: '123456' click_button 'Update' assert_current_url '/admin_area/home' - assert_contain 'You updated your account successfully.' + assert_contain 'Your account has been updated successfully.' - assert Admin.first.valid_password?('pas123') + assert Admin.to_adapter.find_first.valid_password?('pas123') end - test 'a signed in admin should not see a reconfirmation message if he did not change his email, despite having an unconfirmed email' do + test 'a signed in admin should not see a reconfirmation message if they did not change their email, despite having an unconfirmed email' do sign_in_as_admin get edit_admin_registration_path - fill_in 'email', :with => 'admin.new@example.com' - fill_in 'current password', :with => '123456' + fill_in 'email', with: 'admin.new@example.com' + fill_in 'current password', with: '123456' click_button 'Update' get edit_admin_registration_path - fill_in 'password', :with => 'pas123' - fill_in 'password confirmation', :with => 'pas123' - fill_in 'current password', :with => '123456' + fill_in 'password', with: 'pas123' + fill_in 'password confirmation', with: 'pas123' + fill_in 'current password', with: '123456' click_button 'Update' assert_current_url '/admin_area/home' - assert_contain 'You updated your account successfully.' + assert_contain 'Your account has been updated successfully.' - assert_equal "admin.new@example.com", Admin.first.unconfirmed_email - assert Admin.first.valid_password?('pas123') + assert_equal "admin.new@example.com", Admin.to_adapter.find_first.unconfirmed_email + assert Admin.to_adapter.find_first.valid_password?('pas123') end -end \ No newline at end of file +end diff --git a/test/integration/rememberable_test.rb b/test/integration/rememberable_test.rb index 7c50bc11f5..1fc4e4d584 100644 --- a/test/integration/rememberable_test.rb +++ b/test/integration/rememberable_test.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'test_helper' -class RememberMeTest < ActionController::IntegrationTest - def create_user_and_remember(add_to_token='') +class RememberMeTest < Devise::IntegrationTest + def create_user_and_remember(add_to_token = '') user = create_user user.remember_me! - raw_cookie = User.serialize_into_cookie(user).tap { |a| a.last << add_to_token } + raw_cookie = User.serialize_into_cookie(user).tap { |a| a[1] << add_to_token } cookies['remember_user_token'] = generate_signed_cookie(raw_cookie) user end def generate_signed_cookie(raw_cookie) - request = ActionDispatch::TestRequest.new + request = ActionController::TestRequest.create(Class.new) # needs a "controller class" request.cookie_jar.signed['raw_cookie'] = raw_cookie request.cookie_jar['raw_cookie'] end @@ -25,13 +27,13 @@ def cookie_expires(key) Time.parse(expires).utc end - test 'do not remember the user if he has not checked remember me option' do - user = sign_in_as_user + test 'do not remember the user if they have not checked remember me option' do + sign_in_as_user assert_nil request.cookies["remember_user_cookie"] end - test 'handles unverified requests gets rid of caches' do - swap UsersController, :allow_forgery_protection => true do + test 'handle unverified requests gets rid of caches' do + swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) assert_not warden.authenticated?(:user) @@ -42,25 +44,46 @@ def cookie_expires(key) end end + test 'handle unverified requests does not create cookies on sign in' do + swap ApplicationController, allow_forgery_protection: true do + get new_user_session_path + assert request.session[:_csrf_token] + + post user_session_path, params: { + authenticity_token: "oops", + user: { email: "jose.valim@gmail.com", password: "123456", remember_me: "1" } + } + assert_not warden.authenticated?(:user) + assert_not request.cookies['remember_user_token'] + end + end + test 'generate remember token after sign in' do - user = sign_in_as_user :remember_me => true - assert request.cookies["remember_user_token"] + sign_in_as_user remember_me: true + assert request.cookies['remember_user_token'] end test 'generate remember token after sign in setting cookie options' do # We test this by asserting the cookie is not sent after the redirect # since we changed the domain. This is the only difference with the # previous test. - swap Devise, :rememberable_options => { :domain => "omg.somewhere.com" } do - user = sign_in_as_user :remember_me => true + swap Devise, rememberable_options: { domain: "omg.somewhere.com" } do + sign_in_as_user remember_me: true assert_nil request.cookies["remember_user_token"] end end + test 'generate remember token with a custom key' do + swap Devise, rememberable_options: { key: "v1lat_token" } do + sign_in_as_user remember_me: true + assert request.cookies["v1lat_token"] + end + end + test 'generate remember token after sign in setting session options' do begin Rails.configuration.session_options[:domain] = "omg.somewhere.com" - user = sign_in_as_user :remember_me => true + sign_in_as_user remember_me: true assert_nil request.cookies["remember_user_token"] ensure Rails.configuration.session_options.delete(:domain) @@ -73,35 +96,24 @@ def cookie_expires(key) assert_response :success assert warden.authenticated?(:user) assert warden.user(:user) == user - assert_match /remember_user_token[^\n]*HttpOnly/, response.headers["Set-Cookie"], "Expected Set-Cookie header in response to set HttpOnly flag on remember_user_token cookie." end - test 'remember the user before sign up and redirect him to his home' do - user = create_user_and_remember + test 'remember the user before sign up and redirect them to their home' do + create_user_and_remember get new_user_registration_path assert warden.authenticated?(:user) assert_redirected_to root_path end - test 'cookies are destroyed on unverified requests' do - swap ApplicationController, :allow_forgery_protection => true do - user = create_user_and_remember - get users_path - assert warden.authenticated?(:user) - post root_path, :authenticity_token => 'INVALID' - assert_not warden.authenticated?(:user) - end - end - test 'does not extend remember period through sign in' do - swap Devise, :extend_remember_period => true, :remember_for => 1.year do + swap Devise, extend_remember_period: true, remember_for: 1.year do user = create_user user.remember_me! user.remember_created_at = old = 10.days.ago user.save - sign_in_as_user :remember_me => true + sign_in_as_user remember_me: true user.reload assert warden.user(:user) == user @@ -109,8 +121,42 @@ def cookie_expires(key) end end + test 'extends remember period when extend remember period config is true' do + swap Devise, extend_remember_period: true, remember_for: 1.year do + create_user_and_remember + old_remember_token = nil + + travel_to 1.day.ago do + get root_path + old_remember_token = request.cookies['remember_user_token'] + end + + get root_path + current_remember_token = request.cookies['remember_user_token'] + + assert_not_equal old_remember_token, current_remember_token + end + end + + test 'does not extend remember period when extend period config is false' do + swap Devise, extend_remember_period: false, remember_for: 1.year do + create_user_and_remember + old_remember_token = nil + + travel_to 1.day.ago do + get root_path + old_remember_token = request.cookies['remember_user_token'] + end + + get root_path + current_remember_token = request.cookies['remember_user_token'] + + assert_equal old_remember_token, current_remember_token + end + end + test 'do not remember other scopes' do - user = create_user_and_remember + create_user_and_remember get root_path assert_response :success assert warden.authenticated?(:user) @@ -118,15 +164,15 @@ def cookie_expires(key) end test 'do not remember with invalid token' do - user = create_user_and_remember('add') + create_user_and_remember('add') get users_path assert_not warden.authenticated?(:user) assert_redirected_to new_user_session_path end test 'do not remember with expired token' do - user = create_user_and_remember - swap Devise, :remember_for => 0 do + create_user_and_remember + swap Devise, remember_for: 0.days do get users_path assert_not warden.authenticated?(:user) assert_redirected_to new_user_session_path @@ -134,11 +180,11 @@ def cookie_expires(key) end test 'do not remember the user anymore after forget' do - user = create_user_and_remember + create_user_and_remember get users_path assert warden.authenticated?(:user) - get destroy_user_session_path + delete destroy_user_session_path assert_not warden.authenticated?(:user) assert_nil warden.cookies['remember_user_token'] @@ -155,4 +201,13 @@ def cookie_expires(key) get users_path assert_not warden.authenticated?(:user) end + + test 'valid sign in calls after_remembered callback' do + user = create_user_and_remember + + User.expects(:serialize_from_cookie).returns user + user.expects :after_remembered + + get new_user_registration_path + end end diff --git a/test/integration/timeoutable_test.rb b/test/integration/timeoutable_test.rb index f488d8ef85..73c716e660 100644 --- a/test/integration/timeoutable_test.rb +++ b/test/integration/timeoutable_test.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'test_helper' -class SessionTimeoutTest < ActionController::IntegrationTest +class SessionTimeoutTest < Devise::IntegrationTest def last_request_at @controller.user_session['last_request_at'] @@ -8,12 +10,11 @@ def last_request_at test 'set last request at in user session after each request' do sign_in_as_user - old_last_request = last_request_at assert_not_nil last_request_at + @controller.user_session.delete('last_request_at') get users_path assert_not_nil last_request_at - assert_not_equal old_last_request, last_request_at end test 'set last request at in user session after each request is skipped if tracking is disabled' do @@ -21,7 +22,19 @@ def last_request_at old_last_request = last_request_at assert_not_nil last_request_at - get users_path, {}, 'devise.skip_trackable' => true + get users_path, headers: { 'devise.skip_trackable' => true } + assert_equal old_last_request, last_request_at + end + + test 'does not set last request at in user session after each request if timeoutable is disabled' do + sign_in_as_user + old_last_request = last_request_at + assert_not_nil last_request_at + + new_time = 2.seconds.from_now + Time.stubs(:now).returns(new_time) + + get users_path, headers: { 'devise.skip_timeoutable' => true } assert_equal old_last_request, last_request_at end @@ -35,21 +48,50 @@ def last_request_at assert warden.authenticated?(:user) end - test 'time out user session after default limit time' do + test 'time out user session after default limit time when sign_out_all_scopes is false' do + swap Devise, sign_out_all_scopes: false do + sign_in_as_admin + + user = sign_in_as_user + get expire_user_path(user) + assert_not_nil last_request_at + + get users_path + assert_redirected_to users_path + assert_not warden.authenticated?(:user) + assert warden.authenticated?(:admin) + end + end + + test 'time out all sessions after default limit time when sign_out_all_scopes is true' do + swap Devise, sign_out_all_scopes: true do + sign_in_as_admin + + user = sign_in_as_user + get expire_user_path(user) + assert_not_nil last_request_at + + get root_path + assert_not warden.authenticated?(:user) + assert_not warden.authenticated?(:admin) + end + end + + test 'time out user session after default limit time and redirect to latest get request' do user = sign_in_as_user - get expire_user_path(user) - assert_not_nil last_request_at + visit edit_form_user_path(user) - get users_path - assert_redirected_to users_path - assert_not warden.authenticated?(:user) + click_button 'Update' + sign_in_as_user + + assert_equal edit_form_user_url(user), current_url end test 'time out is not triggered on sign out' do user = sign_in_as_user get expire_user_path(user) - get destroy_user_session_path + delete destroy_user_session_path assert_response :redirect assert_redirected_to root_path @@ -57,36 +99,33 @@ def last_request_at assert_contain 'Signed out successfully' end - test 'time out is not triggered on sign in' do + test 'expired session is not extended by sign in page' do user = sign_in_as_user get expire_user_path(user) + assert warden.authenticated?(:user) - post "/users/sign_in", :email => user.email, :password => "123456" - - assert_response :redirect + get "/users/sign_in" + assert_redirected_to "/users/sign_in" follow_redirect! - assert_contain 'You are signed in' + + assert_response :success + assert_contain 'Log in' + assert_not warden.authenticated?(:user) end - test 'admin does not explode on time out' do - admin = sign_in_as_admin - get expire_admin_path(admin) + test 'time out is not triggered on sign in' do + user = sign_in_as_user + get expire_user_path(user) - Admin.send :define_method, :reset_authentication_token! do - nil - end + post "/users/sign_in", params: { email: user.email, password: "123456" } - begin - get admins_path - assert_redirected_to admins_path - assert_not warden.authenticated?(:admin) - ensure - Admin.send(:remove_method, :reset_authentication_token!) - end + assert_response :redirect + follow_redirect! + assert_contain 'You are signed in' end test 'user configured timeout limit' do - swap Devise, :timeout_in => 8.minutes do + swap Devise, timeout_in: 8.minutes do user = sign_in_as_user get users_path @@ -102,8 +141,8 @@ def last_request_at end test 'error message with i18n' do - store_translations :en, :devise => { - :failure => { :user => { :timeout => 'Session expired!' } } + store_translations :en, devise: { + failure: { user: { timeout: 'Session expired!' } } } do user = sign_in_as_user @@ -115,8 +154,8 @@ def last_request_at end test 'error message with i18n with double redirect' do - store_translations :en, :devise => { - :failure => { :user => { :timeout => 'Session expired!' } } + store_translations :en, devise: { + failure: { user: { timeout: 'Session expired!' } } } do user = sign_in_as_user @@ -128,8 +167,19 @@ 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 + user = sign_in_as_user remember_me: true get expire_user_path(user) assert_not_nil last_request_at @@ -137,4 +187,13 @@ def last_request_at assert_response :success assert warden.authenticated?(:user) end + + test 'does not crash when the last_request_at is a String' do + user = sign_in_as_user + + 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/token_authenticatable_test.rb b/test/integration/token_authenticatable_test.rb deleted file mode 100644 index 17426dbf56..0000000000 --- a/test/integration/token_authenticatable_test.rb +++ /dev/null @@ -1,161 +0,0 @@ -require 'test_helper' - -class TokenAuthenticationTest < ActionController::IntegrationTest - - test 'authenticate with valid authentication token key and value through params' do - swap Devise, :token_authentication_key => :secret_token do - sign_in_as_new_user_with_token - - assert_response :success - assert_current_url "/users?secret_token=#{VALID_AUTHENTICATION_TOKEN}" - assert_contain 'Welcome' - assert warden.authenticated?(:user) - end - end - - test 'authenticate with valid authentication token key and value through params, when params with the same key as scope exist' do - swap Devise, :token_authentication_key => :secret_token do - user = create_user_with_authentication_token - post exhibit_user_path(user), Devise.token_authentication_key => user.authentication_token, :user => { :some => "data" } - - assert_response :success - assert_contain 'User is authenticated' - assert warden.authenticated?(:user) - end - end - - test 'authenticate with valid authentication token key but does not store if stateless' do - swap Devise, :token_authentication_key => :secret_token, :skip_session_storage => [:token_auth] do - sign_in_as_new_user_with_token - assert warden.authenticated?(:user) - - get users_path - assert_redirected_to new_user_session_path - assert_not warden.authenticated?(:user) - end - end - - test 'authenticate with valid authentication token key and value through http' do - swap Devise, :token_authentication_key => :secret_token do - sign_in_as_new_user_with_token(:http_auth => true) - - assert_response :success - assert_match 'user@test.com', response.body - assert warden.authenticated?(:user) - end - end - - test 'does authenticate with valid authentication token key and value through params if not configured' do - swap Devise, :token_authentication_key => :secret_token, :params_authenticatable => [:database] do - sign_in_as_new_user_with_token - - assert_contain 'You need to sign in or sign up before continuing' - assert_contain 'Sign in' - assert_not warden.authenticated?(:user) - end - end - - test 'does authenticate with valid authentication token key and value through http if not configured' do - swap Devise, :token_authentication_key => :secret_token, :http_authenticatable => [:database] do - sign_in_as_new_user_with_token(:http_auth => true) - - assert_response 401 - assert_contain 'Invalid email or password.' - assert_not warden.authenticated?(:user) - end - end - - test 'does not authenticate with improper authentication token key' do - swap Devise, :token_authentication_key => :donald_duck_token do - sign_in_as_new_user_with_token(:auth_token_key => :secret_token) - assert_equal new_user_session_path, @request.path - - assert_contain 'You need to sign in or sign up before continuing' - assert_contain 'Sign in' - assert_not warden.authenticated?(:user) - end - end - - test 'does not authenticate with improper authentication token value' do - store_translations :en, :devise => {:failure => {:invalid_token => 'LOL, that was not a single character correct.'}} do - sign_in_as_new_user_with_token(:auth_token => '*** INVALID TOKEN ***') - assert_equal new_user_session_path, @request.path - - assert_contain 'LOL, that was not a single character correct.' - assert_contain 'Sign in' - assert_not warden.authenticated?(:user) - end - end - - test 'authenticate with valid authentication token key and do not store if stateless and timeoutable are enabled' do - swap Devise, :token_authentication_key => :secret_token, :skip_session_storage => [:token_auth], :timeout_in => (0.1).second do - user = sign_in_as_new_user_with_token - assert warden.authenticated?(:user) - - # Expiring does not work because we are setting the session value when accessing it - sleep 0.3 - - get_users_path_as_existing_user(user) - assert warden.authenticated?(:user) - end - end - - test 'should reset token and not authenticate when expire_auth_token_on_timeout is set to true, timeoutable is enabled and we have a timed out session' do - swap Devise, :token_authentication_key => :secret_token, :expire_auth_token_on_timeout => true, :timeout_in => (-1).minute do - user = sign_in_as_new_user_with_token - assert warden.authenticated?(:user) - token = user.authentication_token - - get_users_path_as_existing_user(user) - assert_not warden.authenticated?(:user) - user.reload - assert_not_equal token, user.authentication_token - end - end - - test 'should not be subject to injection' do - swap Devise, :token_authentication_key => :secret_token do - user1 = create_user_with_authentication_token() - - # Clean up user cache - @user = nil - - user2 = create_user_with_authentication_token(:email => "another@test.com") - user2.update_attribute(:authentication_token, "ANOTHERTOKEN") - - assert_not_equal user1, user2 - visit users_path(Devise.token_authentication_key.to_s + '[$ne]' => user1.authentication_token) - assert_nil warden.user(:user) - end - end - - private - - def sign_in_as_new_user_with_token(options = {}) - user = options.delete(:user) || create_user_with_authentication_token(options) - - options[:auth_token_key] ||= Devise.token_authentication_key - options[:auth_token] ||= user.authentication_token - - if options[:http_auth] - header = "Basic #{Base64.encode64("#{VALID_AUTHENTICATION_TOKEN}:X")}" - get users_path(:format => :xml), {}, "HTTP_AUTHORIZATION" => header - else - visit users_path(options[:auth_token_key].to_sym => options[:auth_token]) - end - - user - end - - def create_user_with_authentication_token(options={}) - user = create_user(options) - user.authentication_token = VALID_AUTHENTICATION_TOKEN - user.save - user - end - - def get_users_path_as_existing_user(user) - sign_in_as_new_user_with_token(:user => user) - end - -end diff --git a/test/integration/trackable_test.rb b/test/integration/trackable_test.rb index df492784fa..f5b6fcda82 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 < ActionController::IntegrationTest +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 @@ -10,13 +17,13 @@ class TrackableHooksTest < ActionController::IntegrationTest sign_in_as_user user.reload - assert_kind_of Time, user.current_sign_in_at - assert_kind_of Time, user.last_sign_in_at + assert user.current_sign_in_at.acts_like?(:time) + assert user.last_sign_in_at.acts_like?(:time) assert_equal user.current_sign_in_at, user.last_sign_in_at assert user.current_sign_in_at >= user.created_at - visit destroy_user_session_path + delete destroy_user_session_path new_time = 2.seconds.from_now Time.stubs(:now).returns(new_time) @@ -37,7 +44,7 @@ class TrackableHooksTest < ActionController::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 < ActionController::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 @@ -56,15 +64,15 @@ class TrackableHooksTest < ActionController::IntegrationTest user.reload assert_equal 1, user.sign_in_count - visit destroy_user_session_path + delete destroy_user_session_path sign_in_as_user user.reload assert_equal 2, user.sign_in_count end test "does not update anything if user has signed out along the way" do - swap Devise, :allow_unconfirmed_access_for => 0 do - user = create_user(:confirm => false) + swap Devise, allow_unconfirmed_access_for: 0.days do + user = create_user(confirm: false) sign_in_as_user user.reload @@ -80,7 +88,7 @@ class TrackableHooksTest < ActionController::IntegrationTest end user.reload assert_equal 0, user.sign_in_count - visit destroy_user_session_path + delete destroy_user_session_path sign_in_as_user do header 'devise.skip_trackable', false diff --git a/test/mailers/confirmation_instructions_test.rb b/test/mailers/confirmation_instructions_test.rb index 213923d9c6..5b46331219 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 @@ -37,50 +39,63 @@ def mail assert_equal [user.email], mail.to end - test 'setup sender from configuration' do + test 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end - test 'setup sender from custom mailer defaults' do + test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end - test 'setup reply to as copy from sender' do + test 'set up sender from custom mailer defaults with proc' do + Devise.mailer = 'Users::FromProcMailer' + assert_equal ['custom@example.com'], mail.from + end + + test 'custom mailer renders parent mailer template' do + Devise.mailer = 'Users::Mailer' + assert_present mail.body.encoded + end + + test 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end - test 'setup reply to as different if set in defaults' do + test 'set up reply to as different if set in defaults' do Devise.mailer = 'Users::ReplyToMailer' assert_equal ['custom@example.com'], mail.from assert_equal ['custom_reply_to@example.com'], mail.reply_to end - - test 'setup subject from I18n' do - store_translations :en, :devise => { :mailer => { :confirmation_instructions => { :subject => 'Account Confirmation' } } } do + test 'set up subject from I18n' do + store_translations :en, devise: { mailer: { confirmation_instructions: { subject: 'Account Confirmation' } } } do assert_equal 'Account Confirmation', mail.subject end end test 'subject namespaced by model' do - store_translations :en, :devise => { :mailer => { :confirmation_instructions => { :user_subject => 'User Account Confirmation' } } } do + store_translations :en, devise: { mailer: { confirmation_instructions: { user_subject: 'User Account Confirmation' } } } do assert_equal 'User Account Confirmation', mail.subject end end test 'body should have user info' do - assert_match /#{user.email}/, mail.body.encoded + assert_match user.email, mail.body.encoded end test 'body should have link to confirm the account' do - host = ActionMailer::Base.default_url_options[:host] - confirmation_url_regexp = %r{} - assert_match confirmation_url_regexp, mail.body.encoded + host, port = ActionMailer::Base.default_url_options.values_at :host, :port + + if mail.body.encoded =~ %r{} + assert_equal user.confirmation_token, $1 + else + flunk "expected confirmation url regex to match" + end end test 'renders a scoped if scoped_views is set to true' do - swap Devise, :scoped_views => true do + swap Devise, scoped_views: true do assert_equal user.email, mail.body.decoded end end @@ -95,7 +110,7 @@ def mail end test 'mailer sender accepts a proc' do - swap Devise, :mailer_sender => proc { "another@example.com" } do + swap Devise, mailer_sender: proc { "another@example.com" } do assert_equal ['another@example.com'], mail.from end end diff --git a/test/mailers/email_changed_test.rb b/test/mailers/email_changed_test.rb new file mode 100644 index 0000000000..f324165452 --- /dev/null +++ b/test/mailers/email_changed_test.rb @@ -0,0 +1,132 @@ +# frozen_string_literal: true + +require 'test_helper' + +class EmailChangedTest < ActionMailer::TestCase + def setup + setup_mailer + Devise.mailer = 'Devise::Mailer' + Devise.mailer_sender = 'test@example.com' + Devise.send_email_changed_notification = true + end + + def teardown + Devise.mailer = 'Devise::Mailer' + Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' + Devise.send_email_changed_notification = false + end + + def user + @user ||= create_user.tap { |u| + @original_user_email = u.email + u.update!(email: 'new-email@example.com') + } + end + + def mail + @mail ||= begin + user + ActionMailer::Base.deliveries.last + end + end + + test 'email sent after changing the user email' do + assert_not_nil mail + end + + test 'content type should be set to html' do + assert_includes mail.content_type, 'text/html' + end + + test 'send email changed to the original user email' do + mail + assert_equal [@original_user_email], mail.to + end + + test 'set up sender from configuration' do + assert_equal ['test@example.com'], mail.from + end + + test 'set up sender from custom mailer defaults' do + Devise.mailer = 'Users::Mailer' + assert_equal ['custom@example.com'], mail.from + end + + test 'set up sender from custom mailer defaults with proc' do + Devise.mailer = 'Users::FromProcMailer' + assert_equal ['custom@example.com'], mail.from + end + + test 'custom mailer renders parent mailer template' do + Devise.mailer = 'Users::Mailer' + assert_present mail.body.encoded + end + + test 'set up reply to as copy from sender' do + assert_equal ['test@example.com'], mail.reply_to + end + + test 'set up reply to as different if set in defaults' do + Devise.mailer = 'Users::ReplyToMailer' + assert_equal ['custom@example.com'], mail.from + assert_equal ['custom_reply_to@example.com'], mail.reply_to + end + + test 'set up subject from I18n' do + store_translations :en, devise: { mailer: { email_changed: { subject: 'Email Has Changed' } } } do + assert_equal 'Email Has Changed', mail.subject + end + end + + test 'subject namespaced by model' do + store_translations :en, devise: { mailer: { email_changed: { user_subject: 'User Email Has Changed' } } } do + assert_equal 'User Email Has Changed', mail.subject + end + end + + test 'body should have user info' do + body = mail.body.encoded + assert_match "Hello #{@original_user_email}", body + assert_match "has been changed to #{user.email}", body + end +end + +class EmailChangedReconfirmationTest < ActionMailer::TestCase + def setup + setup_mailer + Devise.mailer = 'Devise::Mailer' + Devise.mailer_sender = 'test@example.com' + Devise.send_email_changed_notification = true + end + + def teardown + Devise.mailer = 'Devise::Mailer' + Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' + Devise.send_email_changed_notification = false + end + + def admin + @admin ||= create_admin.tap { |u| + @original_admin_email = u.email + u.update!(email: 'new-email@example.com') + } + end + + def mail + @mail ||= begin + admin + ActionMailer::Base.deliveries[-2] + end + end + + test 'send email changed to the original user email' do + mail + assert_equal [@original_admin_email], mail.to + end + + test 'body should have unconfirmed user info' do + body = mail.body.encoded + assert_match admin.email, body + assert_match "is being changed to #{admin.unconfirmed_email}", body + end +end diff --git a/test/mailers/mailer_test.rb b/test/mailers/mailer_test.rb new file mode 100644 index 0000000000..6f9f568e8a --- /dev/null +++ b/test/mailers/mailer_test.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require "test_helper" + +class MailerTest < ActionMailer::TestCase + test "pass given block to #mail call" do + class TestMailer < Devise::Mailer + def confirmation_instructions(record, token, opts = {}) + @token = token + devise_mail(record, :confirmation_instructions, opts) do |format| + format.html(content_transfer_encoding: "7bit") + end + end + end + + mail = TestMailer.confirmation_instructions(create_user, "confirmation-token") + + 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 887021b44d..5a344cbf09 100644 --- a/test/mailers/reset_password_instructions_test.rb +++ b/test/mailers/reset_password_instructions_test.rb @@ -1,7 +1,8 @@ +# frozen_string_literal: true + require 'test_helper' class ResetPasswordInstructionsTest < ActionMailer::TestCase - def setup setup_mailer Devise.mailer = 'Devise::Mailer' @@ -28,55 +29,69 @@ 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 assert_equal [user.email], mail.to end - test 'setup sender from configuration' do + test 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end - test 'setup sender from custom mailer defaults' do + test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end - test 'setup reply to as copy from sender' do + test 'set up sender from custom mailer defaults with proc' do + Devise.mailer = 'Users::FromProcMailer' + assert_equal ['custom@example.com'], mail.from + end + + test 'custom mailer renders parent mailer template' do + Devise.mailer = 'Users::Mailer' + assert_present mail.body.encoded + end + + test 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end - test 'setup subject from I18n' do - store_translations :en, :devise => { :mailer => { :reset_password_instructions => { :subject => 'Reset instructions' } } } do + test 'set up subject from I18n' do + store_translations :en, devise: { mailer: { reset_password_instructions: { subject: 'Reset instructions' } } } do assert_equal 'Reset instructions', mail.subject end end test 'subject namespaced by model' do - store_translations :en, :devise => { :mailer => { :reset_password_instructions => { :user_subject => 'User Reset Instructions' } } } do + store_translations :en, devise: { mailer: { reset_password_instructions: { user_subject: 'User Reset Instructions' } } } do assert_equal 'User Reset Instructions', mail.subject end end test 'body should have user info' do - assert_match(/#{user.email}/, mail.body.encoded) + assert_match user.email, mail.body.encoded end test 'body should have link to confirm the account' do - host = ActionMailer::Base.default_url_options[:host] - reset_url_regexp = %r{} - assert_match reset_url_regexp, mail.body.encoded + host, port = ActionMailer::Base.default_url_options.values_at :host, :port + + if mail.body.encoded =~ %r{} + 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 end test 'mailer sender accepts a proc' do - swap Devise, :mailer_sender => proc { "another@example.com" } do + swap Devise, mailer_sender: proc { "another@example.com" } do assert_equal ['another@example.com'], mail.from end end diff --git a/test/mailers/unlock_instructions_test.rb b/test/mailers/unlock_instructions_test.rb index a0cf2abd35..dff580e2eb 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,45 +35,59 @@ 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 assert_equal [user.email], mail.to end - test 'setup sender from configuration' do + test 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end - test 'setup sender from custom mailer defaults' do + test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end - test 'setup reply to as copy from sender' do + test 'set up sender from custom mailer defaults with proc' do + Devise.mailer = 'Users::FromProcMailer' + assert_equal ['custom@example.com'], mail.from + end + + test 'custom mailer renders parent mailer template' do + Devise.mailer = 'Users::Mailer' + assert_present mail.body.encoded + end + + test 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end - test 'setup subject from I18n' do - store_translations :en, :devise => { :mailer => { :unlock_instructions => { :subject => 'Yo unlock instructions' } } } do + test 'set up subject from I18n' do + store_translations :en, devise: { mailer: { unlock_instructions: { subject: 'Yo unlock instructions' } } } do assert_equal 'Yo unlock instructions', mail.subject end end test 'subject namespaced by model' do - store_translations :en, :devise => { :mailer => { :unlock_instructions => { :user_subject => 'User Unlock Instructions' } } } do + store_translations :en, devise: { mailer: { unlock_instructions: { user_subject: 'User Unlock Instructions' } } } do assert_equal 'User Unlock Instructions', mail.subject end end test 'body should have user info' do - assert_match(/#{user.email}/, mail.body.encoded) + assert_match user.email, mail.body.encoded end test 'body should have link to unlock the account' do - host = ActionMailer::Base.default_url_options[:host] - unlock_url_regexp = %r{} - assert_match unlock_url_regexp, mail.body.encoded + host, port = ActionMailer::Base.default_url_options.values_at :host, :port + + if mail.body.encoded =~ %r{} + assert_equal user.unlock_token, Devise.token_generator.digest(user.class, :unlock_token, $1) + else + flunk "expected unlock url regex to match" + end end end diff --git a/test/mapping_test.rb b/test/mapping_test.rb index 7750947678..9d60287cd4 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 @@ -35,8 +37,8 @@ def fake_request(path, params={}) assert_equal [], Devise.mappings[:skip_admin].used_routes end - test 'sign_out_via defaults to :get' do - assert_equal :get, Devise.mappings[:user].sign_out_via + test 'sign_out_via defaults to :delete' do + assert_equal :delete, Devise.mappings[:user].sign_out_via end test 'allows custom sign_out_via to be given' do @@ -50,18 +52,19 @@ def fake_request(path, params={}) end test 'has strategies depending on the model declaration' do - assert_equal [:rememberable, :token_authenticatable, :database_authenticatable], Devise.mappings[:user].strategies + assert_equal [:rememberable, :database_authenticatable], Devise.mappings[:user].strategies assert_equal [:database_authenticatable], Devise.mappings[:admin].strategies end test 'has no input strategies depending on the model declaration' do - assert_equal [:rememberable, :token_authenticatable], Devise.mappings[:user].no_input_strategies + assert_equal [:rememberable], Devise.mappings[:user].no_input_strategies assert_equal [], Devise.mappings[:admin].no_input_strategies end test 'find scope for a given object' do assert_equal :user, Devise::Mapping.find_scope!(User) assert_equal :user, Devise::Mapping.find_scope!(:user) + assert_equal :user, Devise::Mapping.find_scope!("user") assert_equal :user, Devise::Mapping.find_scope!(User.new) end @@ -70,6 +73,12 @@ def fake_request(path, params={}) assert_equal :user, Devise::Mapping.find_scope!(Class.new(User).new) end + test 'find scope uses devise_scope' do + user = User.new + def user.devise_scope; :special_scope; end + assert_equal :special_scope, Devise::Mapping.find_scope!(user) + end + test 'find scope raises an error if cannot be found' do assert_raise RuntimeError do Devise::Mapping.find_scope!(String) @@ -110,12 +119,12 @@ def fake_request(path, params={}) assert mapping.lockable? assert_not mapping.omniauthable? end - + test 'find mapping by path' do assert_raise RuntimeError do Devise::Mapping.find_by_path!('/accounts/facebook/callback') end - + assert_nothing_raised do Devise::Mapping.find_by_path!('/:locale/accounts/login') end @@ -123,5 +132,5 @@ def fake_request(path, params={}) assert_nothing_raised do Devise::Mapping.find_by_path!('/accounts/facebook/callback', :path) end - end + end end diff --git a/test/models/authenticatable_test.rb b/test/models/authenticatable_test.rb index 132be644f5..4d58b1e492 100644 --- a/test/models/authenticatable_test.rb +++ b/test/models/authenticatable_test.rb @@ -1,7 +1,50 @@ +# 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, 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.find_or_initialize_with_errors([:email], attributes) + end end -end \ No newline at end of file +end diff --git a/test/models/confirmable_test.rb b/test/models/confirmable_test.rb index 3d93d6dba0..31a955e727 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 @@ -23,38 +36,32 @@ def setup test 'should confirm a user by updating confirmed at' do user = create_user assert_nil user.confirmed_at - assert user.confirm! + assert user.confirm assert_not_nil user.confirmed_at end - test 'should clear confirmation token while confirming a user' do - user = create_user - assert_present user.confirmation_token - user.confirm! - assert_nil user.confirmation_token - end - test 'should verify whether a user is confirmed or not' do assert_not new_user.confirmed? user = create_user assert_not user.confirmed? - user.confirm! + user.confirm assert user.confirmed? end test 'should not confirm a user already confirmed' do user = create_user - assert user.confirm! + assert user.confirm assert_blank user.errors[:email] - assert_not user.confirm! + assert_not user.confirm assert_equal "was already confirmed, please try signing in", user.errors[:email].join end - test 'should find and confirm a user automatically' do + test 'should find and confirm a user automatically based on the raw token' do user = create_user - confirmed_user = User.confirm_by_token(user.confirmation_token) - assert_equal confirmed_user, user + raw = user.raw_confirmation_token + confirmed_user = User.confirm_by_token(raw) + assert_equal user, confirmed_user assert user.reload.confirmed? end @@ -67,21 +74,49 @@ def setup test 'should return a new record with errors when a blank token is given' do confirmed_user = User.confirm_by_token('') assert_not confirmed_user.persisted? - assert_equal "can't be blank", confirmed_user.errors[:confirmation_token].join + 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 user = create_user user.confirmed_at = Time.now user.save - confirmed_user = User.confirm_by_token(user.confirmation_token) + confirmed_user = User.confirm_by_token(user.raw_confirmation_token) assert confirmed_user.confirmed? assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join end + test 'should show error when a token has already been used' do + user = create_user + raw = user.raw_confirmation_token + User.confirm_by_token(raw) + assert user.reload.confirmed? + + confirmed_user = User.confirm_by_token(raw) + assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join + end + test 'should send confirmation instructions by email' do assert_email_sent "mynewuser@example.com" do - create_user :email => "mynewuser@example.com" + create_user email: "mynewuser@example.com" end end @@ -104,19 +139,37 @@ def setup end end + test 'should skip confirmation e-mail without confirming if skip_confirmation_notification! is invoked' do + user = new_user + user.skip_confirmation_notification! + + assert_email_not_sent do + user.save! + assert_not user.confirmed? + end + end + + test 'should not send confirmation when no email is provided' do + assert_email_not_sent do + user = new_user + user.email = '' + user.save(validate: false) + end + end + 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 + confirmation_user = User.send_confirmation_instructions(email: user.email) + 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") + confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com") assert_not confirmation_user.persisted? end test 'should add error to new user email if no email was found' do - confirmation_user = User.send_confirmation_instructions(:email => "invalid@example.com") + confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com") assert confirmation_user.errors[:email] assert_equal "not found", confirmation_user.errors[:email].join end @@ -124,7 +177,7 @@ def setup test 'should send email instructions for the user confirm its email' do user = create_user assert_email_sent user.email do - User.send_confirmation_instructions(:email => user.email) + User.send_confirmation_instructions(email: user.email) end end @@ -136,7 +189,7 @@ def setup assert_not_nil user.reload.confirmation_token end - test 'should not resend email instructions if the user change his email' do + test 'should not resend email instructions if the user change their email' do user = create_user user.email = 'new_test@example.com' assert_email_not_sent do @@ -146,26 +199,27 @@ def setup test 'should not reset confirmation status or token when updating email' do user = create_user - user.confirm! + original_token = user.confirmation_token + user.confirm user.email = 'new_test@example.com' user.save! user.reload assert user.confirmed? - assert_nil user.confirmation_token + assert_equal original_token, user.confirmation_token end test 'should not be able to send instructions if the user is already confirmed' do user = create_user - user.confirm! - assert_not user.resend_confirmation_token + user.confirm + assert_not user.resend_confirmation_instructions assert user.confirmed? assert_equal 'was already confirmed, please try signing in', user.errors[:email].join end test 'confirm time should fallback to devise confirm in default configuration' do - swap Devise, :allow_unconfirmed_access_for => 1.day do - user = new_user + swap Devise, allow_unconfirmed_access_for: 1.day do + user = create_user user.confirmation_sent_at = 2.days.ago assert_not user.active_for_authentication? @@ -175,7 +229,7 @@ def setup end test 'should be active when confirmation sent at is not overpast' do - swap Devise, :allow_unconfirmed_access_for => 5.days do + swap Devise, allow_unconfirmed_access_for: 5.days do Devise.allow_unconfirmed_access_for = 5.days user = create_user @@ -192,7 +246,7 @@ def setup assert_not user.confirmed? assert_not user.active_for_authentication? - user.confirm! + user.confirm assert user.confirmed? assert user.active_for_authentication? end @@ -200,10 +254,28 @@ def setup test 'should not be active when confirm in is zero' do Devise.allow_unconfirmed_access_for = 0.days user = create_user - user.confirmation_sent_at = Date.today + user.confirmation_sent_at = Time.zone.today 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 + swap Devise, allow_unconfirmed_access_for: nil do + user = create_user + user.confirmation_sent_at = Time.zone.today + assert user.active_for_authentication? + end + end + test 'should not be active without confirmation' do user = create_user user.confirmation_sent_at = nil @@ -219,28 +291,38 @@ def setup assert user.reload.active_for_authentication? end + test 'should not break when a user tries to reset their password in the case where confirmation is not required and confirm_within is set' do + swap Devise, confirm_within: 3.days do + user = create_user + user.instance_eval { def confirmation_required?; false end } + user.confirmation_sent_at = nil + user.save + assert user.reload.confirm + end + end + test 'should find a user to send email instructions for the user confirm its email by authentication_keys' do - swap Devise, :authentication_keys => [:username, :email] do + 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 + confirm_user = User.send_confirmation_instructions(email: user.email, username: user.username) + assert_equal user, confirm_user end end test 'should require all confirmation_keys' do - swap Devise, :confirmation_keys => [:username, :email] do + swap Devise, confirmation_keys: [:username, :email] do user = create_user - confirm_user = User.send_confirmation_instructions(:email => user.email) + confirm_user = User.send_confirmation_instructions(email: user.email) assert_not confirm_user.persisted? - assert_equal "can't be blank", confirm_user.errors[:username].join + assert confirm_user.errors.added?(:username, :blank) end end 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.confirmation_token) - assert_equal confirmed_user, user + confirmed_user = User.confirm_by_token(user.raw_confirmation_token) + assert_equal user, confirmed_user user.reload.confirmed? end @@ -249,117 +331,182 @@ def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at) end test 'should accept confirmation email token after 2 days when expiration is set to 3 days' do - swap Devise, :confirm_within => 3.days do + swap Devise, confirm_within: 3.days do assert confirm_user_by_token_with_confirmation_sent_at(2.days.ago) end end 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 + swap Devise, confirm_within: 3.days do assert_not confirm_user_by_token_with_confirmation_sent_at(4.days.ago) end end - test 'should generate a new token if the previous one has expired' do - swap Devise, :confirm_within => 3.days do + test 'do not generate a new token on resend' do + user = create_user + old = user.confirmation_token + user = User.find(user.id) + user.resend_confirmation_instructions + assert_equal user.confirmation_token, old + end + + test 'generate a new token after first has expired' do + swap Devise, confirm_within: 3.days do user = create_user - user.update_attribute(:confirmation_sent_at, 4.days.ago) old = user.confirmation_token - user.resend_confirmation_token + user.update_attribute(:confirmation_sent_at, 4.days.ago) + user = User.find(user.id) + user.resend_confirmation_instructions assert_not_equal user.confirmation_token, old end end + + test 'should call after_confirmation if confirmed' do + user = create_user + user.define_singleton_method :after_confirmation do + self.username = self.username.to_s + 'updated' + end + old = user.username + assert user.confirm + assert_not_equal user.username, old + end + + test 'should not call after_confirmation if not confirmed' do + user = create_user + assert user.confirm + user.define_singleton_method :after_confirmation do + self.username = self.username.to_s + 'updated' + end + old = user.username + 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) + assert_not admin.confirm(ensure_valid: true) + end end class ReconfirmableTest < ActiveSupport::TestCase test 'should not worry about validations on confirm even with reconfirmable' do admin = create_admin admin.reset_password_token = "a" - assert admin.confirm! + assert admin.confirm end test 'should generate confirmation token after changing email' do admin = create_admin - assert admin.confirm! - assert_nil admin.confirmation_token - assert admin.update_attributes(:email => 'new_test@example.com') - assert_not_nil admin.confirmation_token + assert admin.confirm + residual_token = admin.confirmation_token + assert admin.update(email: 'new_test@example.com') + assert_not_equal residual_token, admin.confirmation_token end - test 'should not generate confirmation token if skipping reconfirmation after changing email' do + test 'should not regenerate confirmation token or require reconfirmation if skipping reconfirmation after changing email' do admin = create_admin - assert admin.confirm! + original_token = admin.confirmation_token + assert admin.confirm admin.skip_reconfirmation! - assert admin.update_attributes(:email => 'new_test@example.com') - assert_nil admin.confirmation_token + assert admin.update(email: 'new_test@example.com') + assert admin.confirmed? + assert_not admin.pending_reconfirmation? + assert_equal original_token, admin.confirmation_token end + test 'should skip sending reconfirmation email when email is changed and skip_confirmation_notification! is invoked' do + admin = create_admin + admin.skip_confirmation_notification! + + assert_email_not_sent do + 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.confirm + 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 test 'should send confirmation instructions by email after changing email' do admin = create_admin - assert admin.confirm! + 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 + + 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(email: 'new_test@example.com') + end + assert_match "new_test@example.com", ActionMailer::Base.deliveries.last.body.encoded end test 'should not send confirmation by email after changing password' do admin = create_admin - assert admin.confirm! + assert admin.confirm + assert_email_not_sent do + assert admin.update(password: 'newpass', password_confirmation: 'newpass') + end + end + + test 'should not send confirmation by email after changing to a blank email' do + admin = create_admin + assert admin.confirm assert_email_not_sent do - assert admin.update_attributes(:password => 'newpass', :password_confirmation => 'newpass') + admin.email = '' + admin.save(validate: false) end end 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.confirm + 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.confirm + assert admin.update(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email - assert admin.confirm! + assert admin.confirm assert_equal 'new_test@example.com', admin.email end 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.confirm + 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') - confirmation_admin = Admin.send_confirmation_instructions(:email => admin.unconfirmed_email) - assert_equal confirmation_admin, admin + assert admin.confirm + assert admin.update(email: 'new_test@example.com') + confirmation_admin = Admin.send_confirmation_instructions(email: admin.unconfirmed_email) + 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") + confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com") assert_not confirmation_admin.persisted? end test 'should add error to new admin email if no email or unconfirmed_email was found' do - confirmation_admin = Admin.send_confirmation_instructions(:email => "invalid@email.com") + confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com") assert confirmation_admin.errors[:email] assert_equal "not found", confirmation_admin.errors[:email].join end @@ -368,24 +515,63 @@ class ReconfirmableTest < ActiveSupport::TestCase admin = create_admin admin.unconfirmed_email = "new_test@email.com" assert admin.save - admin = Admin.find_by_unconfirmed_email_with_errors(:email => "new_test@email.com") + admin = Admin.find_by_unconfirmed_email_with_errors(email: "new_test@email.com") assert admin.persisted? end test 'required_fields should contain the fields that Devise uses' do - assert_same_content Devise::Models::Confirmable.required_fields(User), [ - :confirmation_sent_at, + assert_equal [ :confirmation_token, - :confirmed_at - ] + :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_same_content Devise::Models::Confirmable.required_fields(Admin), [ - :confirmation_sent_at, + 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_not admin.pending_reconfirmation? + end + + test 'should not require reconfirmation after creating a record with #save called in callback' do + class Admin::WithSaveInCallback < Admin + after_create :save + end + + admin = Admin::WithSaveInCallback.create(valid_attributes.except(:username)) + assert_not admin.pending_reconfirmation? + end + + test 'should require reconfirmation after creating a record and updating the email' do + admin = create_admin + assert_not admin.instance_variable_get(:@bypass_confirmation_postpone) + admin.email = "new_test@email.com" + admin.save + assert admin.pending_reconfirmation? + end + + test 'should notify previous email on email change when configured' do + swap Devise, send_email_changed_notification: true do + admin = create_admin + original_email = admin.email + + assert_difference 'ActionMailer::Base.deliveries.size', 2 do + 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 + + assert_email_not_sent do + assert admin.confirm + end + end end end diff --git a/test/models/database_authenticatable_test.rb b/test/models/database_authenticatable_test.rb index 638eaf39f4..909e010458 100644 --- a/test/models/database_authenticatable_test.rb +++ b/test/models/database_authenticatable_test.rb @@ -1,62 +1,128 @@ +# frozen_string_literal: true + require 'test_helper' +require 'test_models' require 'digest/sha1' class DatabaseAuthenticatableTest < ActiveSupport::TestCase + def setup + setup_mailer + end + test 'should downcase case insensitive keys when saving' do # case_insensitive_keys is set to :email by default. email = 'Foo@Bar.com' - user = new_user(:email => email) + user = new_user(email: email) assert_equal email, user.email user.save! assert_equal email.downcase, user.email end + test 'should downcase case insensitive keys that refer to virtual attributes when saving' do + email = 'Foo@Bar1.com' + confirmation = 'Foo@Bar1.com' + attributes = valid_attributes(email: email, email_confirmation: confirmation) + user = UserWithVirtualAttributes.new(attributes) + + assert_equal confirmation, user.email_confirmation + user.save! + assert_equal confirmation.downcase, user.email_confirmation + end + + test 'should not mutate value assigned to case insensitive key' do + email = 'Foo@Bar.com' + original_email = email.dup + user = new_user(email: email) + + user.save! + assert_equal original_email, email + end + test 'should remove whitespace from strip whitespace keys when saving' do # strip_whitespace_keys is set to :email by default. email = ' foo@bar.com ' - user = new_user(:email => email) + user = new_user(email: email) assert_equal email, user.email user.save! assert_equal email.strip, user.email end + test 'should not mutate value assigned to string whitespace key' do + email = ' foo@bar.com ' + original_email = email.dup + user = new_user(email: email) + + user.save! + assert_equal original_email, email + end + + test "doesn't throw exception when globally configured strip_whitespace_keys are not present on a model" do + swap Devise, strip_whitespace_keys: [:fake_key] do + assert_nothing_raised { create_user } + end + end + + test "doesn't throw exception when globally configured case_insensitive_keys are not present on a model" do + swap Devise, case_insensitive_keys: [:fake_key] do + assert_nothing_raised { create_user } + end + end + test "param filter should not convert booleans and integer to strings" do - conditions = { 'login' => 'foo@bar.com', "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) } - conditions = Devise::ParamFilter.new([], []).filter(conditions) - assert_equal( { 'login' => 'foo@bar.com', "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => "1..10" }, conditions) + conditions = { "login" => "foo@bar.com", "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) } + conditions = Devise::ParameterFilter.new([], []).filter(conditions) + assert_equal( { "login" => "foo@bar.com", "bool1" => "true", "bool2" => "false", "fixnum" => "123", "will_be_converted" => "1..10" }, conditions) + end + + test 'param filter should filter case_insensitive_keys as insensitive' do + conditions = {'insensitive' => 'insensitive_VAL', 'sensitive' => 'sensitive_VAL'} + conditions = Devise::ParameterFilter.new(['insensitive'], []).filter(conditions) + assert_equal( {'insensitive' => 'insensitive_val', 'sensitive' => 'sensitive_VAL'}, conditions ) end - test "param filter should not convert regular expressions to strings" do - conditions = { "regexp" => /expression/ } - conditions = Devise::ParamFilter.new([], []).filter(conditions) - assert_equal( { "regexp" => /expression/ }, conditions) + test 'param filter should filter strip_whitespace_keys stripping whitespaces' do + conditions = {'strip_whitespace' => ' strip_whitespace_val ', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '} + conditions = Devise::ParameterFilter.new([], ['strip_whitespace']).filter(conditions) + 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 encrypted password while setting password' do + test 'should generate a hashed password while setting password' do user = new_user assert_present user.encrypted_password end - test 'allow authenticatable_salt to work even with nil encrypted password' do + test 'should support custom hashing methods' do + user = UserWithCustomHashing.new(password: '654321') + assert_equal '123456', user.encrypted_password + end + + test 'allow authenticatable_salt to work even with nil hashed password' do user = User.new user.encrypted_password = nil assert_nil user.authenticatable_salt end - test 'should not generate encrypted password if password is blank' do - assert_blank new_user(:password => nil).encrypted_password - assert_blank new_user(:password => '').encrypted_password + test 'should not generate a hashed password if password is blank' do + assert_blank new_user(password: nil).encrypted_password + assert_blank new_user(password: '').encrypted_password end - test 'should encrypt password again if password has changed' do + test 'should hash password again if password has changed' do user = create_user encrypted_password = user.encrypted_password user.password = user.password_confirmation = 'new_password' @@ -83,107 +149,162 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase 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 user = create_user - assert user.update_with_password(:current_password => '12345678', - :password => 'pass4321', :password_confirmation => 'pass4321') - assert user.reload.valid_password?('pass4321') - end - - test 'should update password with valid current password and :as option' do - user = create_user - assert user.update_with_password(:current_password => '12345678', - :password => 'pass4321', :password_confirmation => 'pass4321', :as => :admin) + assert user.update_with_password(current_password: '12345678', + password: 'pass4321', password_confirmation: 'pass4321') assert user.reload.valid_password?('pass4321') end test 'should add an error to current password when it is invalid' do user = create_user - assert_not user.update_with_password(:current_password => 'other', - :password => 'pass4321', :password_confirmation => 'pass4321') + 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 end test 'should add an error to current password when it is blank' do user = create_user - assert_not user.update_with_password(:password => 'pass4321', - :password_confirmation => '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? - assert_not 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 user = create_user - assert user.update_with_password(:current_password => '12345678', :email => "new@example.com") + assert user.update_with_password(current_password: '12345678', email: "new@example.com") assert_equal "new@example.com", user.email end test 'should not update password with invalid confirmation' do user = create_user - assert_not user.update_with_password(:current_password => '12345678', - :password => 'pass4321', :password_confirmation => 'other') + 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 - assert_not user.update_with_password(:current_password => '12345678', - :password => 'pass4321', :password_confirmation => 'other') + assert_not user.update_with_password(current_password: '12345678', + password: 'pass4321', password_confirmation: 'other') assert user.password.blank? assert user.password_confirmation.blank? end test 'should update the user without password' do user = create_user - user.update_without_password(:email => 'new@example.com') + user.update_without_password(email: 'new@example.com') assert_equal 'new@example.com', user.email end - test 'should update the user without password with :as option' do + test 'should not update password without password' do user = create_user - user.update_without_password(:email => 'new@example.com', :as => :admin) - assert_equal 'new@example.com', user.email + user.update_without_password(password: 'pass4321', password_confirmation: 'pass4321') + assert_not user.reload.valid_password?('pass4321') + assert user.valid_password?('12345678') end - test 'should not update password without password' do + test 'should destroy user if current password is valid' do user = create_user - user.update_without_password(:password => 'pass4321', :password_confirmation => 'pass4321') - assert !user.reload.valid_password?('pass4321') - assert user.valid_password?('12345678') + assert user.destroy_with_password('12345678') + assert_not user.persisted? + end + + test 'should not destroy user with invalid password' do + user = create_user + 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 + assert_not user.destroy_with_password(nil) + assert user.persisted? + 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(password: 'newpass', password_confirmation: 'newpass') + end + end + + test 'should notify previous email on email change when configured' do + swap Devise, send_email_changed_notification: true do + user = create_user + original_email = user.email + assert_email_sent original_email do + assert user.update(email: 'new-email@example.com') + end + assert_match original_email, ActionMailer::Base.deliveries.last.body.encoded + end + end + + test 'should notify email on password change when configured' do + swap Devise, send_password_change_notification: true do + user = create_user + assert_email_sent user.email do + 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 = User.create(:email => "HEllO@example.com", :password => "123456") - user = User.create(:email => "HEllO@example.com", :password => "123456") - assert !user.valid? + User.create(email: "HEllO@example.com", password: "123456") + user = User.create(email: "HEllO@example.com", password: "123456") + assert_not user.valid? end - test 'required_fiels should be encryptable_password and the email field by default' do - assert_same_content Devise::Models::DatabaseAuthenticatable.required_fields(User), [ - :email, - :encrypted_password - ] + test 'required_fields should be encryptable_password and the email field by default' do + 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_same_content Devise::Models::DatabaseAuthenticatable.required_fields(User), [ + swap Devise, authentication_keys: [:login] do + 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 18ea2edda9..b1d8cab0d4 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 @@ -7,36 +9,73 @@ def setup test "should respect maximum attempts configuration" do user = create_user - user.confirm! - swap Devise, :maximum_attempts => 2 do - 3.times { user.valid_for_authentication?{ false } } + user.confirm + swap Devise, maximum_attempts: 2 do + 2.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end end - test "should increment failed_attempts on successfull validation if the user is already locked" do + test "should increment failed_attempts on successful validation if the user is already locked" do user = create_user - user.confirm! + user.confirm - swap Devise, :maximum_attempts => 2 do - 3.times { user.valid_for_authentication?{ false } } + swap Devise, maximum_attempts: 2 do + 2.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end user.valid_for_authentication?{ true } - assert_equal 4, user.reload.failed_attempts + assert_equal 3, user.reload.failed_attempts end test "should not touch failed_attempts if lock_strategy is none" do user = create_user - user.confirm! - swap Devise, :lock_strategy => :none, :maximum_attempts => 2 do + 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! @@ -53,13 +92,13 @@ def setup test "active_for_authentication? should be the opposite of locked?" do user = create_user - user.confirm! + user.confirm assert user.active_for_authentication? user.lock_access! assert_not user.active_for_authentication? end - test "should unlock a user by cleaning locked_at, falied_attempts and unlock_token" do + test "should unlock a user by cleaning locked_at, failed_attempts and unlock_token" do user = create_user user.lock_access! assert_not_nil user.reload.locked_at @@ -77,7 +116,7 @@ def setup end test "should unlock user after unlock_in period" do - swap Devise, :unlock_in => 3.hours do + swap Devise, unlock_in: 3.hours do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? @@ -88,7 +127,7 @@ def setup end test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do - swap Devise, :unlock_strategy => :email do + swap Devise, unlock_strategy: :email do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? @@ -108,13 +147,13 @@ 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 test "should not generate unlock_token when :email is not an unlock strategy" do - swap Devise, :unlock_strategy => :time do + swap Devise, unlock_strategy: :time do user = create_user user.lock_access! assert_nil user.unlock_token @@ -122,7 +161,7 @@ def setup end test "should send email with unlock instructions when :email is an unlock strategy" do - swap Devise, :unlock_strategy => :email do + swap Devise, unlock_strategy: :email do user = create_user assert_email_sent do user.lock_access! @@ -130,8 +169,26 @@ def setup end end + test "doesn't send email when you pass option send_instructions to false" do + swap Devise, unlock_strategy: :email do + user = create_user + assert_email_not_sent do + user.lock_access! send_instructions: false + end + end + end + + test "sends email when you pass options other than send_instructions" do + swap Devise, unlock_strategy: :email do + user = create_user + assert_email_sent do + user.lock_access! foo: :bar, bar: :foo + end + end + end + test "should not send email with unlock instructions when :email is not an unlock strategy" do - swap Devise, :unlock_strategy => :time do + swap Devise, unlock_strategy: :time do user = create_user assert_email_not_sent do user.lock_access! @@ -139,11 +196,11 @@ def setup end end - test 'should find and unlock a user automatically' do + test 'should find and unlock a user automatically based on raw token' do user = create_user - user.lock_access! - locked_user = User.unlock_access_by_token(user.unlock_token) - assert_equal locked_user, user + raw = user.send_unlock_instructions + locked_user = User.unlock_access_by_token(raw) + assert_equal user, locked_user assert_not user.reload.access_locked? end @@ -156,54 +213,63 @@ def setup test 'should return a new record with errors when a blank token is given' do locked_user = User.unlock_access_by_token('') assert_not locked_user.persisted? - assert_equal "can't be blank", locked_user.errors[:unlock_token].join + 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 + unlock_user = User.send_unlock_instructions(email: user.email) + 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") + unlock_user = User.send_unlock_instructions(email: "invalid@example.com") assert_not unlock_user.persisted? end test 'should add error to new user email if no email was found' do - unlock_user = User.send_unlock_instructions(:email => "invalid@example.com") + unlock_user = User.send_unlock_instructions(email: "invalid@example.com") assert_equal 'not found', unlock_user.errors[:email].join end test 'should find a user to send unlock instructions by authentication_keys' do - swap Devise, :authentication_keys => [:username, :email] do + 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 + unlock_user = User.send_unlock_instructions(email: user.email, username: user.username) + assert_equal user, unlock_user end end test 'should require all unlock_keys' do - swap Devise, :unlock_keys => [:username, :email] do - user = create_user - unlock_user = User.send_unlock_instructions(:email => user.email) - assert_not unlock_user.persisted? - assert_equal "can't be blank", unlock_user.errors[:username].join - end + swap Devise, unlock_keys: [:username, :email] do + user = create_user + unlock_user = User.send_unlock_instructions(email: user.email) + 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 - assert_not user.resend_unlock_token + 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 + assert_not user.resend_unlock_instructions + assert_not user.access_locked? + assert_equal 'was not locked', user.errors[:username].join + end + end + test 'should unlock account if lock has expired and increase attempts on failure' do - swap Devise, :unlock_in => 1.minute do + swap Devise, unlock_in: 1.minute do user = create_user - user.confirm! + user.confirm user.failed_attempts = 2 user.locked_at = 2.minutes.ago @@ -214,9 +280,9 @@ def setup end test 'should unlock account if lock has expired on success' do - swap Devise, :unlock_in => 1.minute do + swap Devise, unlock_in: 1.minute do user = create_user - user.confirm! + user.confirm user.failed_attempts = 2 user.locked_at = 2.minutes.ago @@ -228,36 +294,96 @@ def setup end 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_same_content Devise::Models::Lockable.required_fields(User), [ - :failed_attempts, - :locked_at, - :unlock_token - ] + swap Devise, unlock_strategy: :both do + swap Devise, lock_strategy: :failed_attempts do + assert_equal [ + :failed_attempts, + :locked_at, + :unlock_token + ], Devise::Models::Lockable.required_fields(User) end end end 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_same_content Devise::Models::Lockable.required_fields(User), [ - :failed_attempts, - :locked_at - ] + swap Devise, unlock_strategy: :time do + swap Devise, lock_strategy: :failed_attempts do + assert_equal [ + :failed_attempts, + :locked_at + ], Devise::Models::Lockable.required_fields(User) end end end 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_same_content Devise::Models::Lockable.required_fields(User), [ - :failed_attempts, - :unlock_token - ] + swap Devise, unlock_strategy: :email do + swap Devise, lock_strategy: :failed_attempts do + assert_equal [ + :failed_attempts, + :unlock_token + ], Devise::Models::Lockable.required_fields(User) end end end + + test 'should not return a locked unauthenticated message if in paranoid mode' do + swap Devise, paranoid: :true do + user = create_user + user.failed_attempts = Devise.maximum_attempts + 1 + user.lock_access! + + assert_equal :invalid, user.unauthenticated_message + end + end + + test 'should return last attempt message if user made next-to-last attempt of password entering' do + swap Devise, last_attempt_warning: true, lock_strategy: :failed_attempts do + user = create_user + user.failed_attempts = Devise.maximum_attempts - 2 + assert_equal :invalid, user.unauthenticated_message + + user.failed_attempts = Devise.maximum_attempts - 1 + assert_equal :last_attempt, user.unauthenticated_message + + user.failed_attempts = Devise.maximum_attempts + assert_equal :locked, user.unauthenticated_message + end + end + + test 'should not return last attempt message if last_attempt_warning is disabled' do + swap Devise, last_attempt_warning: false, lock_strategy: :failed_attempts do + user = create_user + user.failed_attempts = Devise.maximum_attempts - 1 + assert_equal :invalid, user.unauthenticated_message + end + end + + test 'should return locked message if user was programatically locked' do + user = create_user + user.lock_access! + assert_equal :locked, user.unauthenticated_message + end + + test 'unlock_strategy_enabled? should return true for both, email, and time strategies if :both is used' do + swap Devise, unlock_strategy: :both do + user = create_user + assert_equal true, user.unlock_strategy_enabled?(:both) + assert_equal true, user.unlock_strategy_enabled?(:time) + assert_equal true, user.unlock_strategy_enabled?(:email) + assert_equal false, user.unlock_strategy_enabled?(:none) + assert_equal false, user.unlock_strategy_enabled?(:an_undefined_strategy) + end + end + + test 'unlock_strategy_enabled? should return true only for the configured strategy' do + swap Devise, unlock_strategy: :email do + user = create_user + assert_equal false, user.unlock_strategy_enabled?(:both) + assert_equal false, user.unlock_strategy_enabled?(:time) + assert_equal true, user.unlock_strategy_enabled?(:email) + assert_equal false, user.unlock_strategy_enabled?(:none) + assert_equal false, user.unlock_strategy_enabled?(:an_undefined_strategy) + end + end end diff --git a/test/models/omniauthable_test.rb b/test/models/omniauthable_test.rb index 13a89a5964..22cea976cf 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_same_content 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 9907fc26dd..b2234ac6ac 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,29 +18,75 @@ 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 test 'should reset password and password confirmation from params' do user = create_user - user.reset_password!('123456789', '987654321') + user.reset_password('123456789', '987654321') assert_equal '123456789', user.password assert_equal '987654321', user.password_confirmation end test 'should reset password and save the record' do - assert create_user.reset_password!('123456789', '123456789') + assert create_user.reset_password('123456789', '123456789') + end + + test 'should clear reset password token while resetting the password' do + user = create_user + assert_nil user.reset_password_token + + user.send_reset_password_instructions + assert_present user.reset_password_token + assert user.reset_password('123456789', '123456789') + assert_nil user.reset_password_token + end + + test 'should not clear reset password token for new user' do + user = new_user + assert_nil user.reset_password_token + + user.send_reset_password_instructions + assert_present user.reset_password_token + + user.save + assert_present user.reset_password_token end - test 'should clear reset password token while reseting the password' do + test 'should clear reset password token if changing password' do user = create_user assert_nil user.reset_password_token user.send_reset_password_instructions assert_present user.reset_password_token - assert user.reset_password!('123456789', '123456789') + user.password = "123456678" + user.password_confirmation = "123456678" + user.save! + assert_nil user.reset_password_token + end + + test 'should clear reset password token if changing email' do + user = create_user + assert_nil user.reset_password_token + + user.send_reset_password_instructions + assert_present user.reset_password_token + user.email = "another@example.com" + user.save! + assert_nil user.reset_password_token + end + + test 'should clear reset password successfully even if there is no email' do + user = create_user_without_email + assert_nil user.reset_password_token + + user.send_reset_password_instructions + assert_present user.reset_password_token + user.password = "123456678" + user.password_confirmation = "123456678" + user.save! assert_nil user.reset_password_token end @@ -46,14 +94,14 @@ def setup user = create_user user.send_reset_password_instructions assert_present user.reset_password_token - assert_not 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) - assert_not 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 @@ -67,126 +115,118 @@ 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 + reset_password_user = User.send_reset_password_instructions(email: user.email) + 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") + reset_password_user = User.send_reset_password_instructions(email: "invalid@example.com") assert_not reset_password_user.persisted? assert_equal "not found", reset_password_user.errors[:email].join end test 'should find a user to send instructions by authentication_keys' do - swap Devise, :authentication_keys => [:username, :email] do + 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 + reset_password_user = User.send_reset_password_instructions(email: user.email, username: user.username) + 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) - assert_not 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 user = create_user token = user.reset_password_token - User.send_reset_password_instructions(:email => user.email) + User.send_reset_password_instructions(email: user.email) assert_not_equal token, user.reload.reset_password_token end - test 'should send email instructions to the user reset his password' do + test 'should send email instructions to the user reset their password' do user = create_user assert_email_sent do - User.send_reset_password_instructions(:email => user.email) + User.send_reset_password_instructions(email: user.email) end end - test 'should find a user to reset his password based on reset_password_token' do + test 'should find a user to reset their password based on the raw token' do user = create_user - user.send :generate_reset_password_token! + raw = user.send_reset_password_instructions - reset_password_user = User.reset_password_by_token(:reset_password_token => user.reset_password_token) - assert_equal reset_password_user, user + reset_password_user = User.reset_password_by_token(reset_password_token: raw) + 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') + reset_password_user = User.reset_password_by_token(reset_password_token: 'invalid_token') 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 => '') + reset_password_user = User.reset_password_by_token(reset_password_token: '') assert_not reset_password_user.persisted? - assert_match "can't be blank", reset_password_user.errors[:reset_password_token].join + assert reset_password_user.errors.added?(:reset_password_token, :blank) end test 'should return a new record with errors if password is blank' do user = create_user - user.send :generate_reset_password_token! + raw = user.send_reset_password_instructions - reset_password_user = User.reset_password_by_token(:reset_password_token => user.reset_password_token, :password => '') + reset_password_user = User.reset_password_by_token(reset_password_token: raw, password: '') assert_not reset_password_user.errors.empty? - assert_match "can't be blank", reset_password_user.errors[:password].join + assert reset_password_user.errors.added?(:password, :blank) + assert_equal raw, reset_password_user.reset_password_token + end + + test 'should return a new record with errors if password is not provided' do + user = create_user + raw = user.send_reset_password_instructions + + reset_password_user = User.reset_password_by_token(reset_password_token: raw) + 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 test 'should reset successfully user password given the new password and confirmation' do user = create_user old_password = user.password - user.send :generate_reset_password_token! + raw = user.send_reset_password_instructions - User.reset_password_by_token( - :reset_password_token => user.reset_password_token, - :password => 'new_password', - :password_confirmation => 'new_password' + reset_password_user = User.reset_password_by_token( + reset_password_token: raw, + password: 'new_password', + password_confirmation: 'new_password' ) - user.reload + assert_nil reset_password_user.reset_password_token + user.reload assert_not user.valid_password?(old_password) assert user.valid_password?('new_password') - end - - test 'should not reset reset password token during reset_password_within time' do - swap Devise, :reset_password_within => 1.hour do - user = create_user - user.send_reset_password_instructions - 3.times do - token = user.reset_password_token - user.send_reset_password_instructions - assert_equal token, user.reset_password_token - end - end - end - - test 'should reset reset password token after reset_password_within time' do - swap Devise, :reset_password_within => 1.hour do - user = create_user - user.reset_password_sent_at = 2.days.ago - token = user.reset_password_token - user.send_reset_password_instructions - assert_not_equal token, user.reset_password_token - end + assert_nil user.reset_password_token end test 'should not reset password after reset_password_within time' do - swap Devise, :reset_password_within => 1.hour do + swap Devise, reset_password_within: 1.hour do user = create_user + raw = user.send_reset_password_instructions + old_password = user.password - user.send :generate_reset_password_token! user.reset_password_sent_at = 2.days.ago user.save! reset_password_user = User.reset_password_by_token( - :reset_password_token => user.reset_password_token, - :password => 'new_password', - :password_confirmation => 'new_password' + reset_password_token: raw, + password: 'new_password', + password_confirmation: 'new_password' ) user.reload @@ -197,9 +237,27 @@ def setup end test 'required_fields should contain the fields that Devise uses' do - assert_same_content 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, 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 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 + assert_nil User.with_reset_password_token('random-token') end + end diff --git a/test/models/registerable_test.rb b/test/models/registerable_test.rb index fe15728989..df5cf6fcf1 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_same_content 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 1a185f6f1f..8b83172120 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 @@ -13,6 +15,19 @@ def create_resource user = create_user user.expects(:valid?).never user.remember_me! + assert user.remember_created_at + end + + test 'remember_me should not generate a new token if valid token exists' do + user = create_user + user.singleton_class.send(:attr_accessor, :remember_token) + User.to_adapter.expects(:find_first).returns(nil) + + user.remember_me! + existing_token = user.remember_token + + user.remember_me! + assert_equal existing_token, user.remember_token end test 'forget_me should not clear remember token if using salt' do @@ -22,153 +37,148 @@ def create_resource user.forget_me! end + test 'can generate remember token' do + user = create_user + user.singleton_class.send(:attr_accessor, :remember_token) + User.to_adapter.expects(:find_first).returns(nil) + user.remember_me! + assert user.remember_token + end + test 'serialize into cookie' do user = create_user user.remember_me! - assert_equal [user.to_key, user.authenticatable_salt], User.serialize_into_cookie(user) + id, token, date = User.serialize_into_cookie(user) + assert_equal id, user.to_key + assert_equal token, user.authenticatable_salt + assert date.is_a?(String) end test 'serialize from cookie' do user = create_user user.remember_me! - assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt) + assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt, Time.now.utc) end - test 'raises a RuntimeError if authenticatable_salt is nil' do - user = User.new - user.encrypted_password = nil - assert_raise RuntimeError do - user.rememberable_value - end + test 'serialize from cookie should accept a String with the datetime seconds and microseconds' do + user = create_user + user.remember_me! + assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt, Time.now.utc.to_f.to_json) 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=) + test 'serialize from cookie should return nil with invalid datetime' do + user = create_user + user.remember_me! + assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, "2013") end - test 'forget_me should clear remember_created_at' do - resource = create_resource - resource.remember_me! - assert_not resource.remember_created_at.nil? - resource.forget_me! - assert resource.remember_created_at.nil? + test 'serialize from cookie should return nil if no resource is found' do + assert_nil resource_class.serialize_from_cookie([0], "123", Time.now.utc) end - test 'forget_me should not try to update resource if it has been destroyed' do - resource = create_resource - resource.destroy - resource.expects(:remember_created_at).never - resource.expects(:save).never - resource.forget_me! + test 'serialize from cookie should return nil if no timestamp' do + user = create_user + user.remember_me! + assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt) end - test 'remember is expired if not created at timestamp is set' do - assert create_resource.remember_expired? + test 'serialize from cookie should return nil if timestamp is earlier than token creation' do + user = create_user + user.remember_me! + assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, 1.day.ago) end - test 'serialize should return nil if no resource is found' do - assert_nil resource_class.serialize_from_cookie([0], "123") + test 'serialize from cookie should return nil if timestamp is older than remember_for' do + user = create_user + user.remember_created_at = 1.month.ago + user.remember_me! + assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, 3.weeks.ago) end - test 'remember me return nil if is a valid resource with invalid token' do - resource = create_resource - assert_nil resource_class.serialize_from_cookie([resource.id], "123") + test 'serialize from cookie me return nil if is a valid resource with invalid token' do + user = create_user + user.remember_me! + assert_nil User.serialize_from_cookie(user.to_key, "123", Time.now.utc) end - test 'remember for should fallback to devise remember for default configuration' do - swap Devise, :remember_for => 1.day do - resource = create_resource - resource.remember_me! - assert_not resource.remember_expired? - end - end + test 'raises a RuntimeError if the user does not implements a rememberable value' do + user = User.new + assert_raise(RuntimeError) { user.rememberable_value } - test 'remember expires at should sum date of creation with remember for configuration' do - swap Devise, :remember_for => 3.days do - resource = create_resource - resource.remember_me! - assert_equal 3.days.from_now.to_date, resource.remember_expires_at.to_date + user_with_remember_token = User.new + def user_with_remember_token.remember_token; '123-token'; end + assert_equal '123-token', user_with_remember_token.rememberable_value - Devise.remember_for = 5.days - assert_equal 5.days.from_now.to_date, resource.remember_expires_at.to_date - end + user_with_salt = User.new + def user_with_salt.authenticatable_salt; '123-salt'; end + assert_equal '123-salt', user_with_salt.rememberable_value end - test 'remember should be expired if remember_for is zero' do - swap Devise, :remember_for => 0.days do - Devise.remember_for = 0.days - resource = create_resource - resource.remember_me! - assert resource.remember_expired? + test 'raises a RuntimeError if authenticatable_salt is nil or empty' do + user = User.new + def user.authenticatable_salt; nil; end + assert_raise RuntimeError do + user.rememberable_value end - end - test 'remember should be expired if it was created before limit time' do - swap Devise, :remember_for => 1.day do - resource = create_resource - resource.remember_me! - resource.remember_created_at = 2.days.ago - resource.save - assert resource.remember_expired? + user = User.new + def user.authenticatable_salt; ""; end + assert_raise RuntimeError do + user.rememberable_value end end - test 'remember should not be expired if it was created whitin the limit time' do - swap Devise, :remember_for => 30.days do + test 'should respond to remember_me attribute' do + 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 + swap Devise, expire_all_remember_me_on_sign_out: true do resource = create_resource resource.remember_me! - resource.remember_created_at = (30.days.ago + 2.minutes) - resource.save - assert_not resource.remember_expired? + assert_not_nil resource.remember_created_at + + resource.forget_me! + assert_nil resource.remember_created_at end end - test 'if extend_remember_period is false, remember_me! should generate a new timestamp if expired' do - swap Devise, :remember_for => 5.minutes do + test 'forget_me should not clear remember_created_at if expire_all_remember_me_on_sign_out is false' do + swap Devise, expire_all_remember_me_on_sign_out: false do resource = create_resource - resource.remember_me!(false) - assert resource.remember_created_at + resource.remember_me! - resource.remember_created_at = old = 10.minutes.ago - resource.save + assert_not_nil resource.remember_created_at - resource.remember_me!(false) - assert_not_equal old.to_i, resource.remember_created_at.to_i + resource.forget_me! + assert_not_nil resource.remember_created_at end end - test 'if extend_remember_period is false, remember_me! should not generate a new timestamp' do - swap Devise, :remember_for => 1.year do - resource = create_resource - resource.remember_me!(false) - assert resource.remember_created_at - - resource.remember_created_at = old = 10.minutes.ago.utc - resource.save + test 'forget_me should not try to update resource if it has been destroyed' do + resource = create_resource + resource.expects(:remember_created_at).never + resource.expects(:save).never - resource.remember_me!(false) - assert_equal old.to_i, resource.remember_created_at.to_i - end + resource.destroy + resource.forget_me! end - test 'if extend_remember_period is true, remember_me! should always generate a new timestamp' do - swap Devise, :remember_for => 1.year do + test 'remember expires at uses remember for configuration' do + swap Devise, remember_for: 3.days do resource = create_resource - resource.remember_me!(true) - assert resource.remember_created_at - - resource.remember_created_at = old = 10.minutes.ago - resource.save + resource.remember_me! + assert_equal 3.days.from_now.to_date, resource.remember_expires_at.to_date - resource.remember_me!(true) - assert_not_equal old, resource.remember_created_at + Devise.remember_for = 5.days + assert_equal 5.days.from_now.to_date, resource.remember_expires_at.to_date end end - test 'should have the required_fiels array' do - assert_same_content Devise::Models::Rememberable.required_fields(User), [ + test 'should have the required_fields array' do + 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 82d928e24e..024ccf4497 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,33 +7,28 @@ 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) + test 'should not include unsafe keys on JSON' do + keys = from_json().keys.select{ |key| !key.include?("id") } + assert_equal %w(created_at email facebook_token updated_at username), keys.sort end - test 'should include unsafe keys on XML if a force_except is provided' do - assert_no_match / :email) - assert_match /confirmation-token/, @user.to_xml(:force_except => :email) + test 'should not include unsafe keys on JSON even if a new except is provided' do + assert_no_key "email", from_json(except: :email) + assert_no_key "confirmation_token", from_json(except: :email) end - test 'should not include unsafe keys on JSON' do - assert_equal %w(created_at email facebook_token id updated_at username), from_json().keys.sort + test 'should include unsafe keys on JSON if a force_except is provided' do + assert_no_key "email", from_json(force_except: :email) + assert_key "confirmation_token", from_json(force_except: :email) end - test 'should not include unsafe keys on JSON even if a new except is provided' do - assert_no_key "email", from_json(:except => :email) - assert_no_key "confirmation_token", from_json(:except => :email) + test 'should not include unsafe keys in inspect' do + assert_match(/email/, @user.inspect) + assert_no_match(/confirmation_token/, @user.inspect) end - test 'should include unsafe keys on JSON if a force_except is provided' do - assert_no_key "email", from_json(:force_except => :email) - assert_key "confirmation_token", from_json(:force_except => :email) + test 'should accept frozen options' do + assert_key "username", @user.as_json({ only: :username, except: [:email].freeze }.freeze)["user"] end def assert_key(key, subject) @@ -39,10 +36,10 @@ def assert_key(key, subject) end def assert_no_key(key, subject) - assert !subject.key?(key), "Expected #{subject.inspect} to not have key #{key.inspect}" + assert_not subject.key?(key), "Expected #{subject.inspect} to not have key #{key.inspect}" end - def from_json(options=nil) + def from_json(options = nil) ActiveSupport::JSON.decode(@user.to_json(options))["user"] end end diff --git a/test/models/timeoutable_test.rb b/test/models/timeoutable_test.rb index 9dc93e0c48..43926521db 100644 --- a/test/models/timeoutable_test.rb +++ b/test/models/timeoutable_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class TimeoutableTest < ActiveSupport::TestCase @@ -29,7 +31,7 @@ class TimeoutableTest < ActiveSupport::TestCase end test 'fallback to Devise config option' do - swap Devise, :timeout_in => 1.minute do + swap Devise, timeout_in: 1.minute do user = new_user assert user.timedout?(2.minutes.ago) assert_not user.timedout?(30.seconds.ago) @@ -41,6 +43,11 @@ class TimeoutableTest < ActiveSupport::TestCase end test 'required_fields should contain the fields that Devise uses' do - assert_same_content Devise::Models::Timeoutable.required_fields(User), [] + assert_equal [], Devise::Models::Timeoutable.required_fields(User) + end + + test 'should not raise error if remember_created_at is not empty and rememberable is disabled' do + user = create_admin(remember_created_at: Time.current) + assert user.timedout?(31.minutes.ago) end end diff --git a/test/models/token_authenticatable_test.rb b/test/models/token_authenticatable_test.rb deleted file mode 100644 index 15da9dd48a..0000000000 --- a/test/models/token_authenticatable_test.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'test_helper' - -class TokenAuthenticatableTest < ActiveSupport::TestCase - - test 'should reset authentication token' do - user = new_user - user.reset_authentication_token - previous_token = user.authentication_token - user.reset_authentication_token - assert_not_equal previous_token, user.authentication_token - end - - test 'should ensure authentication token' do - user = new_user - user.ensure_authentication_token - previous_token = user.authentication_token - user.ensure_authentication_token - assert_equal previous_token, user.authentication_token - end - - test 'should authenticate a valid user with authentication token and return it' do - user = create_user - user.ensure_authentication_token! - user.confirm! - authenticated_user = User.find_for_token_authentication(:auth_token => user.authentication_token) - assert_equal authenticated_user, user - end - - test 'should return nil when authenticating an invalid user by authentication token' do - user = create_user - user.ensure_authentication_token! - user.confirm! - authenticated_user = User.find_for_token_authentication(:auth_token => user.authentication_token.reverse) - assert_nil authenticated_user - end - - test 'should not be subject to injection' do - user1 = create_user - user1.ensure_authentication_token! - user1.confirm! - - user2 = create_user - user2.ensure_authentication_token! - user2.confirm! - - user = User.find_for_token_authentication(:auth_token => {'$ne' => user1.authentication_token}) - assert_nil user - end - - test 'required_fields should contain the fields that Devise uses' do - assert_same_content Devise::Models::TokenAuthenticatable.required_fields(User), [ - :authentication_token - ] - end -end diff --git a/test/models/trackable_test.rb b/test/models/trackable_test.rb index 6abcd76cba..250ca1d463 100644 --- a/test/models/trackable_test.rb +++ b/test/models/trackable_test.rb @@ -1,13 +1,80 @@ +# frozen_string_literal: true + require 'test_helper' class TrackableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do - assert_same_content Devise::Models::Trackable.required_fields(User), [ + assert_equal [ :current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count - ] + ], Devise::Models::Trackable.required_fields(User) + end + + test 'update_tracked_fields should only set attributes but not save the record' do + user = create_user + request = mock + request.stubs(:remote_ip).returns("127.0.0.1") + + assert_nil user.current_sign_in_ip + assert_nil user.last_sign_in_ip + assert_nil user.current_sign_in_at + assert_nil user.last_sign_in_at + assert_equal 0, user.sign_in_count + + user.update_tracked_fields(request) + + assert_equal "127.0.0.1", user.current_sign_in_ip + assert_equal "127.0.0.1", user.last_sign_in_ip + assert_not_nil user.current_sign_in_at + assert_not_nil user.last_sign_in_at + assert_equal 1, user.sign_in_count + + user.reload + + assert_nil user.current_sign_in_ip + assert_nil user.last_sign_in_ip + assert_nil user.current_sign_in_at + assert_nil user.last_sign_in_at + assert_equal 0, user.sign_in_count + end + + test "update_tracked_fields! should not persist invalid records" do + user = UserWithValidations.new + request = mock + request.stubs(:remote_ip).returns("127.0.0.1") + + assert_not user.update_tracked_fields!(request) + assert_not user.persisted? + end + + test "update_tracked_fields! should not run model validations" do + user = User.new + request = mock + request.stubs(:remote_ip).returns("127.0.0.1") + + user.expects(:after_validation_callback).never + + assert_not user.update_tracked_fields!(request) + end + + test 'extract_ip_from should be overridable' do + class UserWithOverride < User + protected + def extract_ip_from(request) + "127.0.0.2" + end + end + + request = mock + request.stubs(:remote_ip).returns("127.0.0.1") + user = UserWithOverride.new + + user.update_tracked_fields(request) + + assert_equal "127.0.0.2", user.current_sign_in_ip + assert_equal "127.0.0.2", user.last_sign_in_ip end end diff --git a/test/models/validatable_test.rb b/test/models/validatable_test.rb index 10be9092c8..e8858de7e3 100644 --- a/test/models/validatable_test.rb +++ b/test/models/validatable_test.rb @@ -1,18 +1,20 @@ # encoding: UTF-8 +# frozen_string_literal: true + require 'test_helper' class ValidatableTest < ActiveSupport::TestCase test 'should require email to be set' do - user = new_user(:email => nil) + user = new_user(email: nil) assert user.invalid? assert user.errors[:email] - assert_equal 'can\'t be blank', user.errors[:email].join + assert user.errors.added?(:email, :blank) end test 'should require uniqueness of email if email has changed, allowing blank' do existing_user = create_user - user = new_user(:email => '') + user = new_user(email: '') assert user.invalid? assert_no_match(/taken/, user.errors[:email].join) @@ -20,72 +22,74 @@ class ValidatableTest < ActiveSupport::TestCase assert user.invalid? assert_match(/taken/, user.errors[:email].join) - user.save(:validate => false) + user.save(validate: false) assert user.valid? end test 'should require correct email format if email has changed, allowing blank' do - user = new_user(:email => '') + user = new_user(email: '') assert user.invalid? assert_not_equal 'is invalid', user.errors[:email].join - %w{invalid_email_format 123 $$$ () ☃ bla@bla.}.each do |email| + %w{invalid_email_format 123 $$$ () ☃}.each do |email| user.email = email - assert user.invalid?, 'should be invalid with email ' << email + assert user.invalid?, "should be invalid with email #{email}" assert_equal 'is invalid', user.errors[:email].join end - user.save(:validate => false) + user.save(validate: false) assert user.valid? end test 'should accept valid emails' do %w(a.b.c@example.com test_mail@gmail.com any@any.net email@test.br 123@mail.test 1☃3@mail.test).each do |email| - user = new_user(:email => email) - assert user.valid?, 'should be valid with email ' << email + user = new_user(email: email) + assert user.valid?, "should be valid with email #{email}" assert_blank user.errors[:email] end end test 'should require password to be set when creating a new record' do - user = new_user(:password => '', :password_confirmation => '') + user = new_user(password: '', password_confirmation: '') assert user.invalid? - assert_equal 'can\'t be blank', user.errors[:password].join + assert user.errors.added?(:password, :blank) end test 'should require confirmation to be set when creating a new record' do - user = new_user(:password => 'new_password', :password_confirmation => 'blabla') + user = new_user(password: 'new_password', password_confirmation: 'blabla') assert user.invalid? - assert_equal 'doesn\'t match confirmation', user.errors[:password].join + + assert user.errors.added?(:password_confirmation, :confirmation, attribute: "Password") end - test 'should require password when updating/reseting password' do + test 'should require password when updating/resetting password' do user = create_user user.password = '' user.password_confirmation = '' assert user.invalid? - assert_equal 'can\'t be blank', user.errors[:password].join + assert user.errors.added?(:password, :blank) end - test 'should require confirmation when updating/reseting password' do + test 'should require confirmation when updating/resetting password' do user = create_user user.password_confirmation = 'another_password' assert user.invalid? - assert_equal 'doesn\'t match confirmation', user.errors[:password].join + + assert user.errors.added?(:password_confirmation, :confirmation, attribute: "Password") end - test 'should require a password with minimum of 6 characters' do - user = new_user(:password => '12345', :password_confirmation => '12345') + test 'should require a password with minimum of 7 characters' do + user = new_user(password: '12345', password_confirmation: '12345') assert user.invalid? - assert_equal 'is too short (minimum is 6 characters)', user.errors[:password].join + assert_equal 'is too short (minimum is 7 characters)', user.errors[:password].join end - test 'should require a password with maximum of 128 characters long' do - user = new_user(:password => 'x'*129, :password_confirmation => 'x'*129) + test 'should require a password with maximum of 72 characters long' do + user = new_user(password: 'x'*73, password_confirmation: 'x'*73) assert user.invalid? - assert_equal 'is too long (maximum is 128 characters)', user.errors[:password].join + assert_equal 'is too long (maximum is 72 characters)', user.errors[:password].join end test 'should not require password length when it\'s not changed' do @@ -98,20 +102,23 @@ class ValidatableTest < ActiveSupport::TestCase assert_not (user.errors[:password].join =~ /is too long/) end - test 'should complain about length even if possword is not required' do - user = new_user(:password => 'x'*129, :password_confirmation => 'x'*129) + test 'should complain about length even if password is not required' do + user = new_user(password: 'x'*73, password_confirmation: 'x'*73) user.stubs(:password_required?).returns(false) assert user.invalid? - assert_equal 'is too long (maximum is 128 characters)', user.errors[:password].join + assert_equal 'is too long (maximum is 72 characters)', user.errors[:password].join end test 'should not be included in objects with invalid API' do - assert_raise RuntimeError do + exception = assert_raise RuntimeError do Class.new.send :include, Devise::Models::Validatable end + + expected_message = /Could not use :validatable module since .* does not respond to the following methods: validates_presence_of.*/ + assert_match expected_message, exception.message end 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 end diff --git a/test/models_test.rb b/test/models_test.rb index b33404651e..e2aced9ee5 100644 --- a/test/models_test.rb +++ b/test/models_test.rb @@ -1,26 +1,7 @@ -require 'test_helper' - -class Configurable < User - devise :database_authenticatable, :confirmable, :rememberable, :timeoutable, :lockable, - :stretches => 15, :pepper => 'abcdef', :allow_unconfirmed_access_for => 5.days, - :remember_for => 7.days, :timeout_in => 15.minutes, :unlock_in => 10.days -end - -class WithValidation < Admin - devise :database_authenticatable, :validatable, :password_length => 2..6 -end - -class UserWithValidation < User - validates_presence_of :username -end +# frozen_string_literal: true -class Several < Admin - devise :validatable - devise :lockable -end - -class Inheritable < Admin -end +require 'test_helper' +require 'test_models' class ActiveRecordTest < ActiveSupport::TestCase def include_module?(klass, mod) @@ -45,8 +26,8 @@ def assert_include_modules(klass, *modules) test 'validations options are not applied too late' do validators = WithValidation.validators_on :password length = validators.find { |v| v.kind == :length } - assert_equal 2, length.options[:minimum] - assert_equal 6, length.options[:maximum] + assert_equal 2, length.options[:minimum].call + assert_equal 6, length.options[:maximum].call end test 'validations are applied just once' do @@ -104,7 +85,18 @@ def assert_include_modules(klass, *modules) end test 'set null fields on migrations' do - Admin.create! + # Ignore email sending since no email exists. + klass = Class.new(Admin) do + def send_devise_notification(*); end + end + + assert_nothing_raised { klass.create! } + end +end + +module StubModelFilters + def stub_filter(name) + define_singleton_method(name) { |*| nil } end end @@ -112,16 +104,17 @@ class CheckFieldsTest < ActiveSupport::TestCase test 'checks if the class respond_to the required fields' do Player = Class.new do extend Devise::Models + extend StubModelFilters - def self.before_validation(instance) - end + stub_filter :before_validation + stub_filter :after_update devise :database_authenticatable attr_accessor :encrypted_password, :email end - assert_nothing_raised Devise::Models::MissingAttribute do + assert_nothing_raised do Devise::Models.check_fields!(Player) end end @@ -129,9 +122,10 @@ def self.before_validation(instance) test 'raises Devise::Models::MissingAtrribute and shows the missing attribute if the class doesn\'t respond_to one of the attributes' do Clown = Class.new do extend Devise::Models + extend StubModelFilters - def self.before_validation(instance) - end + stub_filter :before_validation + stub_filter :after_update devise :database_authenticatable @@ -146,9 +140,10 @@ def self.before_validation(instance) test 'raises Devise::Models::MissingAtrribute with all the missing attributes if there is more than one' do Magician = Class.new do extend Devise::Models + extend StubModelFilters - def self.before_validation(instance) - end + stub_filter :before_validation + stub_filter :after_update devise :database_authenticatable end @@ -157,23 +152,4 @@ def self.before_validation(instance) Devise::Models.check_fields!(Magician) end end - - test "doesn't raise a NoMethodError exception when the module doesn't have a required_field(klass) class method" do - driver = Class.new do - extend Devise::Models - - def self.before_validation(instance) - end - - attr_accessor :encrypted_password, :email - - devise :database_authenticatable - end - - swap_module_method_existence Devise::Models::DatabaseAuthenticatable, :required_fields do - assert_deprecated do - Devise::Models.check_fields!(driver) - end - end - end end diff --git a/test/omniauth/config_test.rb b/test/omniauth/config_test.rb index 3de56c3525..d2bf11bb01 100644 --- a/test/omniauth/config_test.rb +++ b/test/omniauth/config_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test_helper' class OmniAuthConfigTest < ActiveSupport::TestCase @@ -11,12 +13,12 @@ class MyStrategy end test 'strategy_name returns provider if no name option are given' do - config = Devise::OmniAuth::Config.new :facebook, [{ :other => :option }] + config = Devise::OmniAuth::Config.new :facebook, [{ other: :option }] assert_equal :facebook, config.strategy_name end test 'returns name option when have a name' do - config = Devise::OmniAuth::Config.new :facebook, [{ :name => :github }] + config = Devise::OmniAuth::Config.new :facebook, [{ name: :github }] assert_equal :github, config.strategy_name end @@ -25,19 +27,21 @@ class MyStrategy assert_equal OmniAuth::Strategies::Facebook, config.strategy_class end - test "finds the strategy in OmniAuth's list by name" do - NamedTestStrategy = Class.new - NamedTestStrategy.send :include, OmniAuth::Strategy - NamedTestStrategy.option :name, :the_one + class NamedTestStrategy + include OmniAuth::Strategy + option :name, :the_one + end + test "finds the strategy in OmniAuth's list by name" do config = Devise::OmniAuth::Config.new :the_one, [{}] assert_equal NamedTestStrategy, config.strategy_class end - test "finds the strategy in OmniAuth's list by class name" do - UnNamedTestStrategy = Class.new - UnNamedTestStrategy.send :include, OmniAuth::Strategy + class UnNamedTestStrategy + include OmniAuth::Strategy + end + test "finds the strategy in OmniAuth's list by class name" do config = Devise::OmniAuth::Config.new :un_named_test_strategy, [{}] assert_equal UnNamedTestStrategy, config.strategy_class end @@ -50,8 +54,8 @@ class MyStrategy end test 'allows the user to define a custom require path' do - config = Devise::OmniAuth::Config.new :my_strategy, [{:strategy_class => MyStrategy}] + config = Devise::OmniAuth::Config.new :my_strategy, [{strategy_class: MyStrategy}] config_class = config.strategy_class assert_equal MyStrategy, config_class end -end \ No newline at end of file +end diff --git a/test/omniauth/url_helpers_test.rb b/test/omniauth/url_helpers_test.rb index 67054b6529..a8098c741a 100644 --- a/test/omniauth/url_helpers_test.rb +++ b/test/omniauth/url_helpers_test.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'test_helper' class OmniAuthRoutesTest < ActionController::TestCase tests ApplicationController - def assert_path(action, provider, with_param=true) + def assert_path(action, provider, with_param = true) # Resource param assert_equal @controller.send(action, :user, provider), - @controller.send("user_#{action}", provider) + @controller.send("user_#{provider}_#{action}") # With an object assert_equal @controller.send(action, User.new, provider), - @controller.send("user_#{action}", provider) + @controller.send("user_#{provider}_#{action}") if with_param # Default url params - assert_equal @controller.send(action, :user, provider, :param => 123), - @controller.send("user_#{action}", provider, :param => 123) + assert_equal @controller.send(action, :user, provider, param: 123), + @controller.send("user_#{provider}_#{action}", param: 123) end end @@ -30,7 +32,7 @@ def assert_path(action, provider, with_param=true) test 'should generate authorization path' do assert_match "/users/auth/facebook", @controller.omniauth_authorize_path(:user, :facebook) - assert_raise ActionController::RoutingError do + assert_raise NoMethodError do @controller.omniauth_authorize_path(:user, :github) end end @@ -41,7 +43,7 @@ def assert_path(action, provider, with_param=true) test 'should generate authorization path with params' do assert_match "/users/auth/openid?openid_url=http%3A%2F%2Fyahoo.com", - @controller.omniauth_authorize_path(:user, :openid, :openid_url => "http://yahoo.com") + @controller.omniauth_authorize_path(:user, :openid, openid_url: "http://yahoo.com") end test 'should not add a "?" if no param was sent' do diff --git a/test/orm/active_record.rb b/test/orm/active_record.rb index d1bff6c201..e9b7ea5219 100644 --- a/test/orm/active_record.rb +++ b/test/orm/active_record.rb @@ -1,9 +1,17 @@ +# frozen_string_literal: true + ActiveRecord::Migration.verbose = false ActiveRecord::Base.logger = Logger.new(nil) +ActiveRecord::Base.include_root_in_json = true -ActiveRecord::Migrator.migrate(File.expand_path("../../rails_app/db/migrate/", __FILE__)) +migrate_path = File.expand_path("../../rails_app/db/migrate/", __FILE__) +if Devise::Test.rails71_and_up? + ActiveRecord::MigrationContext.new(migrate_path).migrate +else + ActiveRecord::MigrationContext.new(migrate_path, ActiveRecord::SchemaMigration).migrate +end class ActiveSupport::TestCase - self.use_transactional_fixtures = true + self.use_transactional_tests = true self.use_instantiated_fixtures = false end diff --git a/test/orm/mongoid.rb b/test/orm/mongoid.rb index b28a796c4d..5b8807f1fb 100644 --- a/test/orm/mongoid.rb +++ b/test/orm/mongoid.rb @@ -1,14 +1,15 @@ +# frozen_string_literal: true + require 'mongoid/version' Mongoid.configure do |config| - config.master = Mongo::Connection.new('127.0.0.1', 27017).db("devise-test-suite") + config.load!('test/support/mongoid.yml') config.use_utc = true config.include_root_in_json = true end class ActiveSupport::TestCase setup do - User.delete_all - Admin.delete_all + Mongoid::Config.purge! end end diff --git a/test/parameter_sanitizer_test.rb b/test/parameter_sanitizer_test.rb new file mode 100644 index 0000000000..c00cd58eb9 --- /dev/null +++ b/test/parameter_sanitizer_test.rb @@ -0,0 +1,105 @@ +# frozen_string_literal: true + +require 'test_helper' +require 'devise/parameter_sanitizer' + +class ParameterSanitizerTest < ActiveSupport::TestCase + def sanitizer(params) + params = ActionController::Parameters.new(params) + Devise::ParameterSanitizer.new(User, :user, params) + end + + test 'permits the default parameters for sign in' do + sanitizer = sanitizer('user' => { 'email' => 'jose' }) + sanitized = sanitizer.sanitize(:sign_in) + + assert_equal({ 'email' => '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) + + assert_equal({ 'email' => 'jose' }, sanitized) + end + + test 'permits the default parameters for account update' do + sanitizer = sanitizer('user' => { 'email' => 'jose', 'role' => 'invalid' }) + sanitized = sanitizer.sanitize(:account_update) + + assert_equal({ 'email' => 'jose' }, sanitized) + end + + test 'permits news parameters for an existing action' do + sanitizer = sanitizer('user' => { 'username' => 'jose' }) + sanitizer.permit(:sign_in, keys: [:username]) + sanitized = sanitizer.sanitize(:sign_in) + + assert_equal({ 'username' => 'jose' }, sanitized) + end + + test 'permits news parameters for an existing action with a block' do + sanitizer = sanitizer('user' => { 'username' => 'jose' }) + sanitizer.permit(:sign_in) do |user| + user.permit(:username) + end + + sanitized = sanitizer.sanitize(:sign_in) + + assert_equal({ 'username' => 'jose' }, sanitized) + end + + test 'permit parameters for new actions' do + sanitizer = sanitizer('user' => { 'email' => 'jose@omglol', 'name' => 'Jose' }) + sanitizer.permit(:invite_user, keys: [:email, :name]) + + sanitized = sanitizer.sanitize(:invite_user) + + assert_equal({ 'email' => 'jose@omglol', 'name' => 'Jose' }, sanitized) + end + + test 'fails when we do not have any permitted parameters for the action' do + sanitizer = sanitizer('user' => { 'email' => 'jose', 'password' => 'invalid' }) + + assert_raise NotImplementedError do + sanitizer.sanitize(:unknown) + end + end + + test 'removes permitted parameters' do + sanitizer = sanitizer('user' => { 'email' => 'jose@omglol', 'username' => 'jose' }) + + sanitizer.permit(:sign_in, keys: [:username], except: [:email]) + sanitized = sanitizer.sanitize(:sign_in) + + assert_equal({ 'username' => 'jose' }, sanitized) + end +end diff --git a/test/rails_app/Rakefile b/test/rails_app/Rakefile index f47ab4d562..ba6b733dd2 100644 --- a/test/rails_app/Rakefile +++ b/test/rails_app/Rakefile @@ -3,8 +3,4 @@ require File.expand_path('../config/application', __FILE__) -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - Rails.application.load_tasks diff --git a/test/rails_app/app/active_record/admin.rb b/test/rails_app/app/active_record/admin.rb index 124bc9059f..5383b3b23e 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 f12053eb1f..be35adb9b6 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 \ No newline at end of file +end diff --git a/test/rails_app/app/active_record/user.rb b/test/rails_app/app/active_record/user.rb index eefe2dd91b..37d454df49 100644 --- a/test/rails_app/app/active_record/user.rb +++ b/test/rails_app/app/active_record/user.rb @@ -1,6 +1,19 @@ +# frozen_string_literal: true + require 'shared_user' class User < ActiveRecord::Base include Shim include SharedUser + + 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 new file mode 100644 index 0000000000..42f233f36d --- /dev/null +++ b/test/rails_app/app/active_record/user_on_engine.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require 'shared_user_without_omniauth' + +class UserOnEngine < ActiveRecord::Base + self.table_name = 'users' + include Shim + include SharedUserWithoutOmniauth +end 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 new file mode 100644 index 0000000000..596bc3b94c --- /dev/null +++ b/test/rails_app/app/active_record/user_on_main_app.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require 'shared_user_without_omniauth' + +class UserOnMainApp < ActiveRecord::Base + self.table_name = 'users' + include Shim + include SharedUserWithoutOmniauth +end 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 0000000000..c396ba8835 --- /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 new file mode 100644 index 0000000000..62bdb89760 --- /dev/null +++ b/test/rails_app/app/active_record/user_without_email.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "shared_user_without_email" + +class UserWithoutEmail < ActiveRecord::Base + self.table_name = 'users' + include Shim + include SharedUserWithoutEmail +end + diff --git a/test/rails_app/app/controllers/admins/sessions_controller.rb b/test/rails_app/app/controllers/admins/sessions_controller.rb index 1c1b0b8e1a..122e15a77e 100644 --- a/test/rails_app/app/controllers/admins/sessions_controller.rb +++ b/test/rails_app/app/controllers/admins/sessions_controller.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Admins::SessionsController < Devise::SessionsController def new flash[:special] = "Welcome to #{controller_path.inspect} controller!" super end -end \ No newline at end of file +end diff --git a/test/rails_app/app/controllers/admins_controller.rb b/test/rails_app/app/controllers/admins_controller.rb index 538eb41cdb..c732f58908 100644 --- a/test/rails_app/app/controllers/admins_controller.rb +++ b/test/rails_app/app/controllers/admins_controller.rb @@ -1,11 +1,8 @@ +# frozen_string_literal: true + class AdminsController < ApplicationController - before_filter :authenticate_admin! + before_action :authenticate_admin! def index end - - def expire - admin_session['last_request_at'] = 31.minutes.ago.utc - render :text => 'Admin will be expired on next request' - end end diff --git a/test/rails_app/app/controllers/application_controller.rb b/test/rails_app/app/controllers/application_controller.rb index c1cfa4991a..616845d760 100644 --- a/test/rails_app/app/controllers/application_controller.rb +++ b/test/rails_app/app/controllers/application_controller.rb @@ -1,8 +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 - before_filter :current_user, :unless => :devise_controller? - before_filter :authenticate_user!, :if => :devise_controller? + 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 new file mode 100644 index 0000000000..652bd2e000 --- /dev/null +++ b/test/rails_app/app/controllers/application_with_fake_engine.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +class ApplicationWithFakeEngine < ApplicationController + private + + helper_method :fake_engine + def fake_engine + @fake_engine ||= FakeEngine.new + end +end + +class FakeEngine + def user_on_engine_confirmation_path + '/user_on_engine/confirmation' + end + + def new_user_on_engine_session_path + '/user_on_engine/confirmation/new' + end + + def new_user_on_engine_registration_path + '/user_on_engine/registration/new' + end + + def new_user_on_engine_password_path + '/user_on_engine/password/new' + end + + def new_user_on_engine_unlock_path + '/user_on_engine/unlock/new' + end +end diff --git a/test/rails_app/app/controllers/custom/registrations_controller.rb b/test/rails_app/app/controllers/custom/registrations_controller.rb new file mode 100644 index 0000000000..dd0e7a2fa0 --- /dev/null +++ b/test/rails_app/app/controllers/custom/registrations_controller.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +class Custom::RegistrationsController < Devise::RegistrationsController + def new + super do |resource| + @new_block_called = true + end + end + + def create + super do |resource| + @create_block_called = true + end + end + + def update + super do |resource| + @update_block_called = true + end + end + + def create_block_called? + @create_block_called == true + end + + def update_block_called? + @update_block_called == true + end + + def new_block_called? + @new_block_called == true + end +end diff --git a/test/rails_app/app/controllers/home_controller.rb b/test/rails_app/app/controllers/home_controller.rb index 19a787bde5..b8f3327ada 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,6 +22,6 @@ def set end def unauthenticated - render :text => "unauthenticated", :status => :unauthorized + 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 daf5e7fad2..f7bdaa08e2 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 \ No newline at end of file +end diff --git a/test/rails_app/app/controllers/publisher/sessions_controller.rb b/test/rails_app/app/controllers/publisher/sessions_controller.rb index 03e106d7f1..48ce6859dc 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 \ No newline at end of file +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 0000000000..1045fea185 --- /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 71eb57ec5a..f5327fbd7b 100644 --- a/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb +++ b/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook - data = env["omniauth.auth"] + data = request.respond_to?(:get_header) ? request.get_header("omniauth.auth") : request.env["omniauth.auth"] session["devise.facebook_data"] = data["extra"]["user_hash"] - render :json => data + render json: data end def sign_in_facebook - user = User.find_by_email('user@test.com') + user = User.to_adapter.find_first(email: 'user@test.com') user.remember_me = true sign_in user - render :text => "" + render body: "" end -end \ No newline at end of file +end diff --git a/test/rails_app/app/controllers/users_controller.rb b/test/rails_app/app/controllers/users_controller.rb index 4fe523289a..b3b49ee2a2 100644 --- a/test/rails_app/app/controllers/users_controller.rb +++ b/test/rails_app/app/controllers/users_controller.rb @@ -1,23 +1,34 @@ +# frozen_string_literal: true + class UsersController < ApplicationController - prepend_before_filter :current_user, :only => :exhibit - before_filter :authenticate_user!, :except => [:accept, :exhibit] - respond_to :html, :xml + prepend_before_action :current_user, only: :exhibit + before_action :authenticate_user!, except: [:accept, :exhibit] + clear_respond_to + respond_to :html, :json def index user_session[:cart] = "Cart" respond_with(current_user) end + def edit_form + user_session['last_request_at'] = params.fetch(:last_request_at, 31.minutes.ago.utc) + end + + def update_form + render body: 'Update' + end + def accept @current_user = current_user end def exhibit - render :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 :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 22a7940eb2..fc3fb393d3 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 new file mode 100644 index 0000000000..e369512576 --- /dev/null +++ b/test/rails_app/app/mailers/users/from_proc_mailer.rb @@ -0,0 +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 6b6b8fbf75..5962e15daa 100644 --- a/test/rails_app/app/mailers/users/mailer.rb +++ b/test/rails_app/app/mailers/users/mailer.rb @@ -1,8 +1,5 @@ +# frozen_string_literal: true + class Users::Mailer < Devise::Mailer - default :from => 'custom@example.com' + default from: 'custom@example.com' end - -class Users::ReplyToMailer < Devise::Mailer - default :from => 'custom@example.com' - default :reply_to => 'custom_reply_to@example.com' -end \ No newline at end of file diff --git a/test/rails_app/app/mailers/users/reply_to_mailer.rb b/test/rails_app/app/mailers/users/reply_to_mailer.rb new file mode 100644 index 0000000000..4b241d32a9 --- /dev/null +++ b/test/rails_app/app/mailers/users/reply_to_mailer.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class Users::ReplyToMailer < Devise::Mailer + default from: 'custom@example.com' + default reply_to: 'custom_reply_to@example.com' +end diff --git a/test/rails_app/app/mongoid/admin.rb b/test/rails_app/app/mongoid/admin.rb index 4ab7408375..c41ea059d0 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 @@ -6,22 +8,24 @@ class Admin include SharedAdmin ## Database authenticatable - field :email, :type => String, :null => true - field :encrypted_password, :type => String, :null => true + field :email, type: String + field :encrypted_password, type: String ## Recoverable - field :reset_password_token, :type => String - field :reset_password_sent_at, :type => Time + field :reset_password_token, type: String + field :reset_password_sent_at, type: Time ## Rememberable - field :remember_created_at, :type => Time + field :remember_created_at, type: Time ## Confirmable - field :confirmation_token, :type => String - field :confirmed_at, :type => Time - field :confirmation_sent_at, :type => Time - field :unconfirmed_email, :type => String # Only if using reconfirmable + field :confirmation_token, type: String + field :confirmed_at, type: Time + field :confirmation_sent_at, type: Time + field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable - field :locked_at, :type => Time + field :locked_at, type: Time + + field :active, type: Boolean, default: false end diff --git a/test/rails_app/app/mongoid/shim.rb b/test/rails_app/app/mongoid/shim.rb index 0556561e17..e5f35782f5 100644 --- a/test/rails_app/app/mongoid/shim.rb +++ b/test/rails_app/app/mongoid/shim.rb @@ -1,19 +1,20 @@ +# frozen_string_literal: true + module Shim extend ::ActiveSupport::Concern included do include ::Mongoid::Timestamps - field :created_at, :type => DateTime + field :created_at, type: DateTime end module ClassMethods - def last(options={}) - options.delete(:order) if options[:order] == "id" - super(options) + def order(attribute) + asc(attribute) end def find_by_email(email) - first(:conditions => { :email => email }) + find_by(email: email) end end diff --git a/test/rails_app/app/mongoid/user.rb b/test/rails_app/app/mongoid/user.rb index 5c5a381735..7e5b2b381c 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 @@ -5,38 +7,44 @@ class User include Shim include SharedUser - field :username, :type => String - field :facebook_token, :type => String + field :username, type: String + field :facebook_token, type: String ## Database authenticatable - field :email, :type => String, :null => false, :default => "" - field :encrypted_password, :type => String, :null => false, :default => "" + 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 + field :reset_password_token, type: String + field :reset_password_sent_at, type: Time ## Rememberable - field :remember_created_at, :type => Time + 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 - field :confirmed_at, :type => Time - field :confirmation_sent_at, :type => Time - # field :unconfirmed_email, :type => String # Only if using reconfirmable + field :confirmation_token, type: String + field :confirmed_at, type: Time + field :confirmation_sent_at, type: Time + # field :unconfirmed_email, type: String # Only if using reconfirmable ## 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 + 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 - ## Token authenticatable - field :authentication_token, :type => String + 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 new file mode 100644 index 0000000000..f63b727bbf --- /dev/null +++ b/test/rails_app/app/mongoid/user_on_engine.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'shared_user_without_omniauth' + +class UserOnEngine + include Mongoid::Document + include Shim + include SharedUserWithoutOmniauth + + 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 + + ## Confirmable + field :confirmation_token, type: String + field :confirmed_at, type: Time + field :confirmation_sent_at, type: Time + # field :unconfirmed_email, type: String # Only if using reconfirmable + + ## 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 +end diff --git a/test/rails_app/app/mongoid/user_on_main_app.rb b/test/rails_app/app/mongoid/user_on_main_app.rb new file mode 100644 index 0000000000..92fea262b5 --- /dev/null +++ b/test/rails_app/app/mongoid/user_on_main_app.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'shared_user_without_omniauth' + +class UserOnMainApp + include Mongoid::Document + include Shim + include SharedUserWithoutOmniauth + + 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 + + ## Confirmable + field :confirmation_token, type: String + field :confirmed_at, type: Time + field :confirmation_sent_at, type: Time + # field :unconfirmed_email, type: String # Only if using reconfirmable + + ## 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 +end 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 0000000000..c1b73a3063 --- /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 new file mode 100644 index 0000000000..b82ea56ad2 --- /dev/null +++ b/test/rails_app/app/mongoid/user_without_email.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "shared_user_without_email" + +class UserWithoutEmail + include Mongoid::Document + include Shim + include SharedUserWithoutEmail + + 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 +end 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 c3f29d2bb0..f3be6278ed 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" %> \ No newline at end of file +<%= render template: "devise/sessions/new" %> diff --git a/test/rails_app/app/views/home/admin_dashboard.html.erb b/test/rails_app/app/views/home/admin_dashboard.html.erb index ad6e24625d..382c9968d7 100644 --- a/test/rails_app/app/views/home/admin_dashboard.html.erb +++ b/test/rails_app/app/views/home/admin_dashboard.html.erb @@ -1 +1 @@ -Admin dashboard \ No newline at end of file +Admin dashboard diff --git a/test/rails_app/app/views/home/index.html.erb b/test/rails_app/app/views/home/index.html.erb index 7272a5af22..c3942a09a8 100644 --- a/test/rails_app/app/views/home/index.html.erb +++ b/test/rails_app/app/views/home/index.html.erb @@ -1 +1 @@ -Home! \ No newline at end of file +Home! diff --git a/test/rails_app/app/views/home/join.html.erb b/test/rails_app/app/views/home/join.html.erb index a8d9133de2..e3bafea5c6 100644 --- a/test/rails_app/app/views/home/join.html.erb +++ b/test/rails_app/app/views/home/join.html.erb @@ -1 +1 @@ -Join \ No newline at end of file +Join diff --git a/test/rails_app/app/views/home/user_dashboard.html.erb b/test/rails_app/app/views/home/user_dashboard.html.erb index a54dcabf2f..578ba45aae 100644 --- a/test/rails_app/app/views/home/user_dashboard.html.erb +++ b/test/rails_app/app/views/home/user_dashboard.html.erb @@ -1 +1 @@ -User dashboard \ No newline at end of file +User dashboard diff --git a/test/rails_app/app/views/layouts/application.html.erb b/test/rails_app/app/views/layouts/application.html.erb index 5a4c004829..cdd9fe1acb 100644 --- a/test/rails_app/app/views/layouts/application.html.erb +++ b/test/rails_app/app/views/layouts/application.html.erb @@ -7,7 +7,7 @@
<%- flash.each do |name, msg| -%> - <%= content_tag :div, msg, :id => "flash_#{name}" %> + <%= content_tag :div, msg, id: "flash_#{name}" %> <%- end -%> <% if user_signed_in? -%> diff --git a/test/rails_app/app/views/users/edit_form.html.erb b/test/rails_app/app/views/users/edit_form.html.erb new file mode 100644 index 0000000000..b7a2e31c1f --- /dev/null +++ b/test/rails_app/app/views/users/edit_form.html.erb @@ -0,0 +1 @@ +<%= button_to 'Update', update_form_user_path(current_user), method: 'put' %> diff --git a/test/rails_app/bin/bundle b/test/rails_app/bin/bundle new file mode 100755 index 0000000000..66e9889e8b --- /dev/null +++ b/test/rails_app/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/test/rails_app/bin/rails b/test/rails_app/bin/rails new file mode 100755 index 0000000000..728cd85aa5 --- /dev/null +++ b/test/rails_app/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../../config/application', __FILE__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/test/rails_app/bin/rake b/test/rails_app/bin/rake new file mode 100755 index 0000000000..17240489f6 --- /dev/null +++ b/test/rails_app/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/test/rails_app/config/application.rb b/test/rails_app/config/application.rb index ecafba8d93..fc3b171d07 100644 --- a/test/rails_app/config/application.rb +++ b/test/rails_app/config/application.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require File.expand_path('../boot', __FILE__) +require "logger" require "action_controller/railtie" require "action_mailer/railtie" -require "active_resource/railtie" require "rails/test_unit/railtie" Bundler.require :default, DEVISE_ORM @@ -17,25 +19,35 @@ module RailsApp class Application < Rails::Application # Add additional load paths for your own custom dirs - config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers views).include?($1) } - config.autoload_paths += [ "#{config.root}/app/#{DEVISE_ORM}" ] + config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers mailers views).include?($1) } + config.autoload_paths += ["#{config.root}/app/#{DEVISE_ORM}"] # Configure generators values. Many other options are available, be sure to check the documentation. # config.generators do |g| # g.orm :active_record # g.template_engine :erb - # g.test_framework :test_unit, :fixture => true + # g.test_framework :test_unit, fixture: true # end # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters << :password - config.assets.enabled = false + # config.assets.enabled = false - config.action_mailer.default_url_options = { :host => "localhost:3000" } + config.action_mailer.default_url_options = { host: "localhost", port: 3000 } # 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 ced57d00db..e328fce492 100644 --- a/test/rails_app/config/boot.rb +++ b/test/rails_app/config/boot.rb @@ -1,8 +1,27 @@ +# frozen_string_literal: true + unless defined?(DEVISE_ORM) DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym end -require 'rubygems' -require 'bundler/setup' +module Devise + module Test + # 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.rails70? + Rails.version.start_with? '7.0' + end + end +end -$:.unshift File.expand_path('../../../../lib', __FILE__) \ No newline at end of file +# Set up gems listed in the Gemfile. +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) +require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) diff --git a/test/rails_app/config/environment.rb b/test/rails_app/config/environment.rb index cb86aabf1b..1c7a3ec2c2 100644 --- a/test/rails_app/config/environment.rb +++ b/test/rails_app/config/environment.rb @@ -1,5 +1,7 @@ -# Load the rails application +# frozen_string_literal: true + +# Load the rails application. require File.expand_path('../application', __FILE__) -# Initialize the rails application +# Initialize the rails application. RailsApp::Application.initialize! diff --git a/test/rails_app/config/environments/development.rb b/test/rails_app/config/environments/development.rb index bc251f755d..d23c88d153 100644 --- a/test/rails_app/config/environments/development.rb +++ b/test/rails_app/config/environments/development.rb @@ -1,18 +1,32 @@ +# frozen_string_literal: true + RailsApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb + # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development - # since you don't have to restart the webserver when you make code changes. + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. config.cache_classes = false - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true + # Do not eager load code on boot. + config.eager_load = false - # Show full error reports and disable caching + # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false - # Don't care if the mailer can't send + # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Only use best-standards-support built into browsers. + config.action_dispatch.best_standards_support = :builtin + + # Raise an error on page load if there are pending migrations + config.active_record.migration_error = :page_load + + # Debug mode disables concatenation and preprocessing of assets. + config.assets.debug = true end diff --git a/test/rails_app/config/environments/production.rb b/test/rails_app/config/environments/production.rb index fe0831be97..17c5b266f5 100644 --- a/test/rails_app/config/environments/production.rb +++ b/test/rails_app/config/environments/production.rb @@ -1,33 +1,82 @@ +# frozen_string_literal: true + RailsApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb + # Settings specified here will take precedence over those in config/application.rb. - # The production environment is meant for finished, "live" apps. - # Code is not reloaded between requests + # Code is not reloaded between requests. config.cache_classes = true - # Full error reports are disabled and caching is turned on + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both thread web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true - # See everything in the log (default is :info) - # config.log_level = :debug + # Enable Rack::Cache to put a simple HTTP cache in front of your application + # Add `rack-cache` to your Gemfile before enabling this. + # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. + # config.action_dispatch.rack_cache = true - # Use a different logger for distributed setups - # config.logger = SyslogLogger.new + # Disable Rails's static asset server (Apache or nginx will already do this). + config.public_file_server.enabled = false - # Use a different cache store in production - # config.cache_store = :mem_cache_store + # Compress JavaScripts and CSS. + config.assets.js_compressor = :uglifier + # config.assets.css_compressor = :sass + + # Whether to fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Generate digests for assets URLs. + config.assets.digest = true + + # Version of your assets, change this if you want to expire all your assets. + config.assets.version = '1.0' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true - # Disable Rails's static asset server - # In production, Apache or nginx will already do this - config.serve_static_assets = false + # Set to :debug to see everything in the log. + config.log_level = :info - # Enable serving of images, stylesheets, and javascripts from an asset server + # Prepend all log lines with the following tags. + # config.log_tags = [:subdomain, :uuid] + + # Use a different logger for distributed setups. + # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" - # Disable delivery errors, bad email addresses will be ignored + # Precompile additional assets. + # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. + # config.assets.precompile += %w( search.js ) + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false - # Enable threaded mode - # config.threadsafe! + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation can not be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Disable automatic flushing of the log to improve performance. + # config.autoflush_log = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new end diff --git a/test/rails_app/config/environments/test.rb b/test/rails_app/config/environments/test.rb index 0dfc4389f8..acc06f31f4 100644 --- a/test/rails_app/config/environments/test.rb +++ b/test/rails_app/config/environments/test.rb @@ -1,33 +1,43 @@ +# frozen_string_literal: true + RailsApp::Application.configure do - # Settings specified here will take precedence over those in config/environment.rb + # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's - # test suite. You never need to work with it otherwise. Remember that + # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped - # and recreated between test runs. Don't rely on the data there! + # and recreated between test runs. Don't rely on the data there! config.cache_classes = true - # Log error messages when you accidentally call methods on nil. - config.whiny_nils = true + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = true + config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'} - # Show full error reports and disable caching + # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false - # Disable request forgery protection in test environment - config.action_controller.allow_forgery_protection = false + # Raise exceptions instead of rendering exception templates. + 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 # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test - # Use SQL instead of Active Record's schema dumper when creating the test database. - # This is necessary if your schema can't be completely dumped by the schema dumper, - # like if you have constraints or database-specific column types - # config.active_record.schema_format = :sql - - config.action_dispatch.show_exceptions = false - + # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr end diff --git a/test/rails_app/config/initializers/backtrace_silencers.rb b/test/rails_app/config/initializers/backtrace_silencers.rb index 56ddc8da86..9edabe9365 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 cd2d70e3de..85fdfe0ae7 100644 --- a/test/rails_app/config/initializers/devise.rb +++ b/test/rails_app/config/initializers/devise.rb @@ -1,14 +1,27 @@ +# 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| + config.secret_key = "d9eb5171c59a4c817f68b0de27b8c1e340c2341b52cdbc60d3083d4e8958532" \ + "18dcc5f589cafde048faec956b61f864b9b5513ff9ce29bf9e5d58b0f234f8e3b" + # ==> 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 with default "from" parameter. config.mailer_sender = "please-change-me@config-initializers-devise.com" + + config.parent_controller = "ApplicationWithFakeEngine" # Configure the class responsible to send e-mails. # config.mailer = "Devise::Mailer" @@ -26,7 +39,7 @@ # session. If you need permissions, you should implement that in a before filter. # You can also supply hash where the value is a boolean expliciting if authentication # should be aborted or not if the value is not present. By default is empty. - # config.authentication_keys = [ :email ] + # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to @@ -38,12 +51,12 @@ # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. - config.case_insensitive_keys = [ :email ] + config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. - config.strip_whitespace_keys = [ :email ] + config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # config.params_authenticatable = true @@ -63,8 +76,8 @@ config.stretches = Rails.env.test? ? 1 : 10 # ==> Configuration for :confirmable - # The time you want to give your user to confirm his account. During this time - # he will be able to access your application without confirming. Default is nil. + # The time you want to give your user to confirm their account. During this time + # they will be able to access your application without confirming. Default is nil. # When allow_unconfirmed_access_for is zero, the user won't be able to sign in without confirming. # You can use this to let your user access some features of your application # without confirming the account, but blocking it after a certain period @@ -72,21 +85,18 @@ # config.allow_unconfirmed_access_for = 2.days # Defines which key will be used when confirming an account - # config.confirmation_keys = [ :email ] + # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks - # If true, a valid remember token can be re-used between multiple browsers. - # config.remember_across_browsers = true - # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # ==> Configuration for :validatable - # Range for password length. Default is 8..128. - # config.password_length = 8..128 + # Range for password length. Default is 8..72. + # config.password_length = 8..72 # Regex to use to validate the email address # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i @@ -103,7 +113,7 @@ # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account - # config.unlock_keys = [ :email ] + # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email @@ -122,19 +132,19 @@ # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account - # config.reset_password_keys = [ :email ] + # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 2.hours - # Setup a pepper to generate the encrypted password. - config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a" + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true - # ==> Configuration for :token_authenticatable - # Defines name of the authentication token params key - # config.token_authentication_key = :auth_token + # Set up a pepper to generate the encrypted password. + config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a" # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for @@ -163,16 +173,27 @@ # config.sign_out_via = :get # ==> OmniAuth - config.omniauth :facebook, 'APP_ID', 'APP_SECRET', :scope => 'email,offline_access' + config.omniauth :facebook, 'APP_ID', 'APP_SECRET', scope: 'email,offline_access' config.omniauth :openid - config.omniauth :openid, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id' + config.omniauth :openid, name: 'google', identifier: 'https://www.google.com/accounts/o8/id' # ==> Warden configuration # 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 45fc8f45a6..7bb3dc01ff 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 d27fc2d907..48d1b70a52 100644 --- a/test/rails_app/config/initializers/secret_token.rb +++ b/test/rails_app/config/initializers/secret_token.rb @@ -1,2 +1,5 @@ -Rails.application.config.secret_token = 'ea942c41850d502f2c8283e26bdc57829f471bb18224ddff0a192c4f32cdf6cb5aa0d82b3a7a7adbeb640c4b06f3aa1cd5f098162d8240f669b39d6b49680571' -Rails.application.config.session_store :cookie_store, :key => "_my_app" \ No newline at end of file +# 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 new file mode 100644 index 0000000000..5cfac4ec5d --- /dev/null +++ b/test/rails_app/config/initializers/session_store.rb @@ -0,0 +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 32cad99ca5..0b748f3fd7 100644 --- a/test/rails_app/config/routes.rb +++ b/test/rails_app/config/routes.rb @@ -1,100 +1,130 @@ +# frozen_string_literal: true + Rails.application.routes.draw do # Resources for testing - resources :users, :only => [:index] do - get :expire, :on => :member - get :accept, :on => :member + resources :users, only: [:index] do + member do + get :expire + get :accept + get :edit_form + put :update_form + end authenticate do - post :exhibit, :on => :member + post :exhibit, on: :member end end - resources :admins, :only => [:index] do - get :expire, :on => :member - end + resources :admins, only: [:index] + + resources :streaming, only: [:index] # Users scope - devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } + devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" } + + devise_for :user_on_main_apps, + class_name: 'UserOnMainApp', + router_name: :main_app, + module: :devise + + devise_for :user_on_engines, + class_name: 'UserOnEngine', + router_name: :fake_engine, + module: :devise + + devise_for :user_without_email, + class_name: 'UserWithoutEmail', + router_name: :main_app, + module: :devise as :user do - match "/as/sign_in", :to => "devise/sessions#new" + get "/as/sign_in", to: "devise/sessions#new" end - match "/sign_in", :to => "devise/sessions#new" + get "/sign_in", to: "devise/sessions#new" + + # Routes for custom controller testing + devise_for :user, only: [:registrations], controllers: { registrations: "custom/registrations" }, as: :custom, path: :custom # Admin scope - devise_for :admin, :path => "admin_area", :controllers => { :sessions => :"admins/sessions" }, :skip => :passwords + devise_for :admin, path: "admin_area", controllers: { sessions: :"admins/sessions" }, skip: :passwords - match "/admin_area/home", :to => "admins#index", :as => :admin_root - match "/anywhere", :to => "foo#bar", :as => :new_admin_password + get "/admin_area/home", to: "admins#index", as: :admin_root + get "/anywhere", to: "foo#bar", as: :new_admin_password authenticate(:admin) do - match "/private", :to => "home#private", :as => :private + get "/private", to: "home#private", as: :private end authenticate(:admin, lambda { |admin| admin.active? }) do - match "/private/active", :to => "home#private", :as => :private_active + get "/private/active", to: "home#private", as: :private_active end authenticated :admin do - match "/dashboard", :to => "home#admin_dashboard" + get "/dashboard", to: "home#admin_dashboard" end authenticated :admin, lambda { |admin| admin.active? } do - match "/dashboard/active", :to => "home#admin_dashboard" + get "/dashboard/active", to: "home#admin_dashboard" end authenticated do - match "/dashboard", :to => "home#user_dashboard" + get "/dashboard", to: "home#user_dashboard" end unauthenticated do - match "/join", :to => "home#join" + get "/join", to: "home#join" end # Routes for constraints testing - devise_for :headquarters_admin, :class_name => "Admin", :path => "headquarters", :constraints => {:host => /192\.168\.1\.\d\d\d/} + devise_for :headquarters_admin, class_name: "Admin", path: "headquarters", constraints: {host: /192\.168\.1\.\d\d\d/} + + constraints(host: /192\.168\.1\.\d\d\d/) do + devise_for :homebase_admin, class_name: "Admin", path: "homebase" + end - constraints(:host => /192\.168\.1\.\d\d\d/) do - devise_for :homebase_admin, :class_name => "Admin", :path => "homebase" + scope(subdomain: 'sub') do + devise_for :subdomain_users, class_name: "User", only: [:sessions] end - devise_for :skip_admin, :class_name => "Admin", :skip => :all + devise_for :skip_admin, class_name: "Admin", skip: :all # Routes for format=false testing - devise_for :htmlonly_admin, :class_name => "Admin", :skip => [:confirmations, :unlocks], :path => "htmlonly_admin", :format => false, :skip_helpers => [:confirmations, :unlocks] - devise_for :htmlonly_users, :class_name => "User", :only => [:confirmations, :unlocks], :path => "htmlonly_users", :format => false, :skip_helpers => true + devise_for :htmlonly_admin, class_name: "Admin", skip: [:confirmations, :unlocks], path: "htmlonly_admin", format: false, skip_helpers: [:confirmations, :unlocks] + devise_for :htmlonly_users, class_name: "User", only: [:confirmations, :unlocks], path: "htmlonly_users", format: false, skip_helpers: true # Other routes for routing_test.rb - devise_for :reader, :class_name => "User", :only => :passwords + devise_for :reader, class_name: "User", only: :passwords - scope :host => "sub.example.com" do - devise_for :sub_admin, :class_name => "Admin" + scope host: "sub.example.com" do + devise_for :sub_admin, class_name: "Admin" end - namespace :publisher, :path_names => { :sign_in => "i_dont_care", :sign_out => "get_out" } do - devise_for :accounts, :class_name => "Admin", :path_names => { :sign_in => "get_in" } + namespace :publisher, path_names: { sign_in: "i_dont_care", sign_out: "get_out" } do + devise_for :accounts, class_name: "Admin", path_names: { sign_in: "get_in" } end - scope ":locale", :module => :invalid do - devise_for :accounts, :singular => "manager", :class_name => "Admin", - :path_names => { - :sign_in => "login", :sign_out => "logout", - :password => "secret", :confirmation => "verification", - :unlock => "unblock", :sign_up => "register", - :registration => "management", :cancel => "giveup" - }, :failure_app => lambda { |env| [404, {"Content-Type" => "text/plain"}, ["Oops, not found"]] }, :module => :devise + scope ":locale", module: :invalid do + devise_for :accounts, singular: "manager", class_name: "Admin", + path_names: { + sign_in: "login", sign_out: "logout", + password: "secret", confirmation: "verification", + unlock: "unblock", sign_up: "register", + registration: "management", + cancel: "giveup", edit: "edit/profile" + }, failure_app: lambda { |env| [404, {"Content-Type" => "text/plain"}, ["Oops, not found"]] }, module: :devise end - namespace :sign_out_via, :module => "devise" do - devise_for :deletes, :sign_out_via => :delete, :class_name => "Admin" - devise_for :posts, :sign_out_via => :post, :class_name => "Admin" - devise_for :delete_or_posts, :sign_out_via => [:delete, :post], :class_name => "Admin" + namespace :sign_out_via, module: "devise" do + devise_for :deletes, sign_out_via: :delete, class_name: "Admin" + devise_for :posts, sign_out_via: :post, class_name: "Admin" + devise_for :gets, sign_out_via: :get, class_name: "Admin" + devise_for :delete_or_posts, sign_out_via: [:delete, :post], class_name: "Admin" end - match "/set", :to => "home#set" - match "/unauthenticated", :to => "home#unauthenticated" - match "/custom_strategy/new" + get "/set", to: "home#set" + get "/unauthenticated", to: "home#unauthenticated" + get "/custom_strategy/new" - root :to => "home#index" + root to: "home#index", via: [:get, :post] end diff --git a/test/rails_app/db/migrate/20100401102949_create_tables.rb b/test/rails_app/db/migrate/20100401102949_create_tables.rb index 85e3000b52..8d46b3e5c4 100644 --- a/test/rails_app/db/migrate/20100401102949_create_tables.rb +++ b/test/rails_app/db/migrate/20100401102949_create_tables.rb @@ -1,12 +1,14 @@ -class CreateTables < ActiveRecord::Migration +# frozen_string_literal: true + +class CreateTables < ActiveRecord::Migration[5.0] def self.up create_table :users do |t| t.string :username t.string :facebook_token ## Database authenticatable - t.string :email, :null => false, :default => "" - t.string :encrypted_password, :null => false, :default => "" + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token @@ -16,7 +18,7 @@ def self.up t.datetime :remember_created_at ## Trackable - t.integer :sign_in_count, :default => 0 + t.integer :sign_in_count, default: 0 t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip @@ -29,20 +31,17 @@ def self.up # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable - t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts + t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at - ## Token authenticatable - t.string :authentication_token - - t.timestamps + t.timestamps null: false end create_table :admins do |t| ## Database authenticatable - t.string :email, :null => true - t.string :encrypted_password, :null => true + t.string :email, null: true + t.string :encrypted_password, null: true ## Recoverable t.string :reset_password_token @@ -61,9 +60,9 @@ def self.up t.datetime :locked_at ## Attribute for testing route blocks - t.boolean :active, :default => false + t.boolean :active, default: false - t.timestamps + t.timestamps null: false end end diff --git a/test/rails_app/db/schema.rb b/test/rails_app/db/schema.rb index 8fae3c2812..c435f6b96e 100644 --- a/test/rails_app/db/schema.rb +++ b/test/rails_app/db/schema.rb @@ -1,3 +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. @@ -8,43 +11,45 @@ # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # -# It's strongly recommended to check this file into your version control system. +# It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(:version => 20100401102949) do +ActiveRecord::Schema.define(version: 20100401102949) do - create_table "admins", :force => true do |t| + create_table "admins", force: true do |t| t.string "email" - t.string "encrypted_password", :limit => 128 - t.string "password_salt" - t.string "remember_token" - t.datetime "remember_created_at" + t.string "encrypted_password" t.string "reset_password_token" - t.integer "failed_attempts", :default => 0 - t.string "unlock_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.string "confirmation_token" + t.datetime "confirmed_at" + t.datetime "confirmation_sent_at" + t.string "unconfirmed_email" t.datetime "locked_at" + t.boolean "active", default: false t.datetime "created_at" t.datetime "updated_at" end - create_table "users", :force => true do |t| + create_table "users", force: true do |t| t.string "username" t.string "facebook_token" - t.string "email", :default => "", :null => false - t.string "encrypted_password", :limit => 128, :default => "", :null => false - t.string "confirmation_token" - t.datetime "confirmed_at" - t.datetime "confirmation_sent_at" + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false t.string "reset_password_token" + t.datetime "reset_password_sent_at" t.datetime "remember_created_at" - t.integer "sign_in_count", :default => 0 + t.integer "sign_in_count", default: 0 t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" - t.integer "failed_attempts", :default => 0 + t.string "confirmation_token" + t.datetime "confirmed_at" + t.datetime "confirmation_sent_at" + t.integer "failed_attempts", default: 0 t.string "unlock_token" t.datetime "locked_at" - t.string "authentication_token" t.datetime "created_at" t.datetime "updated_at" end 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 0000000000..15b0a03c43 --- /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 5b38341e87..374666ff52 100644 --- a/test/rails_app/lib/shared_admin.rb +++ b/test/rails_app/lib/shared_admin.rb @@ -1,14 +1,19 @@ +# frozen_string_literal: true + module SharedAdmin extend ActiveSupport::Concern included do devise :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable, - :unlock_strategy => :time, :lock_strategy => :none, - :allow_unconfirmed_access_for => 2.weeks, :reconfirmable => true + unlock_strategy: :time, lock_strategy: :none, + allow_unconfirmed_access_for: 2.weeks, reconfirmable: true - validates_length_of :reset_password_token, :minimum => 3, :allow_blank => true - validates_uniqueness_of :email, :allow_blank => true, :if => :email_changed? + validates_length_of :reset_password_token, minimum: 3, allow_blank: true + validates_uniqueness_of :email, allow_blank: true, if: :devise_will_save_change_to_email? end + def raw_confirmation_token + @raw_confirmation_token + end end diff --git a/test/rails_app/lib/shared_user.rb b/test/rails_app/lib/shared_user.rb index 29c262315a..e037fe867a 100644 --- a/test/rails_app/lib/shared_user.rb +++ b/test/rails_app/lib/shared_user.rb @@ -1,18 +1,24 @@ +# frozen_string_literal: true + module SharedUser extend ActiveSupport::Concern included do devise :database_authenticatable, :confirmable, :lockable, :recoverable, - :registerable, :rememberable, :timeoutable, :token_authenticatable, - :trackable, :validatable, :omniauthable + :registerable, :rememberable, :timeoutable, + :trackable, :validatable, :omniauthable, password_length: 7..72, + reconfirmable: false attr_accessor :other_key - attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :confirmation_sent_at # They need to be included after Devise is called. extend ExtendMethods end + def raw_confirmation_token + @raw_confirmation_token + end + module ExtendMethods def new_with_session(params, session) super.tap do |user| diff --git a/test/rails_app/lib/shared_user_without_email.rb b/test/rails_app/lib/shared_user_without_email.rb new file mode 100644 index 0000000000..5a86729ff9 --- /dev/null +++ b/test/rails_app/lib/shared_user_without_email.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module SharedUserWithoutEmail + extend ActiveSupport::Concern + + included do + # NOTE: This is missing :validatable and :confirmable, as they both require + # an email field at the moment. It is also missing :omniauthable because that + # adds unnecessary complexity to the setup + devise :database_authenticatable, :lockable, :recoverable, + :registerable, :rememberable, :timeoutable, + :trackable + end + + # This test stub is a bit rubbish because it's tied very closely to the + # implementation where we care about this one case. However, completely + # removing the email field breaks "recoverable" tests completely, so we are + # just taking the approach here that "email" is something that is a not an + # ActiveRecord field. + def email_changed? + raise NoMethodError + end + + def respond_to?(method_name, include_all = false) + return false if method_name.to_sym == :email_changed? + super(method_name, include_all) + end +end diff --git a/test/rails_app/lib/shared_user_without_omniauth.rb b/test/rails_app/lib/shared_user_without_omniauth.rb new file mode 100644 index 0000000000..7b9ae08fd4 --- /dev/null +++ b/test/rails_app/lib/shared_user_without_omniauth.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module SharedUserWithoutOmniauth + extend ActiveSupport::Concern + + included do + devise :database_authenticatable, :confirmable, :lockable, :recoverable, + :registerable, :rememberable, :timeoutable, + :trackable, :validatable, reconfirmable: false + end + + def raw_confirmation_token + @raw_confirmation_token + end +end diff --git a/test/rails_app/script/rails b/test/rails_app/script/rails deleted file mode 100755 index ec22bf978b..0000000000 --- a/test/rails_app/script/rails +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env ruby -# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. - -ENV_PATH = File.expand_path('../../config/environment', __FILE__) -BOOT_PATH = File.expand_path('../../config/boot', __FILE__) -APP_PATH = File.expand_path('../../config/application', __FILE__) -ROOT_PATH = File.expand_path('../..', __FILE__) - -require BOOT_PATH -require 'rails/commands' diff --git a/test/rails_test.rb b/test/rails_test.rb new file mode 100644 index 0000000000..64ff82cda6 --- /dev/null +++ b/test/rails_test.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require 'test_helper' + +class RailsTest < ActiveSupport::TestCase + test 'correct initializer position' do + initializer = Devise::Engine.initializers.detect { |i| i.name == 'devise.omniauth' } + 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 25d0cc77d5..20ba311727 100644 --- a/test/routes_test.rb +++ b/test/routes_test.rb @@ -1,108 +1,112 @@ +# frozen_string_literal: true + require 'test_helper' +ExpectedRoutingError = Minitest::Assertion + class DefaultRoutingTest < ActionController::TestCase test 'map new user session' do - assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, {:path => 'users/sign_in', :method => :get}) + assert_recognizes({controller: 'devise/sessions', action: 'new'}, {path: 'users/sign_in', method: :get}) assert_named_route "/users/sign_in", :new_user_session_path end test 'map create user session' do - assert_recognizes({:controller => 'devise/sessions', :action => 'create'}, {:path => 'users/sign_in', :method => :post}) + assert_recognizes({controller: 'devise/sessions', action: 'create'}, {path: 'users/sign_in', method: :post}) assert_named_route "/users/sign_in", :user_session_path end test 'map destroy user session' do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => 'users/sign_out', :method => :get}) + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: 'users/sign_out', method: :delete}) assert_named_route "/users/sign_out", :destroy_user_session_path end test 'map new user confirmation' do - assert_recognizes({:controller => 'devise/confirmations', :action => 'new'}, 'users/confirmation/new') + assert_recognizes({controller: 'devise/confirmations', action: 'new'}, 'users/confirmation/new') assert_named_route "/users/confirmation/new", :new_user_confirmation_path end test 'map create user confirmation' do - assert_recognizes({:controller => 'devise/confirmations', :action => 'create'}, {:path => 'users/confirmation', :method => :post}) + assert_recognizes({controller: 'devise/confirmations', action: 'create'}, {path: 'users/confirmation', method: :post}) assert_named_route "/users/confirmation", :user_confirmation_path end test 'map show user confirmation' do - assert_recognizes({:controller => 'devise/confirmations', :action => 'show'}, {:path => 'users/confirmation', :method => :get}) + assert_recognizes({controller: 'devise/confirmations', action: 'show'}, {path: 'users/confirmation', method: :get}) end test 'map new user password' do - assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'users/password/new') + assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'users/password/new') assert_named_route "/users/password/new", :new_user_password_path end test 'map create user password' do - assert_recognizes({:controller => 'devise/passwords', :action => 'create'}, {:path => 'users/password', :method => :post}) + assert_recognizes({controller: 'devise/passwords', action: 'create'}, {path: 'users/password', method: :post}) assert_named_route "/users/password", :user_password_path end test 'map edit user password' do - assert_recognizes({:controller => 'devise/passwords', :action => 'edit'}, 'users/password/edit') + assert_recognizes({controller: 'devise/passwords', action: 'edit'}, 'users/password/edit') assert_named_route "/users/password/edit", :edit_user_password_path end test 'map update user password' do - assert_recognizes({:controller => 'devise/passwords', :action => 'update'}, {:path => 'users/password', :method => :put}) + assert_recognizes({controller: 'devise/passwords', action: 'update'}, {path: 'users/password', method: :put}) end test 'map new user unlock' do - assert_recognizes({:controller => 'devise/unlocks', :action => 'new'}, 'users/unlock/new') + assert_recognizes({controller: 'devise/unlocks', action: 'new'}, 'users/unlock/new') assert_named_route "/users/unlock/new", :new_user_unlock_path end test 'map create user unlock' do - assert_recognizes({:controller => 'devise/unlocks', :action => 'create'}, {:path => 'users/unlock', :method => :post}) + assert_recognizes({controller: 'devise/unlocks', action: 'create'}, {path: 'users/unlock', method: :post}) assert_named_route "/users/unlock", :user_unlock_path end test 'map show user unlock' do - assert_recognizes({:controller => 'devise/unlocks', :action => 'show'}, {:path => 'users/unlock', :method => :get}) + assert_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: 'users/unlock', method: :get}) end test 'map new user registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, 'users/sign_up') + assert_recognizes({controller: 'devise/registrations', action: 'new'}, 'users/sign_up') assert_named_route "/users/sign_up", :new_user_registration_path end test 'map create user registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'create'}, {:path => 'users', :method => :post}) + assert_recognizes({controller: 'devise/registrations', action: 'create'}, {path: 'users', method: :post}) assert_named_route "/users", :user_registration_path end test 'map edit user registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'edit'}, {:path => 'users/edit', :method => :get}) + assert_recognizes({controller: 'devise/registrations', action: 'edit'}, {path: 'users/edit', method: :get}) assert_named_route "/users/edit", :edit_user_registration_path end test 'map update user registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'update'}, {:path => 'users', :method => :put}) + assert_recognizes({controller: 'devise/registrations', action: 'update'}, {path: 'users', method: :put}) end test 'map destroy user registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'destroy'}, {:path => 'users', :method => :delete}) + assert_recognizes({controller: 'devise/registrations', action: 'destroy'}, {path: 'users', method: :delete}) end test 'map cancel user registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'cancel'}, {:path => 'users/cancel', :method => :get}) + assert_recognizes({controller: 'devise/registrations', action: 'cancel'}, {path: 'users/cancel', method: :get}) assert_named_route "/users/cancel", :cancel_user_registration_path end test 'map omniauth callbacks' do - assert_recognizes({:controller => 'users/omniauth_callbacks', :action => 'facebook'}, {:path => 'users/auth/facebook/callback', :method => :get}) - assert_recognizes({:controller => 'users/omniauth_callbacks', :action => 'facebook'}, {:path => 'users/auth/facebook/callback', :method => :post}) - assert_named_route "/users/auth/facebook/callback", :user_omniauth_callback_path, :facebook + assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :get}) + assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :post}) + assert_named_route "/users/auth/facebook/callback", :user_facebook_omniauth_callback_path # named open_id - assert_recognizes({:controller => 'users/omniauth_callbacks', :action => 'google'}, {:path => 'users/auth/google/callback', :method => :get}) - assert_recognizes({:controller => 'users/omniauth_callbacks', :action => 'google'}, {:path => 'users/auth/google/callback', :method => :post}) - assert_named_route "/users/auth/google/callback", :user_omniauth_callback_path, :google + assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :get}) + assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :post}) + assert_named_route "/users/auth/google/callback", :user_google_omniauth_callback_path - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'ysers/omniauth_callbacks', :action => 'twitter'}, {:path => 'users/auth/twitter/callback', :method => :get}) + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'ysers/omniauth_callbacks', action: 'twitter'}, {path: 'users/auth/twitter/callback', method: :get}) end end @@ -115,134 +119,158 @@ def assert_named_route(result, *args) class CustomizedRoutingTest < ActionController::TestCase test 'map admin with :path option' do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'admin_area/sign_up', :method => :get}) + assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'admin_area/sign_up', method: :get}) end test 'map admin with :controllers option' do - assert_recognizes({:controller => 'admins/sessions', :action => 'new'}, {:path => 'admin_area/sign_in', :method => :get}) + assert_recognizes({controller: 'admins/sessions', action: 'new'}, {path: 'admin_area/sign_in', method: :get}) end test 'does not map admin password' do - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'admin_area/password/new') + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'admin_area/password/new') end end test 'subdomain admin' do - assert_recognizes({"host"=>"sub.example.com", :controller => 'devise/sessions', :action => 'new'}, {:host => "sub.example.com", :path => '/sub_admin/sign_in', :method => :get}) + assert_recognizes({"host"=>"sub.example.com", controller: 'devise/sessions', action: 'new'}, {host: "sub.example.com", path: '/sub_admin/sign_in', method: :get}) end test 'does only map reader password' do - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, 'reader/sessions/new') + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/sessions', action: 'new'}, 'reader/sessions/new') end - assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'reader/password/new') + assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'reader/password/new') end test 'map account with custom path name for session sign in' do - assert_recognizes({:controller => 'devise/sessions', :action => 'new', :locale => 'en'}, '/en/accounts/login') + assert_recognizes({controller: 'devise/sessions', action: 'new', locale: 'en'}, '/en/accounts/login') end test 'map account with custom path name for session sign out' do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy', :locale => 'en'}, '/en/accounts/logout') + assert_recognizes({controller: 'devise/sessions', action: 'destroy', locale: 'en'}, {path: '/en/accounts/logout', method: :delete }) end test 'map account with custom path name for password' do - assert_recognizes({:controller => 'devise/passwords', :action => 'new', :locale => 'en'}, '/en/accounts/secret/new') + assert_recognizes({controller: 'devise/passwords', action: 'new', locale: 'en'}, '/en/accounts/secret/new') end test 'map account with custom path name for registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'new', :locale => 'en'}, '/en/accounts/management/register') + assert_recognizes({controller: 'devise/registrations', action: 'new', locale: 'en'}, '/en/accounts/management/register') + end + + test 'map account with custom path name for edit registration' do + assert_recognizes({controller: 'devise/registrations', action: 'edit', locale: 'en'}, '/en/accounts/management/edit/profile') end test 'map account with custom path name for cancel registration' do - assert_recognizes({:controller => 'devise/registrations', :action => 'cancel', :locale => 'en'}, '/en/accounts/management/giveup') + assert_recognizes({controller: 'devise/registrations', action: 'cancel', locale: 'en'}, '/en/accounts/management/giveup') end test 'map deletes with :sign_out_via option' do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/deletes/sign_out', :method => :delete}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/deletes/sign_out', :method => :get}) + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/deletes/sign_out', method: :delete}) + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/deletes/sign_out', method: :get}) end end test 'map posts with :sign_out_via option' do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/posts/sign_out', :method => :post}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/posts/sign_out', :method => :get}) + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :post}) + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :get}) end end test 'map delete_or_posts with :sign_out_via option' do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/delete_or_posts/sign_out', :method => :post}) - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/delete_or_posts/sign_out', :method => :delete}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/delete_or_posts/sign_out', :method => :get}) + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :post}) + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :delete}) + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :get}) end end - + test 'map with constraints defined in hash' do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://192.168.1.100/headquarters/sign_up', :method => :get}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://10.0.0.100/headquarters/sign_up', :method => :get}) + assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://192.168.1.100/headquarters/sign_up', method: :get}) + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://10.0.0.100/headquarters/sign_up', method: :get}) end end - + test 'map with constraints defined in block' do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://192.168.1.100/homebase/sign_up', :method => :get}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://10.0.0.100//homebase/sign_up', :method => :get}) + assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://192.168.1.100/homebase/sign_up', method: :get}) + assert_raise ExpectedRoutingError do + assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://10.0.0.100//homebase/sign_up', method: :get}) end end - + test 'map with format false for sessions' do - assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, {:path => '/htmlonly_admin/sign_in', :method => :get}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, {:path => '/htmlonly_admin/sign_in.xml', :method => :get}) + expected_params = {controller: 'devise/sessions', action: 'new'} + + assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in', method: :get}) + assert_raise ExpectedRoutingError do + assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in.json', method: :get}) end end - + test 'map with format false for passwords' do - assert_recognizes({:controller => 'devise/passwords', :action => 'create'}, {:path => '/htmlonly_admin/password', :method => :post}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/passwords', :action => 'create'}, {:path => '/htmlonly_admin/password.xml', :method => :post}) + expected_params = {controller: 'devise/passwords', action: 'create'} + + assert_recognizes(expected_params, {path: '/htmlonly_admin/password', method: :post}) + assert_raise ExpectedRoutingError do + assert_recognizes(expected_params, {path: '/htmlonly_admin/password.json', method: :post}) end end - + test 'map with format false for registrations' do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => '/htmlonly_admin/sign_up', :method => :get}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => '/htmlonly_admin/sign_up.xml', :method => :get}) + expected_params = {controller: 'devise/registrations', action: 'new'} + + assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up', method: :get}) + assert_raise ExpectedRoutingError do + assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up.json', method: :get}) end end - + test 'map with format false for confirmations' do - assert_recognizes({:controller => 'devise/confirmations', :action => 'show'}, {:path => '/htmlonly_users/confirmation', :method => :get}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/confirmations', :action => 'show'}, {:path => '/htmlonly_users/confirmation.xml', :method => :get}) + expected_params = {controller: 'devise/confirmations', action: 'show'} + + assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation', method: :get}) + assert_raise ExpectedRoutingError do + assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation.json', method: :get}) end end - + test 'map with format false for unlocks' do - assert_recognizes({:controller => 'devise/unlocks', :action => 'show'}, {:path => '/htmlonly_users/unlock', :method => :get}) - assert_raise ActionController::RoutingError do - assert_recognizes({:controller => 'devise/unlocks', :action => 'show'}, {:path => '/htmlonly_users/unlock.xml', :method => :get}) + expected_params = {controller: 'devise/unlocks', action: 'show'} + + assert_recognizes(expected_params, {path: '/htmlonly_users/unlock', method: :get}) + assert_raise ExpectedRoutingError do + 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 + e = assert_raise ArgumentError do + routes = ActionDispatch::Routing::RouteSet.new + routes.draw do + devise_for :not_omniauthable, class_name: 'Admin', controllers: {omniauth_callbacks: "users/omniauth_callbacks"} + end + end + assert_match "Mapping omniauth_callbacks on a resource that is not omniauthable", e.message end end class ScopedRoutingTest < ActionController::TestCase test 'map publisher account' do - assert_recognizes({:controller => 'publisher/registrations', :action => 'new'}, {:path => '/publisher/accounts/sign_up', :method => :get}) + assert_recognizes({controller: 'publisher/registrations', action: 'new'}, {path: '/publisher/accounts/sign_up', method: :get}) assert_equal '/publisher/accounts/sign_up', @routes.url_helpers.new_publisher_account_registration_path end test 'map publisher account merges path names' do - assert_recognizes({:controller => 'publisher/sessions', :action => 'new'}, {:path => '/publisher/accounts/get_in', :method => :get}) + assert_recognizes({controller: 'publisher/sessions', action: 'new'}, {path: '/publisher/accounts/get_in', method: :get}) assert_equal '/publisher/accounts/get_in', @routes.url_helpers.new_publisher_account_session_path end end diff --git a/test/support/action_controller/record_identifier.rb b/test/support/action_controller/record_identifier.rb new file mode 100644 index 0000000000..3d6c61e8b9 --- /dev/null +++ b/test/support/action_controller/record_identifier.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +# Since webrat uses ActionController::RecordIdentifier class that was moved to +# ActionView namespace in Rails 4.1+ + +unless defined?(ActionController::RecordIdentifier) + require 'action_view/record_identifier' + + module ActionController + RecordIdentifier = ActionView::RecordIdentifier + end +end diff --git a/test/support/assertions.rb b/test/support/assertions.rb index 7937969d58..9872a0ae40 100644 --- a/test/support/assertions.rb +++ b/test/support/assertions.rb @@ -1,18 +1,15 @@ +# frozen_string_literal: true + require 'active_support/test_case' class ActiveSupport::TestCase - def assert_not(assertion) - assert !assertion - end - def assert_blank(assertion) assert assertion.blank? end - def assert_not_blank(assertion) - assert !assertion.blank? + def assert_present(assertion) + assert assertion.present? end - alias :assert_present :assert_not_blank def assert_email_sent(address = nil, &block) assert_difference('ActionMailer::Base.deliveries.size', &block) @@ -25,13 +22,6 @@ def assert_email_not_sent(&block) assert_no_difference('ActionMailer::Base.deliveries.size', &block) end - def assert_same_content(result, expected) - assert expected.size == result.size, "the arrays doesn't have the same size" - expected.each do |element| - assert result.include?(element), "The array doesn't include '#{element}'." - end - end - def assert_raise_with_message(exception_klass, message, &block) exception = assert_raise exception_klass, &block assert_equal exception.message, message, diff --git a/test/support/helpers.rb b/test/support/helpers.rb index a2554485e9..01dc6aa562 100644 --- a/test/support/helpers.rb +++ b/test/support/helpers.rb @@ -1,19 +1,22 @@ +# frozen_string_literal: true + require 'active_support/test_case' class ActiveSupport::TestCase - VALID_AUTHENTICATION_TOKEN = 'AbCdEfGhIjKlMnOpQrSt'.freeze - def setup_mailer ActionMailer::Base.deliveries = [] end def store_translations(locale, translations, &block) - begin - I18n.backend.store_translations(locale, translations) - yield - ensure - I18n.reload! - end + # Calling 'available_locales' before storing the translations to ensure + # that the I18n backend will be initialized before we store our custom + # translations, so they will always override the translations for the + # YML file. + I18n.available_locales + I18n.backend.store_translations(locale, translations) + yield + ensure + I18n.reload! end def generate_unique_email @@ -22,27 +25,35 @@ def generate_unique_email "test#{@@email_count}@example.com" end - def valid_attributes(attributes={}) - { :username => "usertest", - :email => generate_unique_email, - :password => '12345678', - :password_confirmation => '12345678' }.update(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 = {}) + 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) @@ -60,32 +71,22 @@ def swap(object, new_values) end end - def clear_cached_variables(options) - if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys) - Devise.mappings.each do |_, mapping| - mapping.to.instance_variable_set(:@devise_param_filter, nil) - 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 swap_module_method_existence(klass, method) - klass.module_eval %Q[ - class << self - alias #{method}_referenced #{method} - undef #{method} + def clear_cached_variables(options) + if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys) + Devise.mappings.each do |_, mapping| + mapping.to.instance_variable_set(:@devise_parameter_filter, nil) end - ] - - begin - yield if block_given? - ensure - - klass.module_eval %Q[ - class << self - alias #{method} #{method}_referenced - undef #{method}_referenced - end - ] end end end diff --git a/test/support/http_method_compatibility.rb b/test/support/http_method_compatibility.rb new file mode 100644 index 0000000000..44d80dffd1 --- /dev/null +++ b/test/support/http_method_compatibility.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module Devise + class IntegrationTest < ActionDispatch::IntegrationTest + end + + class ControllerTestCase < ActionController::TestCase + end +end diff --git a/test/support/integration.rb b/test/support/integration.rb index 9a451c531f..3ed0d85aaf 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,52 +7,53 @@ def warden request.env['warden'] end - def create_user(options={}) + def create_user(options = {}) @user ||= begin user = User.create!( - :username => 'usertest', - :email => options[:email] || 'user@test.com', - :password => options[:password] || '12345678', - :password_confirmation => options[:password] || '12345678', - :created_at => Time.now.utc + username: 'usertest', + email: options[:email] || 'user@test.com', + password: options[:password] || '12345678', + password_confirmation: options[:password] || '12345678', + created_at: Time.now.utc ) user.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at] - user.confirm! unless options[:confirm] == false + 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', - :password => '123456', :password_confirmation => '123456', - :active => options[:active] + email: options[:email] || 'admin@test.com', + password: '123456', password_confirmation: '123456', + active: options[:active] ) - admin.confirm! unless options[:confirm] == false + admin.confirm unless options[:confirm] == false admin 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' - fill_in 'password', :with => options[:password] || '12345678' + fill_in 'email', with: options[:email] || 'user@test.com' + fill_in 'password', with: options[:password] || '12345678' check 'remember me' if options[:remember_me] == true yield if block_given? - click_button 'Sign In' + click_button 'Log In' 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' - fill_in 'password', :with => '123456' + fill_in 'email', with: 'admin@test.com' + fill_in 'password', with: '123456' yield if block_given? - click_button 'Sign In' + click_button 'Log In' admin end @@ -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/en.yml b/test/support/locale/en.yml index e4501ceb38..e1f977b3e7 100644 --- a/test/support/locale/en.yml +++ b/test/support/locale/en.yml @@ -1,4 +1,8 @@ en: + devise: + failure: + user: + does_not_exist: "User %{name} does not exist" errors: messages: taken: "has already been taken" diff --git a/test/support/locale/pt-BR.yml b/test/support/locale/pt-BR.yml new file mode 100644 index 0000000000..687cc87ae6 --- /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 new file mode 100644 index 0000000000..d55de92509 --- /dev/null +++ b/test/support/mongoid.yml @@ -0,0 +1,6 @@ +test: + clients: + default: + database: devise-test-suite + hosts: + - localhost:<%= ENV['MONGODB_PORT'] || '27017' %> diff --git a/test/support/webrat/integrations/rails.rb b/test/support/webrat/integrations/rails.rb index 03821d2628..a78d04e662 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' @@ -14,6 +16,21 @@ def logger # :nodoc: ::Rails.logger end 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) + update_protocol(url) + integration_session.send(http_method, normalize_url(url), params: data, headers: headers) + end + end end module ActionDispatch #:nodoc: diff --git a/test/support/webrat/matchers.rb b/test/support/webrat/matchers.rb new file mode 100644 index 0000000000..24d71df3d9 --- /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_helpers_test.rb b/test/test/controller_helpers_test.rb similarity index 50% rename from test/test_helpers_test.rb rename to test/test/controller_helpers_test.rb index ff4a167741..a158e87536 100644 --- a/test/test_helpers_test.rb +++ b/test/test/controller_helpers_test.rb @@ -1,15 +1,11 @@ +# frozen_string_literal: true + require 'test_helper' -class TestHelpersTest < ActionController::TestCase +class TestControllerHelpersTest < Devise::ControllerTestCase tests UsersController - include Devise::TestHelpers + include Devise::Test::ControllerHelpers - class CustomFailureApp < Devise::FailureApp - def redirect - self.status = 306 - end - end - test "redirects if attempting to access a page unauthenticated" do get :index assert_redirected_to new_user_session_path @@ -17,9 +13,9 @@ def redirect end test "redirects if attempting to access a page with an unconfirmed account" do - swap Devise, :allow_unconfirmed_access_for => 0 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 @@ -28,19 +24,19 @@ def redirect end test "returns nil if accessing current_user with an unconfirmed account" do - swap Devise, :allow_unconfirmed_access_for => 0 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, :id => user + get :accept, params: { id: user } assert_nil assigns(:current_user) end end test "does not redirect with valid user" do user = create_user - user.confirm! + user.confirm sign_in user get :index @@ -52,7 +48,7 @@ def redirect assert_response :redirect user = create_user - user.confirm! + user.confirm sign_in user get :index @@ -61,7 +57,7 @@ def redirect test "redirects if valid user signed out" do user = create_user - user.confirm! + user.confirm sign_in user get :index @@ -70,25 +66,59 @@ def redirect get :index assert_redirected_to new_user_session_path end - + test "respects custom failure app" do - begin - Devise.warden_config.failure_app = CustomFailureApp + custom_failure_app = Class.new(Devise::FailureApp) do + def redirect + self.status = 300 + end + end + + swap Devise.warden_config, failure_app: custom_failure_app do get :index - assert_response 306 - ensure - Devise.warden_config.failure_app = Devise::FailureApp + assert_response 300 + end + end + + test "passes given headers from the failure app to the response" do + custom_failure_app = Class.new(Devise::FailureApp) do + def respond + self.status = 401 + self.response.headers["CUSTOMHEADER"] = 1 + end + end + + swap Devise.warden_config, failure_app: custom_failure_app do + sign_in create_user + get :index + assert_equal 1, @response.headers["CUSTOMHEADER"] + end + end + + test "returns the body of a failure app" do + get :index + + 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 user = create_user - user.confirm! + user.confirm sign_in user ensure Warden::Manager._after_set_user.pop @@ -96,12 +126,12 @@ def redirect 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 user = create_user - user.confirm! + user.confirm sign_in user sign_out user @@ -129,7 +159,7 @@ def redirect test "allows to sign in with different users" do first_user = create_user - first_user.confirm! + first_user.confirm sign_in first_user get :index @@ -137,10 +167,42 @@ def redirect sign_out first_user second_user = create_user - second_user.confirm! + second_user.confirm sign_in second_user get :index assert_match /User ##{second_user.id}/, @response.body end + + test "creates a new warden proxy if the request object has changed" do + old_warden_proxy = warden + + @request = ActionController::TestRequest.create(Class.new) # needs a "controller class" + + new_warden_proxy = warden + + assert_not_equal old_warden_proxy, new_warden_proxy + end + + test "doesn't create a new warden proxy if the request object hasn't changed" do + old_warden_proxy = warden + new_warden_proxy = warden + + 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 new file mode 100644 index 0000000000..7f579a8da3 --- /dev/null +++ b/test/test/integration_helpers_test.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require 'test_helper' + +class TestIntegrationsHelpersTest < Devise::IntegrationTest + include Devise::Test::IntegrationHelpers + + test '#sign_in signs in the resource directly' do + sign_in(create_user) + + visit '/' + assert warden.authenticated?(:user) + end + + test '#sign_outs signs out in the resource directly' do + user = create_user + sign_in user + sign_out user + + visit '/' + assert_not warden.authenticated?(:user) + end + + test '#sign_out does not signs out other scopes' do + sign_in(create_user) + sign_in(create_admin) + sign_out :user + + visit '/' + + assert_not warden.authenticated?(:user) + assert warden.authenticated?(:admin) + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index f3659efadb..e6df812037 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,15 +10,22 @@ 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' +require 'mocha/minitest' +require 'timecop' require 'webrat' Webrat.configure do |config| config.mode = :rails config.open_error_files = false end +if ActiveSupport.respond_to?(:test_order) + ActiveSupport.test_order = :random +end + +OmniAuth.config.logger = Logger.new('/dev/null') + # Add support to load paths so we can overwrite broken webrat setup $:.unshift File.expand_path('../support', __FILE__) Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } @@ -25,3 +34,4 @@ require "rails/generators/test_case" require "generators/devise/install_generator" require "generators/devise/views_generator" +require "generators/devise/controllers_generator" diff --git a/test/test_models.rb b/test/test_models.rb new file mode 100644 index 0000000000..0e52bef430 --- /dev/null +++ b/test/test_models.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +class Configurable < User + devise :database_authenticatable, :confirmable, :rememberable, :timeoutable, :lockable, + stretches: 15, pepper: 'abcdef', allow_unconfirmed_access_for: 5.days, + remember_for: 7.days, timeout_in: 15.minutes, unlock_in: 10.days +end + +class WithValidation < Admin + devise :database_authenticatable, :validatable, password_length: 2..6 +end + +class UserWithValidation < User + validates_presence_of :username +end + +class UserWithCustomHashing < User + protected + def password_digest(password) + password.reverse + end +end + +class UserWithVirtualAttributes < User + devise case_insensitive_keys: [:email, :email_confirmation] + validates :email, presence: true, confirmation: { on: :create } +end + +class Several < Admin + devise :validatable + devise :lockable +end + +class Inheritable < Admin +end