├── .codeclimate.yml ├── .gitattributes ├── .gitbook.yaml ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── dependabot.yml └── workflows │ └── test.yml ├── .github_changelog_generator ├── .gitignore ├── .rubocop.yml ├── .rubocop_todo.yml ├── Appraisals ├── CHANGELOG.md ├── Gemfile ├── Guardfile ├── LICENSE ├── README.md ├── Rakefile ├── SUMMARY.md ├── app ├── controllers │ └── devise_token_auth │ │ ├── application_controller.rb │ │ ├── concerns │ │ ├── resource_finder.rb │ │ └── set_user_by_token.rb │ │ ├── confirmations_controller.rb │ │ ├── omniauth_callbacks_controller.rb │ │ ├── passwords_controller.rb │ │ ├── registrations_controller.rb │ │ ├── sessions_controller.rb │ │ ├── token_validations_controller.rb │ │ └── unlocks_controller.rb ├── models │ └── devise_token_auth │ │ └── concerns │ │ ├── active_record_support.rb │ │ ├── confirmable_support.rb │ │ ├── mongoid_support.rb │ │ ├── tokens_serialization.rb │ │ ├── user.rb │ │ └── user_omniauth_callbacks.rb ├── validators │ └── devise_token_auth_email_validator.rb └── views │ ├── devise │ └── mailer │ │ ├── confirmation_instructions.html.erb │ │ ├── reset_password_instructions.html.erb │ │ └── unlock_instructions.html.erb │ └── devise_token_auth │ └── omniauth_external_window.html.erb ├── bin └── rails ├── config └── locales │ ├── da-DK.yml │ ├── de.yml │ ├── en.yml │ ├── es.yml │ ├── fa.yml │ ├── fr.yml │ ├── he.yml │ ├── it.yml │ ├── ja.yml │ ├── ko.yml │ ├── nl.yml │ ├── pl.yml │ ├── pt-BR.yml │ ├── pt.yml │ ├── ro.yml │ ├── ru.yml │ ├── sq.yml │ ├── sv.yml │ ├── uk.yml │ ├── vi.yml │ ├── zh-CN.yml │ ├── zh-HK.yml │ └── zh-TW.yml ├── devise_token_auth.gemspec ├── docs ├── conceptual.md ├── config │ ├── README.md │ ├── cors.md │ ├── devise.md │ ├── email_auth.md │ ├── initialization.md │ └── omniauth.md ├── faq.md ├── installation.md ├── password_diagram_reset.jpg ├── security.md └── usage │ ├── README.md │ ├── controller_methods.md │ ├── excluding_models.md │ ├── model_concerns.md │ ├── multiple_models.md │ ├── overrides.md │ ├── reset_password.md │ ├── routes.md │ └── testing.md ├── gemfiles ├── rails_4_2.gemfile ├── rails_4_2_mongoid_5.gemfile ├── rails_5_0.gemfile ├── rails_5_1.gemfile ├── rails_5_1_mongoid_6.gemfile ├── rails_5_1_mongoid_7.gemfile ├── rails_5_2.gemfile ├── rails_5_2_mongoid_6.gemfile ├── rails_5_2_mongoid_7.gemfile ├── rails_6_0.gemfile ├── rails_6_0_mongoid_7.gemfile ├── rails_7_0.gemfile └── rails_7_0_mongoid_7.gemfile ├── lib ├── devise_token_auth.rb ├── devise_token_auth │ ├── blacklist.rb │ ├── controllers │ │ ├── helpers.rb │ │ └── url_helpers.rb │ ├── engine.rb │ ├── errors.rb │ ├── rails │ │ └── routes.rb │ ├── token_factory.rb │ ├── url.rb │ └── version.rb ├── generators │ └── devise_token_auth │ │ ├── USAGE │ │ ├── install_generator.rb │ │ ├── install_generator_helpers.rb │ │ ├── install_mongoid_generator.rb │ │ ├── install_views_generator.rb │ │ └── templates │ │ ├── devise_token_auth.rb │ │ ├── devise_token_auth_create_users.rb.erb │ │ ├── user.rb.erb │ │ └── user_mongoid.rb.erb └── tasks │ └── devise_token_auth_tasks.rake └── test ├── controllers ├── custom │ ├── custom_confirmations_controller_test.rb │ ├── custom_omniauth_callbacks_controller_test.rb │ ├── custom_passwords_controller_test.rb │ ├── custom_registrations_controller_test.rb │ ├── custom_sessions_controller_test.rb │ └── custom_token_validations_controller_test.rb ├── demo_group_controller_test.rb ├── demo_mang_controller_test.rb ├── demo_user_controller_test.rb ├── devise_token_auth │ ├── confirmations_controller_test.rb │ ├── omniauth_callbacks_controller_test.rb │ ├── passwords_controller_test.rb │ ├── registrations_controller_test.rb │ ├── sessions_controller_test.rb │ ├── token_validations_controller_test.rb │ └── unlocks_controller_test.rb └── overrides │ ├── confirmations_controller_test.rb │ ├── omniauth_callbacks_controller_test.rb │ ├── passwords_controller_test.rb │ ├── registrations_controller_test.rb │ ├── sessions_controller_test.rb │ └── token_validations_controller_test.rb ├── dummy ├── .powder ├── README.rdoc ├── Rakefile ├── app │ ├── active_record │ │ ├── confirmable_user.rb │ │ ├── lockable_user.rb │ │ ├── mang.rb │ │ ├── only_email_user.rb │ │ ├── scoped_user.rb │ │ ├── unconfirmable_user.rb │ │ ├── unregisterable_user.rb │ │ └── user.rb │ ├── assets │ │ └── images │ │ │ ├── logo.jpg │ │ │ └── omniauth-provider-settings.png │ ├── controllers │ │ ├── application_controller.rb │ │ ├── auth_origin_controller.rb │ │ ├── custom │ │ │ ├── confirmations_controller.rb │ │ │ ├── omniauth_callbacks_controller.rb │ │ │ ├── passwords_controller.rb │ │ │ ├── registrations_controller.rb │ │ │ ├── sessions_controller.rb │ │ │ └── token_validations_controller.rb │ │ ├── demo_group_controller.rb │ │ ├── demo_mang_controller.rb │ │ ├── demo_user_controller.rb │ │ └── overrides │ │ │ ├── confirmations_controller.rb │ │ │ ├── omniauth_callbacks_controller.rb │ │ │ ├── passwords_controller.rb │ │ │ ├── registrations_controller.rb │ │ │ ├── sessions_controller.rb │ │ │ └── token_validations_controller.rb │ ├── helpers │ │ └── application_helper.rb │ ├── models │ │ └── concerns │ │ │ └── favorite_color.rb │ ├── mongoid │ │ ├── confirmable_user.rb │ │ ├── lockable_user.rb │ │ ├── mang.rb │ │ ├── only_email_user.rb │ │ ├── scoped_user.rb │ │ ├── unconfirmable_user.rb │ │ ├── unregisterable_user.rb │ │ └── user.rb │ └── views │ │ └── layouts │ │ └── application.html.erb ├── bin │ ├── bundle │ ├── rails │ ├── rake │ └── spring ├── config.ru ├── config │ ├── application.rb │ ├── application.yml.bk │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── backtrace_silencers.rb │ │ ├── cookies_serializer.rb │ │ ├── devise.rb │ │ ├── devise_token_auth.rb │ │ ├── figaro.rb │ │ ├── filter_parameter_logging.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── omniauth.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ └── en.yml │ ├── mongoid.yml │ ├── routes.rb │ ├── secrets.yml │ └── spring.rb ├── db │ ├── migrate │ │ ├── 20140715061447_devise_token_auth_create_users.rb │ │ ├── 20140715061805_devise_token_auth_create_mangs.rb │ │ ├── 20140829044006_add_operating_thetan_to_user.rb │ │ ├── 20140916224624_add_favorite_color_to_mangs.rb │ │ ├── 20141222035835_devise_token_auth_create_only_email_users.rb │ │ ├── 20141222053502_devise_token_auth_create_unregisterable_users.rb │ │ ├── 20150708104536_devise_token_auth_create_unconfirmable_users.rb │ │ ├── 20160103235141_devise_token_auth_create_scoped_users.rb │ │ ├── 20160629184441_devise_token_auth_create_lockable_users.rb │ │ └── 20190924101113_devise_token_auth_create_confirmable_users.rb │ └── schema.rb ├── lib │ └── migration_database_helper.rb └── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ └── favicon.ico ├── factories └── users.rb ├── lib ├── devise_token_auth │ ├── blacklist_test.rb │ ├── rails │ │ ├── custom_routes_test.rb │ │ └── routes_test.rb │ ├── token_factory_test.rb │ └── url_test.rb └── generators │ └── devise_token_auth │ ├── install_generator_test.rb │ ├── install_generator_with_namespace_test.rb │ └── install_views_generator_test.rb ├── models ├── concerns │ ├── mongoid_support_test.rb │ └── tokens_serialization_test.rb ├── confirmable_user_test.rb ├── only_email_user_test.rb └── user_test.rb ├── support └── controllers │ └── routes.rb └── test_helper.rb /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | duplication: 3 | enabled: true 4 | method-count: 5 | config: 6 | threshold: 30 7 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | test/dummy/config/application.yml filter=git-crypt diff=git-crypt 2 | test/dummy/config/application.yml.bk filter=git-crypt diff=git-crypt 3 | -------------------------------------------------------------------------------- /.gitbook.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | root: ./ 3 | structure: 4 | readme: ./docs/installation.md 5 | summary: SUMMARY.md 6 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | ## Suggest changes 4 | 5 | 1. Create a feature branch with your changes. 6 | 2. Please add a test for your change. Only refactoring and documentation changes require no new tests. If you are adding functionality or fixing a bug, we need a test! 7 | 3. Make all the tests pass against `ActiveRecord` and `Mongoid`. 8 | 4. Issue a Pull Request. 9 | 10 | I will grant you commit access if you send quality pull requests. 11 | 12 | ## Run the tests 13 | 14 | **Prepare** by installing and migrating the database: 15 | 16 | 1. Clone this repo 17 | 1. Run `bundle install` 18 | 1. Run `bundle exec rake db:migrate` 19 | 1. Run `RAILS_ENV=test bundle exec rake db:migrate` 20 | 21 | Now your environment is ready to run tests. 22 | 23 | To run the full **test suite** with the [guard](https://github.com/guard/guard) test runner: 24 | 25 | ```shell 26 | bundle exec guard 27 | ``` 28 | 29 | Guard will re-run each test suite when changes are made to its corresponding files. 30 | 31 | To run **just one test**: Flavio Castelli blogged about [how to execute a single unit test (or even a single test method)](https://flavio.castelli.me/2010/05/28/how-to-run-a-single-rails-unit-test/) instead of running the complete unit test suite. 32 | 33 | To run the full **test suite** with the guard and the [appraisal](https://github.com/thoughtbot/appraisal) against `ActiveRecord`: 34 | 35 | ```shell 36 | bundle exec appraisal rails-5-1 guard 37 | # the same 38 | DEVISE_TOKEN_AUTH_ORM=active_record DB=sqlite bundle exec appraisal 39 | ``` 40 | 41 | `DB` environment variable can take `sqlite`, `mysql`, and `postgresql` values. 42 | 43 | against `Mongoid`: 44 | 45 | ```shell 46 | DEVISE_TOKEN_AUTH_ORM=mongoid bundle exec appraisal rails-5-1-mongoid-7 guard 47 | ``` 48 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | When posting issues, please include the following information to speed up the troubleshooting process: 2 | 3 | * **Version**: which version of this gem (and [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth), [jToker](https://github.com/lynndylanhurley/j-toker) or [Angular2-Token](https://github.com/neroniaky/angular2-token) if applicable) are you using? 4 | * **Request and response headers**: these can be found in the "Network" tab of your browser's web inspector. 5 | * **Rails Stacktrace**: this can be found in the `log/development.log` of your API. 6 | * **Environmental Info**: How is your application different from the [reference implementation](https://github.com/lynndylanhurley/devise_token_auth_demo)? This may include (but is not limited to) the following details: 7 | * **Routes**: are you using some crazy namespace, scope, or constraint? 8 | * **Gems**: are you using MongoDB, Grape, RailsApi, ActiveAdmin, etc.? 9 | * **Custom Overrides**: what have you done in terms of [custom controller overrides](https://github.com/lynndylanhurley/devise_token_auth/#custom-controller-overrides)? 10 | * **Custom Frontend**: are you using [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth), [jToker](https://github.com/lynndylanhurley/j-toker), [Angular2-Token](https://github.com/neroniaky/angular2-token), or something else? 11 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "bundler" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | open-pull-requests-limit: 5 13 | target-branch: "master" 14 | -------------------------------------------------------------------------------- /.github_changelog_generator: -------------------------------------------------------------------------------- 1 | bug-labels=bug,Bug,fix,Fix 2 | enhancement-labels=enhancement,Enhancement,feat,Feat 3 | since-tag=v1.1.3 4 | unreleased-label=Unreleased 5 | user=lynndylanhurley 6 | project=devise_token_auth 7 | base=CHANGELOG.md -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | test/dummy/db/*.sqlite3 5 | test/dummy/db/*.sqlite3-journal 6 | test/dummy/log/*.log 7 | test/dummy/tmp/ 8 | test/dummy/.sass-cache 9 | test/dummy/config/application.yml 10 | coverage 11 | .idea 12 | .byebug_history 13 | .irb_history 14 | .ruby-version 15 | .ruby-gemset 16 | tags 17 | 18 | Gemfile.lock 19 | 20 | # appraisal 21 | gemfiles/*.lock 22 | -------------------------------------------------------------------------------- /Appraisals: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | [ 4 | { name: '4-2', version: '4.2' } 5 | ].each do |rails| 6 | appraise "rails-#{rails[:name]}" do 7 | gem 'rails', "~> #{rails[:version]}" 8 | 9 | gem 'sqlite3', '~> 1.3.6' 10 | gem 'mysql2', '~> 0.4.10' 11 | gem 'pg', '~> 0.21' 12 | end 13 | end 14 | 15 | [ 16 | { name: '5-0', version: '5.0' }, 17 | { name: '5-1', version: '5.1' }, 18 | { name: '5-2', version: '5.2' } 19 | ].each do |rails| 20 | appraise "rails-#{rails[:name]}" do 21 | gem 'rails', "~> #{rails[:version]}" 22 | 23 | gem 'sqlite3', '~> 1.3.6' 24 | gem 'mysql2' 25 | gem 'pg' 26 | end 27 | end 28 | 29 | [ 30 | { name: '4-2', ruby: '2.3.8', rails: '4.2', mongoid: '5.4' }, 31 | { name: '5-1', ruby: '2.3.8', rails: '5.1', mongoid: '6.4' }, 32 | { name: '5-1', ruby: '2.4.5', rails: '5.1', mongoid: '7.0' }, 33 | { name: '5-2', ruby: '2.5.5', rails: '5.2', mongoid: '6.4' }, 34 | { name: '5-2', ruby: '2.5.5', rails: '5.2', mongoid: '7.0' }, 35 | { name: '5-2', ruby: '2.6.2', rails: '5.2', mongoid: '7.0' }, 36 | { name: '6-0', ruby: '2.7.0', rails: '6.0', mongoid: '7.0' }, 37 | { name: '6-0', ruby: '3.1.2', rails: '6.0', mongoid: '7.0' }, 38 | { name: '7-0', ruby: '3.1.2', rails: '7.0', mongoid: '7.0' } 39 | ].each do |set| 40 | appraise "rails-#{set[:name]}-mongoid-#{set[:mongoid][0]}" do 41 | gem 'rails', "~> #{set[:rails]}" 42 | 43 | gem 'mongoid', "~> #{set[:mongoid]}" 44 | gem 'mongoid-locker', '~> 1.0' 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | 5 | # Declare your gem's dependencies in devise_token_auth.gemspec. 6 | # Bundler will treat runtime dependencies like base dependencies, and 7 | # development dependencies will be added by default to the :development group. 8 | gemspec 9 | gem 'omniauth', '~> 2.0' 10 | gem 'omniauth-rails_csrf_protection' 11 | 12 | # Declare any dependencies that are still in development here instead of in 13 | # your gemspec. These might include edge Rails or gems from your path or 14 | # Git. Remember to move these dependencies to your gemspec before releasing 15 | # your gem to rubygems.org. 16 | 17 | # To use debugger 18 | # gem 'debugger' 19 | 20 | 21 | group :development, :test do 22 | gem 'attr_encrypted' 23 | gem 'figaro', '~> 1.2' 24 | gem 'omniauth-facebook' 25 | gem 'omniauth-github' 26 | gem 'omniauth-google-oauth2' 27 | gem 'omniauth-apple' 28 | gem 'rack-cors' 29 | gem 'thor', '~> 1.2' 30 | 31 | # testing 32 | # gem 'spring' 33 | gem 'database_cleaner' 34 | gem 'factory_bot_rails' 35 | gem 'faker', '~> 3.2' 36 | gem 'fuzz_ball' 37 | gem 'minitest' 38 | gem 'minitest-focus' 39 | gem 'minitest-rails', '~> 7' 40 | gem 'minitest-reporters' 41 | gem 'mocha', '>= 1.5' 42 | gem 'pry' 43 | gem 'pry-byebug' 44 | gem 'pry-remote' 45 | 46 | gem 'rubocop', require: false 47 | end 48 | 49 | # code coverage, metrics 50 | group :test do 51 | gem 'rails-controller-testing' 52 | gem 'simplecov', require: false 53 | end 54 | 55 | group :development do 56 | gem 'github_changelog_generator' 57 | end 58 | 59 | if ENV['MONGOID_VERSION'] 60 | case ENV['MONGOID_VERSION'] 61 | when /^7/ 62 | gem 'mongoid', '~> 7' 63 | when /^6/ 64 | gem 'mongoid', '~> 6' 65 | when /^5/ 66 | gem 'mongoid', '~> 5' 67 | else 68 | gem 'mongoid', '>= 5' 69 | end 70 | 71 | gem 'mongoid-locker', '~> 2.0' 72 | end 73 | 74 | gem "rails", "~> 7" 75 | -------------------------------------------------------------------------------- /Guardfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # A sample Guardfile 4 | # More info at https://github.com/guard/guard#readme 5 | 6 | guard :minitest do 7 | # with Minitest::Unit 8 | watch(%r{^test/(.*)\/?test_(.*)\.rb$}) 9 | watch(%r{^lib/(.*/)?([^/]+)\.rb$}) { |m| "test/#{m[1]}test_#{m[2]}.rb" } 10 | watch(%r{^test/test_helper\.rb$}) { 'test' } 11 | 12 | # with Minitest::Spec 13 | # watch(%r{^spec/(.*)_spec\.rb$}) 14 | # watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" } 15 | # watch(%r{^spec/spec_helper\.rb$}) { 'spec' } 16 | 17 | # Rails 4 18 | watch(%r{^app/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" } 19 | watch(%r{^app/controllers/application_controller\.rb$}) { 'test/controllers' } 20 | watch(%r{^app/controllers/(.+)_controller\.rb$}) { |m| "test/integration/#{m[1]}_test.rb" } 21 | watch(%r{^app/views/(.+)_mailer/.+}) { |m| "test/mailers/#{m[1]}_mailer_test.rb" } 22 | watch(%r{^lib/(.+)\.rb$}) { |m| "test/lib/#{m[1]}_test.rb" } 23 | watch(%r{^test/.+_test\.rb$}) 24 | watch(%r{^test/test_helper\.rb$}) { 'test' } 25 | 26 | # Rails < 4 27 | # watch(%r{^app/controllers/(.*)\.rb$}) { |m| "test/functional/#{m[1]}_test.rb" } 28 | # watch(%r{^app/helpers/(.*)\.rb$}) { |m| "test/helpers/#{m[1]}_test.rb" } 29 | # watch(%r{^app/models/(.*)\.rb$}) { |m| "test/unit/#{m[1]}_test.rb" } 30 | end 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | Version 2, December 2004 3 | 4 | Copyright (C) 2004 Sam Hocevar 5 | 6 | Everyone is permitted to copy and distribute verbatim or modified 7 | copies of this license document, and changing it is allowed as long 8 | as the name is changed. 9 | 10 | DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | 13 | 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | begin 4 | require 'bundler/setup' 5 | rescue LoadError 6 | puts 'You must `gem install bundler` and `bundle install` to run rake tasks' 7 | end 8 | 9 | require 'rdoc/task' 10 | 11 | RDoc::Task.new(:rdoc) do |rdoc| 12 | rdoc.rdoc_dir = 'rdoc' 13 | rdoc.title = 'DeviseTokenAuth' 14 | rdoc.options << '--line-numbers' 15 | rdoc.rdoc_files.include('README.rdoc') 16 | rdoc.rdoc_files.include('lib/**/*.rb') 17 | end 18 | 19 | APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) 20 | load 'rails/tasks/engine.rake' 21 | 22 | Bundler::GemHelper.install_tasks 23 | 24 | require 'rake/testtask' 25 | 26 | Rake::TestTask.new(:test) do |t| 27 | t.libs << 'lib' 28 | t.libs << 'test' 29 | t.pattern = 'test/**/*_test.rb' 30 | t.verbose = false 31 | t.warning = false 32 | end 33 | 34 | task default: :test 35 | 36 | require 'rubocop/rake_task' 37 | 38 | desc 'Run RuboCop' 39 | RuboCop::RakeTask.new(:rubocop) do |task| 40 | task.formatters = %w[fuubar offenses worst] 41 | task.fail_on_error = false # don't abort rake on failure 42 | end 43 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | * [Installation](docs/installation.md) 4 | * [Configuration](docs/config/README.md) 5 | * [Initializer Settings](docs/config/initialization.md) 6 | * [OmniAuth](docs/config/omniauth.md) 7 | * [Email Authentication](docs/config/email_auth.md) 8 | * [Customizing Devise Verbiage](docs/config/devise.md) 9 | * [Cross Origin Requests (CORS)](docs/config/cors.md) 10 | * [Usage](docs/usage/README.md) 11 | * [Mounting Routes](docs/usage/routes.md) 12 | * [Controller Integration](docs/usage/controller_methods.md) 13 | * [Model Integration](docs/usage/model_concerns.md) 14 | * [Using Multiple User Classes](docs/usage/multiple_models.md) 15 | * [Excluding Modules](docs/usage/excluding_models.md) 16 | * [Custom Controller/Email Overrides](docs/usage/overrides.md) 17 | * [Reset password flow](docs/usage/reset_password.md) 18 | * [Testing](docs/usage/testing.md) 19 | * [FAQ](docs/faq.md) 20 | * [Conceptual Diagrams](docs/conceptual.md) 21 | * [Token Management](docs/conceptual#about-token-management) 22 | * [Batch Requests](docs/conceptual#about-batch-requests) 23 | * [Security](docs/security.md) 24 | -------------------------------------------------------------------------------- /app/controllers/devise_token_auth/concerns/resource_finder.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth::Concerns::ResourceFinder 4 | extend ActiveSupport::Concern 5 | include DeviseTokenAuth::Controllers::Helpers 6 | 7 | def get_case_insensitive_field_from_resource_params(field) 8 | # honor Devise configuration for case_insensitive keys 9 | q_value = resource_params[field.to_sym] 10 | 11 | if resource_class.case_insensitive_keys.include?(field.to_sym) 12 | q_value.downcase! 13 | end 14 | 15 | if resource_class.strip_whitespace_keys.include?(field.to_sym) 16 | q_value.strip! 17 | end 18 | 19 | q_value 20 | end 21 | 22 | def find_resource(field, value) 23 | @resource = if database_adapter&.include?('mysql') 24 | # fix for mysql default case insensitivity 25 | field_sanitized = resource_class.connection.quote_column_name(field) 26 | resource_class.where("BINARY #{field_sanitized} = ? AND provider= ?", value, provider).first 27 | else 28 | resource_class.dta_find_by(field => value, 'provider' => provider) 29 | end 30 | end 31 | 32 | def database_adapter 33 | @database_adapter ||= begin 34 | rails_version = [Rails::VERSION::MAJOR, Rails::VERSION::MINOR].join(".") 35 | 36 | adapter = 37 | if rails_version >= "6.1" 38 | resource_class.try(:connection_db_config)&.try(:adapter) 39 | else 40 | resource_class.try(:connection_config)&.try(:[], :adapter) 41 | end 42 | end 43 | end 44 | 45 | def resource_class(m = nil) 46 | mapping = if m 47 | Devise.mappings[m] 48 | else 49 | Devise.mappings[resource_name] || Devise.mappings.values.first 50 | end 51 | 52 | mapping.to 53 | end 54 | 55 | def provider 56 | 'email' 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /app/controllers/devise_token_auth/confirmations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | class ConfirmationsController < DeviseTokenAuth::ApplicationController 5 | 6 | def show 7 | @resource = resource_class.confirm_by_token(resource_params[:confirmation_token]) 8 | 9 | if @resource.errors.empty? 10 | yield @resource if block_given? 11 | 12 | redirect_header_options = { account_confirmation_success: true } 13 | 14 | if signed_in?(resource_name) 15 | token = signed_in_resource.create_token 16 | signed_in_resource.save! 17 | 18 | redirect_headers = build_redirect_headers(token.token, 19 | token.client, 20 | redirect_header_options) 21 | 22 | redirect_to_link = signed_in_resource.build_auth_url(redirect_url, redirect_headers) 23 | else 24 | redirect_to_link = DeviseTokenAuth::Url.generate(redirect_url, redirect_header_options) 25 | end 26 | 27 | redirect_to(redirect_to_link, redirect_options) 28 | else 29 | if redirect_url 30 | redirect_to DeviseTokenAuth::Url.generate(redirect_url, account_confirmation_success: false), redirect_options 31 | else 32 | raise ActionController::RoutingError, 'Not Found' 33 | end 34 | end 35 | end 36 | 37 | def create 38 | return render_create_error_missing_email if resource_params[:email].blank? 39 | 40 | @email = get_case_insensitive_field_from_resource_params(:email) 41 | 42 | @resource = resource_class.dta_find_by(uid: @email, provider: provider) 43 | 44 | return render_not_found_error unless @resource 45 | 46 | @resource.send_confirmation_instructions({ 47 | redirect_url: redirect_url, 48 | client_config: resource_params[:config_name] 49 | }) 50 | 51 | return render_create_success 52 | end 53 | 54 | protected 55 | 56 | def render_create_error_missing_email 57 | render_error(401, I18n.t('devise_token_auth.confirmations.missing_email')) 58 | end 59 | 60 | def render_create_success 61 | render json: { 62 | success: true, 63 | message: success_message('confirmations', @email) 64 | } 65 | end 66 | 67 | def render_not_found_error 68 | if Devise.paranoid 69 | render_create_success 70 | else 71 | render_error(404, I18n.t('devise_token_auth.confirmations.user_not_found', email: @email)) 72 | end 73 | end 74 | 75 | private 76 | 77 | def resource_params 78 | params.permit(:email, :confirmation_token, :config_name) 79 | end 80 | 81 | # give redirect value from params priority or fall back to default value if provided 82 | def redirect_url 83 | params.fetch( 84 | :redirect_url, 85 | DeviseTokenAuth.default_confirm_success_url 86 | ) 87 | end 88 | end 89 | end 90 | -------------------------------------------------------------------------------- /app/controllers/devise_token_auth/token_validations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | class TokenValidationsController < DeviseTokenAuth::ApplicationController 5 | skip_before_action :assert_is_devise_resource!, only: [:validate_token] 6 | before_action :set_user_by_token, only: [:validate_token] 7 | 8 | def validate_token 9 | # @resource will have been set by set_user_by_token concern 10 | if @resource 11 | yield @resource if block_given? 12 | render_validate_token_success 13 | else 14 | render_validate_token_error 15 | end 16 | end 17 | 18 | protected 19 | 20 | def render_validate_token_success 21 | render json: { 22 | success: true, 23 | data: resource_data(resource_json: @resource.token_validation_response) 24 | } 25 | end 26 | 27 | def render_validate_token_error 28 | render_error(401, I18n.t('devise_token_auth.token_validations.invalid')) 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/controllers/devise_token_auth/unlocks_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | class UnlocksController < DeviseTokenAuth::ApplicationController 5 | skip_after_action :update_auth_header, only: [:create, :show] 6 | 7 | # this action is responsible for generating unlock tokens and 8 | # sending emails 9 | def create 10 | return render_create_error_missing_email unless resource_params[:email] 11 | 12 | @email = get_case_insensitive_field_from_resource_params(:email) 13 | @resource = find_resource(:email, @email) 14 | 15 | if @resource 16 | yield @resource if block_given? 17 | 18 | @resource.send_unlock_instructions( 19 | email: @email, 20 | provider: 'email', 21 | client_config: params[:config_name] 22 | ) 23 | 24 | if @resource.errors.empty? 25 | return render_create_success 26 | else 27 | render_create_error @resource.errors 28 | end 29 | else 30 | render_not_found_error 31 | end 32 | end 33 | 34 | def show 35 | @resource = resource_class.unlock_access_by_token(params[:unlock_token]) 36 | 37 | if @resource.persisted? 38 | token = @resource.create_token 39 | @resource.save! 40 | yield @resource if block_given? 41 | 42 | redirect_header_options = { unlock: true } 43 | redirect_headers = build_redirect_headers(token.token, 44 | token.client, 45 | redirect_header_options) 46 | redirect_to(@resource.build_auth_url(after_unlock_path_for(@resource), 47 | redirect_headers), 48 | redirect_options) 49 | else 50 | render_show_error 51 | end 52 | end 53 | 54 | private 55 | def after_unlock_path_for(resource) 56 | #TODO: This should probably be a configuration option at the very least. 57 | '/' 58 | end 59 | 60 | def render_create_error_missing_email 61 | render_error(401, I18n.t('devise_token_auth.unlocks.missing_email')) 62 | end 63 | 64 | def render_create_success 65 | render json: { 66 | success: true, 67 | message: success_message('unlocks', @email) 68 | } 69 | end 70 | 71 | def render_create_error(errors) 72 | render json: { 73 | success: false, 74 | errors: errors 75 | }, status: 400 76 | end 77 | 78 | def render_show_error 79 | raise ActionController::RoutingError, 'Not Found' 80 | end 81 | 82 | def render_not_found_error 83 | if Devise.paranoid 84 | render_create_success 85 | else 86 | render_error(404, I18n.t('devise_token_auth.unlocks.user_not_found', email: @email)) 87 | end 88 | end 89 | 90 | def resource_params 91 | params.permit(:email, :unlock_token, :config) 92 | end 93 | end 94 | end 95 | -------------------------------------------------------------------------------- /app/models/devise_token_auth/concerns/active_record_support.rb: -------------------------------------------------------------------------------- 1 | module DeviseTokenAuth::Concerns::ActiveRecordSupport 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | if Rails.gem_version >= Gem::Version.new("7.1.0.a") 6 | serialize :tokens, coder: DeviseTokenAuth::Concerns::TokensSerialization 7 | else 8 | serialize :tokens, DeviseTokenAuth::Concerns::TokensSerialization 9 | end 10 | end 11 | 12 | class_methods do 13 | # It's abstract replacement .find_by 14 | def dta_find_by(attrs = {}) 15 | find_by(attrs) 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /app/models/devise_token_auth/concerns/confirmable_support.rb: -------------------------------------------------------------------------------- 1 | module DeviseTokenAuth::Concerns::ConfirmableSupport 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | # Override standard devise `postpone_email_change?` method 6 | # for not to use `will_save_change_to_email?` & `email_changed?` methods. 7 | def postpone_email_change? 8 | postpone = self.class.reconfirmable && 9 | email_value_in_database != email && 10 | !@bypass_confirmation_postpone && 11 | self.email.present? && 12 | (!@skip_reconfirmation_in_callback || !email_value_in_database.nil?) 13 | @bypass_confirmation_postpone = false 14 | postpone 15 | end 16 | end 17 | 18 | protected 19 | 20 | def email_value_in_database 21 | rails51 = Rails.gem_version >= Gem::Version.new("5.1.x") 22 | if rails51 && respond_to?(:email_in_database) 23 | email_in_database 24 | else 25 | email_was 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /app/models/devise_token_auth/concerns/mongoid_support.rb: -------------------------------------------------------------------------------- 1 | module DeviseTokenAuth::Concerns::MongoidSupport 2 | extend ActiveSupport::Concern 3 | 4 | def as_json(options = {}) 5 | options[:except] = (options[:except] || []) + [:_id] 6 | hash = super(options) 7 | hash['id'] = to_param 8 | hash 9 | end 10 | 11 | class_methods do 12 | # It's abstract replacement .find_by 13 | def dta_find_by(attrs = {}) 14 | find_by(attrs) 15 | rescue Mongoid::Errors::DocumentNotFound 16 | nil 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/models/devise_token_auth/concerns/tokens_serialization.rb: -------------------------------------------------------------------------------- 1 | module DeviseTokenAuth::Concerns::TokensSerialization 2 | extend self 3 | # Serialization hash to json 4 | def dump(object) 5 | JSON.generate(object && object.transform_values do |token| 6 | serialize_updated_at(token).compact 7 | end.compact) 8 | end 9 | 10 | # Deserialization json to hash 11 | def load(json) 12 | case json 13 | when String 14 | JSON.parse(json) 15 | when NilClass 16 | {} 17 | else 18 | json 19 | end 20 | end 21 | 22 | private 23 | 24 | def serialize_updated_at(token) 25 | updated_at_key = ['updated_at', :updated_at].find(&token.method(:[])) 26 | 27 | return token unless token[updated_at_key].respond_to?(:iso8601) 28 | 29 | token.merge updated_at_key => token[updated_at_key].iso8601 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/models/devise_token_auth/concerns/user_omniauth_callbacks.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth::Concerns::UserOmniauthCallbacks 4 | extend ActiveSupport::Concern 5 | 6 | included do 7 | validates :email, presence: true, if: lambda { uid_and_provider_defined? && email_provider? } 8 | validates :email, :devise_token_auth_email => true, allow_nil: true, allow_blank: true, if: lambda { uid_and_provider_defined? && email_provider? } 9 | validates_presence_of :uid, if: lambda { uid_and_provider_defined? && !email_provider? } 10 | 11 | # only validate unique emails among email registration users 12 | validates :email, uniqueness: { case_sensitive: false, scope: :provider }, on: :create, if: lambda { uid_and_provider_defined? && email_provider? } 13 | 14 | # keep uid in sync with email 15 | before_save :sync_uid 16 | before_create :sync_uid 17 | end 18 | 19 | protected 20 | 21 | def uid_and_provider_defined? 22 | defined?(provider) && defined?(uid) 23 | end 24 | 25 | def email_provider? 26 | provider == 'email' 27 | end 28 | 29 | def sync_uid 30 | unless self.new_record? 31 | return if devise_modules.include?(:confirmable) && !@bypass_confirmation_postpone && postpone_email_change? 32 | end 33 | self.uid = email if uid_and_provider_defined? && email_provider? 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /app/validators/devise_token_auth_email_validator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DeviseTokenAuthEmailValidator < ActiveModel::EachValidator 4 | EMAIL_REGEXP = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i 5 | 6 | class << self 7 | def validate?(email) 8 | email =~ EMAIL_REGEXP 9 | end 10 | end 11 | 12 | def validate_each(record, attribute, value) 13 | unless DeviseTokenAuthEmailValidator.validate?(value) 14 | record.errors.add(attribute, email_invalid_message) 15 | end 16 | end 17 | 18 | private 19 | 20 | def email_invalid_message 21 | # Try strictly set message: 22 | message = options[:message] 23 | 24 | if message.nil? 25 | # Try DeviceTokenAuth translations or fallback to ActiveModel translations 26 | message = I18n.t(:'errors.messages.not_email', default: :'errors.messages.invalid') 27 | end 28 | 29 | message 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/views/devise/mailer/confirmation_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

<%= t(:welcome).capitalize + ' ' + @email %>!

2 | 3 |

<%= t '.confirm_link_msg' %>

4 | 5 |

<%= link_to t('.confirm_account_link'), confirmation_url(@resource, {confirmation_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url']}).html_safe %>

6 | -------------------------------------------------------------------------------- /app/views/devise/mailer/reset_password_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

<%= t(:hello).capitalize %> <%= @resource.email %>!

2 | 3 |

<%= t '.request_reset_link_msg' %>

4 | 5 |

<%= link_to t('.password_change_link'), edit_password_url(@resource, reset_password_token: @token, config: message['client-config'].to_s, redirect_url: message['redirect-url'].to_s).html_safe %>

6 | 7 |

<%= t '.ignore_mail_msg' %>

8 |

<%= t '.no_changes_msg' %>

-------------------------------------------------------------------------------- /app/views/devise/mailer/unlock_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

<%= t :hello %> <%= @resource.email %>!

2 | 3 |

<%= t '.account_lock_msg' %>

4 | 5 |

<%= t '.unlock_link_msg' %>

6 | 7 |

<%= link_to t('.unlock_link'), unlock_url(@resource, unlock_token: @token, config: message['client-config'].to_s) %>

8 | -------------------------------------------------------------------------------- /app/views/devise_token_auth/omniauth_external_window.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 33 | 34 | 35 |
36 |     
37 | 38 | 39 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application. 5 | 6 | ENGINE_ROOT = File.expand_path('..', __dir__) 7 | ENGINE_PATH = File.expand_path('../lib/devise_token_auth/engine', __dir__) 8 | 9 | # Set up gems listed in the Gemfile. 10 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 11 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 12 | 13 | require 'rails/all' 14 | require 'rails/engine/commands' 15 | -------------------------------------------------------------------------------- /config/locales/he.yml: -------------------------------------------------------------------------------- 1 | he: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "הודעת אישור נשלחה לחשבון שלך בכתובת '%{email}'. עליך לפעול לפי ההנחיות שבדוא\"ל לפני הפעלת החשבון שלך" 5 | bad_credentials: "נתוני כניסה שגויים. בבקשה נסה שוב." 6 | not_supported: "השתמש ב- POST / sign_in כדי להיכנס. GET אינו נתמך." 7 | user_not_found: "המשתמש לא נמצא או לא היה מחובר." 8 | token_validations: 9 | invalid: "נתוני כניסה שגויים" 10 | registrations: 11 | missing_confirm_success_url: "חסר פרמטר 'confirm_success_url'." 12 | redirect_url_not_allowed: "הפניה אל '%{redirect_url}' אינה מותרת." 13 | email_already_exists: "כבר קיים חשבון עבור '%{email}'" 14 | account_with_uid_destroyed: "חשבון עם UID '%{uid}' הושמד." 15 | account_to_destroy_not_found: "לא ניתן לאתר חשבון להשמדה." 16 | user_not_found: "המשתמש לא נמצא." 17 | omniauth: 18 | not_allowed_redirect_url: "הפניה אל '%{redirect_url}' אינה מותרת." 19 | passwords: 20 | missing_email: "עליך לספק כתובת דוא\"ל." 21 | missing_redirect_url: "כתובת אתר להפניה מחדש חסרה." 22 | not_allowed_redirect_url: "הפניה אל '%{redirect_url}' אינה מותרת." 23 | sended: "אימייל נשלח ל '%{email}' המכיל הוראות לאיפוס הסיסמה שלך." 24 | user_not_found: "לא ניתן למצוא משתמש עם הדוא\"ל '%{email}'." 25 | password_not_required: "חשבון זה אינו דורש סיסמה. במקום זאת, השתמש בחשבון '%{provider}' שלך." 26 | missing_passwords: "עליך למלא את השדות 'סיסמה' ו'אישור סיסמה'." 27 | successfully_updated: "הסיסמה שלך עודכנה בהצלחה." 28 | unlocks: 29 | missing_email: "עליך לספק כתובת דוא\"ל." 30 | sended: "הודעת אימייל נשלחה אל '%{email}' המכילה הוראות לביטול הנעילה של חשבונך." 31 | user_not_found: "ניתן למצוא את המשתמש עם הדוא\"ל '%{email}'" 32 | errors: 33 | messages: 34 | validate_sign_up_params: "שלח נתוני רישום תקינים בגוף הבקשה." 35 | validate_account_update_params: "שלחו בבקשה נתוני עדכון חשבון תקינים בגוף הבקשה." 36 | not_email: "אינו דוא\"ל" 37 | devise: 38 | mailer: 39 | confirmation_instructions: 40 | confirm_link_msg: "תוכל לאשר את כתובת הדוא\"ל של החשבון שלך באמצעות הקישור הבא:" 41 | confirm_account_link: "אשר את החשבון שלי" 42 | reset_password_instructions: 43 | request_reset_link_msg: "מישהו ביקש קישור לשינוי הסיסמה שלך. תוכל לעשות זאת באמצעות הקישור הבא." 44 | password_change_link: "שנה את הסיסמה שלי" 45 | ignore_mail_msg: "אם לא ביקשת זאת, התעלם מדוא\"ל זה." 46 | no_changes_msg: "הסיסמה שלך לא תשתנה עד שתגיע לקישור שלמעלה ותיצור סיסמה חדשה." 47 | unlock_instructions: 48 | account_lock_msg: "החשבון שלך ננעל עקב מספר מופרז של ניסיונות כניסה לא מוצלחים." 49 | unlock_link_msg: "לחץ על הקישור למטה כדי לבטל את נעילת החשבון שלך:" 50 | unlock_link: "בטל את הנעילה של החשבון שלי" 51 | hello: "שלום" 52 | welcome: "ברוך הבא" 53 | -------------------------------------------------------------------------------- /config/locales/it.yml: -------------------------------------------------------------------------------- 1 | it: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "Un'email di conferma è stata mandata al tuo account '%{email}'. Segui le istruzioni nell'email per attivare il tuo account." 5 | bad_credentials: "Credenziali di login non valide. Riprova." 6 | not_supported: "Usa POST /sign_in per eseguire il login. GET non è supportato." 7 | user_not_found: "Utente non trovato o non autenticato." 8 | token_validations: 9 | invalid: "Credenziali di login non valide" 10 | registrations: 11 | missing_confirm_success_url: "Parametro 'confirm_success_url' mancante." 12 | redirect_url_not_allowed: "Redirezione a '%{redirect_url}' non consentita." 13 | email_already_exists: "Esiste già un account per '%{email}'" 14 | account_with_uid_destroyed: "L'account con UID '%{uid}' è stato eliminato." 15 | account_to_destroy_not_found: "Impossibile trovare l'account da eliminare." 16 | user_not_found: "Utente non trovato." 17 | omniauth: 18 | not_allowed_redirect_url: "Redirezione a '%{redirect_url}' non consentita." 19 | passwords: 20 | missing_email: "Devi fornire un indirizzo email." 21 | missing_redirect_url: "Redirect URL mancante." 22 | not_allowed_redirect_url: "Redirezione a '%{redirect_url}' non consentita." 23 | sended: "E' stata inviata un'email a '%{email}' contenente le istruzioni per reimpostare la password." 24 | user_not_found: "Impossibile trovare un utente con email '%{email}'." 25 | password_not_required: "Questo account non richiede una password. Accedi utilizzando l'account di '%{provider}'." 26 | missing_passwords: "Devi riempire i campi 'Password' e 'Password confirmation'." 27 | successfully_updated: "La tua password è stata aggiornata correttamente." 28 | errors: 29 | messages: 30 | validate_sign_up_params: "Dati di registrazione non validi." 31 | validate_account_update_params: "Dati di aggiornamento dell'account non validi." 32 | not_email: "non è un'email" 33 | devise: 34 | mailer: 35 | confirmation_instructions: 36 | confirm_link_msg: "Puoi confermare il tuo account email cliccando sul seguente link:" 37 | confirm_account_link: "Conferma il mio account" 38 | reset_password_instructions: 39 | request_reset_link_msg: "Qualcuno ha richiesto un link per cambiare la tua password. Puoi farlo cliccando sul seguente link." 40 | password_change_link: "Cambia la mia password" 41 | ignore_mail_msg: "Se non hai richiesto questa operazione, puoi ignorare l'email." 42 | no_changes_msg: "La tua password non cambierà finchè non cliccherai sul link sopra per crearne una nuova." 43 | unlock_instructions: 44 | account_lock_msg: "Il tuo account è stato bloccato a causa di un numero eccessivo di tentativi di accesso non validi." 45 | unlock_link_msg: "Clicca sul seguente link per sbloccare il tuo account:" 46 | unlock_link: "Sblocca il mio account" 47 | hello: "ciao" 48 | welcome: "benvenuto" 49 | -------------------------------------------------------------------------------- /config/locales/ja.yml: -------------------------------------------------------------------------------- 1 | ja: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "'%{email}' に確認用のメールを送信しました。メール内の説明を読み、アカウントの有効化をしてください。" 5 | bad_credentials: "ログイン用の認証情報が正しくありません。再度お試しください。" 6 | not_supported: "/sign_in に GET はサポートされていません。POST をお使いください。" 7 | user_not_found: "ユーザーが見つからないか、ログインしていません。" 8 | token_validations: 9 | invalid: "ログイン用の認証情報が正しくありません。" 10 | registrations: 11 | missing_confirm_success_url: "'confirm_success_url' パラメータが与えられていません。" 12 | redirect_url_not_allowed: "'%{redirect_url}' へのリダイレクトは許可されていません。" 13 | email_already_exists: "'%{email}' のアカウントはすでに存在しています。" 14 | account_with_uid_destroyed: "'%{uid}' のアカウントは削除されました。" 15 | account_to_destroy_not_found: "削除するアカウントが見つかりません。" 16 | user_not_found: "ユーザーが見つかりません。" 17 | omniauth: 18 | not_allowed_redirect_url: "'%{redirect_url}' へのリダイレクトは許可されていません。" 19 | passwords: 20 | missing_email: "メールアドレスが与えられていません。" 21 | missing_redirect_url: "リダイレクト URL が与えられていません。" 22 | not_allowed_redirect_url: "'%{redirect_url}' へのリダイレクトは許可されていません。" 23 | sended: "'%{email}' にパスワードリセットの案内が送信されました。" 24 | sended_paranoid: "すでにメールアドレスがデータベースに登録されている場合、 数分後にパスワード再発行用のリンクを記載したメールをお送りします。" 25 | user_not_found: "メールアドレス '%{email}' のユーザーが見つかりません。" 26 | password_not_required: "このアカウントはパスワードを要求していません。'%{provider}' を利用してログインしてください。" 27 | missing_passwords: "'Password', 'Password confirmation' パラメータが与えられていません。" 28 | successfully_updated: "パスワードの更新に成功しました。" 29 | unlocks: 30 | missing_email: "メールアドレスが与えられていません。" 31 | sended: "%{email}' にアカウントのロックを解除する方法を記載したメールが送信されました。" 32 | sended_paranoid: "アカウントが存在する場合、数分後にロックを解除する方法を記載したメールをお送りします。" 33 | user_not_found: "メールアドレス '%{email}' を持つユーザーが見つかりません。" 34 | confirmations: 35 | sended: "'%{email}' にアカウントの確認方法を記載したメールが送信されました。" 36 | sended_paranoid: "すでにメールアドレスがデータベースに登録されている場合、数分後にメールアドレスの確認方法を記載したメールをお送りします。" 37 | user_not_found: "メールアドレス '%{email}' を持つユーザーが見つかりません。" 38 | missing_email: "メールアドレスが与えられていません。" 39 | 40 | errors: 41 | messages: 42 | validate_sign_up_params: "リクエストボディに適切なアカウント新規登録データを送信してください。" 43 | validate_account_update_params: "リクエストボディに適切なアカウント更新のデータを送信してください。" 44 | not_email: "は有効ではありません" 45 | devise: 46 | mailer: 47 | confirmation_instructions: 48 | confirm_link_msg: "下記のリンクからアカウントを有効化できます:" 49 | confirm_account_link: "アカウントを有効化する" 50 | reset_password_instructions: 51 | request_reset_link_msg: "パスワード変更のリクエストが送信されました。下記のリンクからパスワードの変更ができます。" 52 | password_change_link: "パスワードを変更する" 53 | ignore_mail_msg: "もしこの内容に覚えがない場合は、このメールを無視してください。" 54 | no_changes_msg: "上記のリンクにアクセスして新しいパスワードを作成するまで、現在のパスワードは変更されません。" 55 | unlock_instructions: 56 | account_lock_msg: "連続してログインに失敗したため、あなたのアカウントはロックされました。" 57 | unlock_link_msg: "下記のリンクをクリックしてアカウントを有効化してください:" 58 | unlock_link: "アカウントを有効化する" 59 | hello: "こんにちは" 60 | welcome: "ようこそ" 61 | -------------------------------------------------------------------------------- /config/locales/ko.yml: -------------------------------------------------------------------------------- 1 | ko: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "'%{email}'로 주소 인증 메일을 발송했습니다. 계정을 활성화하기 위해서는 반드시 메일의 안내를 따라야 합니다." 5 | bad_credentials: "계정 정보가 맞지 않습니다. 다시 시도해 주세요." 6 | not_supported: "POST /sign_in to sign in을 사용해주세요. GET은 지원하지 않습니다." 7 | user_not_found: "유저를 찾을 수 없습니다." 8 | invalid: "계정 정보가 맞지 않습니다." 9 | registrations: 10 | missing_confirm_success_url: "'confirm_success_url' 파라미터가 없습니다." 11 | redirect_url_not_allowed: "'%{redirect_url}' 주소로 리다이렉트는 허용하지 않습니다." 12 | email_already_exists: "'%{email}'을 사용하는 계정이 이미 있습니다." 13 | account_with_uid_destroyed: " UID가 '%{uid}'인 계정을 삭제했습니다." 14 | account_to_destroy_not_found: "삭제할 계정을 찾을 수 없습니다." 15 | user_not_found: "유저를 찾을 수 없습니다." 16 | omniauth: 17 | not_allowed_redirect_url: "'%{redirect_url}' 주소로 리다이렉트는 허용하지 않습니다." 18 | passwords: 19 | missing_email: "이메일 주소를 입력해야 합니다." 20 | missing_redirect_url: "redirect URL이 없습니다." 21 | not_allowed_redirect_url: "'%{redirect_url}' 주소로 리다이렉트는 허용하지 않습니다." 22 | sended: "'%{email}'로 비밀번호를 재설정하기 위한 안내 메일을 발송했습니다." 23 | user_not_found: "'%{email}'을 사용하는 유저를 찾을 수 없습니다." 24 | password_not_required: "이 계정은 비밀번호가 필요하지 않습니다. '%{provider}'으로 로그인을 진행해 주세요." 25 | missing_passwords: "비밀번호와 비밀번호 확인 필드를 반드시 입력해야 합니다." 26 | successfully_updated: "비밀번호를 성공적으로 업데이트 했습니다." 27 | unlocks: 28 | missing_email: "이메일 주소를 반드시 입력해야 합니다." 29 | sended: "'%{email}'로 계정 잠금 해제를 위한 안내 메일을 발송했습니다." 30 | user_not_found: "'%{email}'을 사용하는 유저를 찾을 수 없습니다." 31 | errors: 32 | messages: 33 | validate_sign_up_params: "요청 값에 알맞은 로그인 데이터를 입력하세요." 34 | validate_account_update_params: "요청 값에 알맞은 업데이트 데이터를 입력하세요." 35 | not_email: "이메일이 아닙니다." 36 | devise: 37 | mailer: 38 | confirmation_instructions: 39 | confirm_link_msg: "아래의 링크를 이용해 계정 인증을 할 수 있습니다." 40 | confirm_account_link: "본인 계정 인증" 41 | reset_password_instructions: 42 | request_reset_link_msg: "누군가 당신의 비밀번호를 변경하는 링크를 요청했으며, 다음의 링크에서 비밀번호 변경이 가능합니다." 43 | password_change_link: "비밀번호 변경" 44 | ignore_mail_msg: "비밀번호 변경을 요청하지 않으셨다면 이 메일을 무시하십시오." 45 | no_changes_msg: "위 링크에 접속하여 새로운 비밀번호를 생성하기 전까지 귀하의 비밀번호는 변경되지 않습니다." 46 | unlock_instructions: 47 | account_lock_msg: "로그인 실패 횟수 초과로 귀하의 계정이 잠금 처리되었습니다." 48 | unlock_link_msg: "계정 잠금을 해제하려면 아래 링크를 클릭하세요." 49 | unlock_link: "계정 잠금 해제" 50 | hello: "안녕하세요" 51 | welcome: "환영합니다" 52 | -------------------------------------------------------------------------------- /config/locales/nl.yml: -------------------------------------------------------------------------------- 1 | nl: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "Een bevestingsmail is verzonden naar het adres '%{email}'. Volg de instructies in de mail om uw account te activeren." 5 | bad_credentials: 'Ongeldige logingegevens.' 6 | not_supported: "Gebruik POST /sign_in om in te loggen. GET wordt niet ondersteund." 7 | user_not_found: "Gebruiker is niet gevonden of niet ingelogd." 8 | token_validations: 9 | invalid: "Ongeldige logingegevens." 10 | registrations: 11 | missing_confirm_success_url: "Parameter 'confirm_success_url' ontbreekt." 12 | redirect_url_not_allowed: "Redirect naar '%{redirect_url}' niet toegestaan." 13 | email_already_exists: "Er bestaat al een account voor het adres '%{email}'" 14 | account_with_uid_destroyed: "Account met id '%{uid}' is verwijderd." 15 | account_to_destroy_not_found: "Te verwijderen account niet gevonden." 16 | user_not_found: "Gebruiker niet gevonden." 17 | omniauth: 18 | not_allowed_redirect_url: "Redirect naar '%{redirect_url}' niet toegestaan." 19 | passwords: 20 | missing_email: "Je moet een e-mailadres opgeven." 21 | missing_redirect_url: "Redirect URL ontbreekt." 22 | not_allowed_redirect_url: "Redirect naar '%{redirect_url}' niet toegestaan." 23 | sended: "Er is een e-mail naar '%{email}' verstuurd met instructies om uw wachtwoord te resetten." 24 | user_not_found: "Kan gebruiker met e-mail '%{email}' niet vinden." 25 | password_not_required: "Voor dit account is geen wachtwoord nodig. Log in met uw '%{provider}' account." 26 | missing_passwords: "De velden 'Wachtwoord' en 'Wachtwoord bevestiging' zijn verplicht." 27 | successfully_updated: "Uw wachtwoord is aangepast." 28 | errors: 29 | messages: 30 | validate_sign_up_params: "Gegevens voor aanmaken van het account zijn niet geldig." 31 | validate_account_update_params: "Gegevens voor updaten van het account zijn niet geldig." 32 | not_email: "is geen geldig e-emailadres" 33 | -------------------------------------------------------------------------------- /config/locales/pt-BR.yml: -------------------------------------------------------------------------------- 1 | pt-BR: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "Uma mensagem com um link de confirmação foi enviado para seu endereço de e-mail. Você precisa confirmar sua conta antes de continuar." 5 | bad_credentials: "E-mail ou senha inválidos." 6 | not_supported: "Use POST /sign_in para efetuar o login. GET não é suportado." 7 | user_not_found: "Usuário não existe ou não está logado." 8 | token_validations: 9 | invalid: "Dados de login inválidos." 10 | registrations: 11 | missing_confirm_success_url: "Parâmetro 'confirm_success_url' não informado." 12 | redirect_url_not_allowed: "Redirecionamento para '%{redirect_url}' não permitido." 13 | email_already_exists: "Já existe uma conta com o email '%{email}'." 14 | account_with_uid_destroyed: "A conta com uid '%{uid}' foi excluída." 15 | account_to_destroy_not_found: "Não foi possível encontrar a conta para exclusão." 16 | user_not_found: "Usuário não encontrado." 17 | omniauth: 18 | not_allowed_redirect_url: "Redirecionamento para '%{redirect_url}' não permitido." 19 | passwords: 20 | missing_email: "Informe o endereço de e-mail." 21 | missing_redirect_url: "URL para redirecionamento não informada." 22 | not_allowed_redirect_url: "Redirecionamento para '%{redirect_url}' não permitido." 23 | sended: "Você receberá um e-mail com instruções sobre como redefinir sua senha." 24 | user_not_found: "Não existe um usuário com o e-mail '%{email}'." 25 | password_not_required: "Esta conta não necessita de uma senha. Faça login utilizando '%{provider}'." 26 | missing_passwords: 'Preencha a senha e a confirmação de senha.' 27 | successfully_updated: "Senha atualizada com sucesso." 28 | errors: 29 | messages: 30 | validate_sign_up_params: "Os dados submetidos na requisição de cadastro são inválidos." 31 | validate_account_update_params: "Os dados submetidos para atualização de conta são inválidos." 32 | not_email: "não é um e-mail" 33 | devise: 34 | mailer: 35 | confirmation_instructions: 36 | confirm_link_msg: "Você pode confirmar a sua conta de e-mail através do link abaixo :" 37 | confirm_account_link: "Confirme conta" 38 | reset_password_instructions: 39 | request_reset_link_msg: "Alguém pediu um link para mudar sua senha. Você pode fazer isso através do link abaixo " 40 | password_change_link: "Alterar a senha" 41 | ignore_mail_msg: "Se você não pediu isso, por favor, ignore este e-mail." 42 | no_changes_msg: "Sua senha não será alterada até que você acessar o link acima e criar um novo." 43 | unlock_instructions: 44 | account_lock_msg: "A sua conta foi bloqueada devido a um número excessivo de sinal de sucesso em tentativas." 45 | unlock_link_msg: "Clique no link abaixo para desbloquear sua conta:" 46 | unlock_link: "Desbloquear minha conta" 47 | hello: "olá" 48 | welcome: "bem-vindo" 49 | -------------------------------------------------------------------------------- /config/locales/pt.yml: -------------------------------------------------------------------------------- 1 | pt: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "Uma mensagem com um link de confirmação foi enviado para seu endereço de e-mail. Você precisa confirmar sua conta antes de continuar." 5 | bad_credentials: "E-mail ou senha inválidos." 6 | not_supported: "Use POST /sign_in para efetuar o login. GET não é suportado." 7 | user_not_found: "Utilizador não existe ou não está logado." 8 | token_validations: 9 | invalid: "Dados de login inválidos." 10 | registrations: 11 | missing_confirm_success_url: "Parâmetro 'confirm_success_url' não informado." 12 | redirect_url_not_allowed: "Redirecionamento para '%{redirect_url}' não permitido." 13 | email_already_exists: "Já existe uma conta com o email '%{email}'." 14 | account_with_uid_destroyed: "A conta com uid '%{uid}' foi excluída." 15 | account_to_destroy_not_found: "Não foi possível encontrar a conta para exclusão." 16 | user_not_found: "Utilizador não encontrado." 17 | omniauth: 18 | not_allowed_redirect_url: "Redirecionamento para '%{redirect_url}' não permitido." 19 | passwords: 20 | missing_email: "Informe o endereço de e-mail." 21 | missing_redirect_url: "URL para redirecionamento não informada." 22 | not_allowed_redirect_url: "Redirecionamento para '%{redirect_url}' não permitido." 23 | sended: "Você receberá um e-mail com instruções sobre como redefinir sua senha." 24 | user_not_found: "Não existe um utilizador com o e-mail '%{email}'." 25 | password_not_required: "Esta conta não necessita de uma senha. Faça login utilizando '%{provider}'." 26 | missing_passwords: "Preencha a senha e a confirmação de senha." 27 | successfully_updated: "Senha atualizada com sucesso." 28 | errors: 29 | messages: 30 | validate_sign_up_params: "Os dados submetidos na requisição de registo são inválidos." 31 | validate_account_update_params: "Os dados submetidos para atualização de conta são inválidos." 32 | not_email: "não é um e-mail" 33 | devise: 34 | mailer: 35 | confirmation_instructions: 36 | subject: "Instruções de confirmação" 37 | confirm_link_msg: "Você pode confirmar a sua conta de e-mail através do link abaixo :" 38 | confirm_account_link: "Confirme conta" 39 | reset_password_instructions: 40 | subject: "Instruções para redefinir sua senha" 41 | request_reset_link_msg: "Alguém pediu um link para mudar sua senha. Você pode fazer isso através do link abaixo " 42 | password_change_link: "Alterar a senha" 43 | ignore_mail_msg: "Se você não pediu isso, por favor, ignore este e-mail." 44 | no_changes_msg: "Sua senha não será alterada até que você acessar o link acima e criar um novo." 45 | unlock_instructions: 46 | subject: "Instruções de desbloqueio" 47 | account_lock_msg: "A sua conta foi bloqueada devido a um número excessivo de sinal de sucesso em tentativas." 48 | unlock_link_msg: "Clique no link abaixo para desbloquear sua conta:" 49 | unlock_link: "Desbloquear minha conta" 50 | hello: "olá" 51 | welcome: "bem-vindo" 52 | -------------------------------------------------------------------------------- /config/locales/zh-CN.yml: -------------------------------------------------------------------------------- 1 | zh-CN: 2 | devise_token_auth: 3 | sessions: 4 | not_confirmed: "您将在几分钟后收到一封电子邮件'%{email}',内有验证账号的步骤说明" 5 | bad_credentials: "不正确的登录信息,请重试" 6 | not_supported: "请使用 POST /sign_in 进行登录. GET 是不支持的." 7 | user_not_found: "没有找到账号或没有成功登录" 8 | token_validations: 9 | invalid: "不正确的登录资料" 10 | registrations: 11 | missing_confirm_success_url: "缺少数据 'confirm_success_url'" 12 | redirect_url_not_allowed: "不支持转向到 '%{redirect_url}'" 13 | email_already_exists: "邮箱'%{email}'已被使用" 14 | account_with_uid_destroyed: "账号 '%{uid}' 已被移除。" 15 | account_to_destroy_not_found: "无法找到目标帐号。" 16 | user_not_found: "找不到帐号。" 17 | omniauth: 18 | not_allowed_redirect_url: "不支持转向到 '%{redirect_url}'" 19 | passwords: 20 | missing_email: "必需提供邮箱。" 21 | missing_redirect_url: "欠缺 redirect URL." 22 | not_allowed_redirect_url: "不支持转向到 '%{redirect_url}'" 23 | sended: "您将在几分钟后收到一封电子邮件'%{email},内含可重新设定密码的链接。" 24 | user_not_found: "找不到帐号 '%{email}'。" 25 | password_not_required: "这不是一个需要密码的帐号. 请使用 '%{provider}' 进行登入" 26 | missing_passwords: "必需填写'密码'与'确认密码'。" 27 | successfully_updated: "您的密码已被修改。" 28 | errors: 29 | messages: 30 | validate_sign_up_params: "请在request body中填入有效的注册内容" 31 | validate_account_update_params: "请在request body中填入有效的更新帐号资料" 32 | not_email: "这不是一个合适的邮箱。" 33 | devise: 34 | mailer: 35 | confirmation_instructions: 36 | confirm_link_msg: "可以使用下面的链接确定你的邮箱" 37 | confirm_account_link: "确定你的帐号" 38 | reset_password_instructions: 39 | request_reset_link_msg: "已申请修改您的密码,你可以用下面的链接进入" 40 | password_change_link: "修改我的密码" 41 | ignore_mail_msg: "如你没有申请,请忽略" 42 | no_changes_msg: "在你点击上面链接前,你的密码都没有改变" 43 | unlock_instructions: 44 | account_lock_msg: "由于多次登入失败,我们已锁定你的帐号" 45 | unlock_link_msg: "可以使用下面的链接解锁你的帐号" 46 | unlock_link: "解锁帐号" 47 | hello: "你好" 48 | welcome: "欢迎" 49 | -------------------------------------------------------------------------------- /config/locales/zh-HK.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | zh-TW: 4 | devise_token_auth: 5 | sessions: 6 | not_confirmed: "您將在幾分鐘後收到一封電子郵件'%{email}',內有驗證帳號的步驟說明。" 7 | bad_credentials: "不正確的登入資料。請重試。" 8 | not_supported: "請使用 POST /sign_in 進行登入. GET 是不支援的." 9 | user_not_found: "未能找到帳號或未能成功登入。" 10 | token_validations: 11 | invalid: "不正確的登入資料。" 12 | registrations: 13 | missing_confirm_success_url: "欠缺數值 'confirm_success_url'" 14 | redirect_url_not_allowed: "不支援轉向到'%{redirect_url}'" 15 | email_already_exists: "電郵'%{email}'已被使用" 16 | account_with_uid_destroyed: "帳號 '%{uid}' 已被移除。" 17 | account_to_destroy_not_found: "無法找到目標帳號。" 18 | user_not_found: "找不到帳號。" 19 | omniauth: 20 | not_allowed_redirect_url: "不支援轉向到 '%{redirect_url}'" 21 | passwords: 22 | missing_email: "必需提供電郵。" 23 | missing_redirect_url: "欠缺 redirect URL." 24 | not_allowed_redirect_url: "不支援轉向到 '%{redirect_url}'" 25 | sended: "您將在幾分鐘後收到一封電子郵件'%{email},內含可重新設定密碼連結的電子郵件。" 26 | user_not_found: "找不到帳號 '%{email}'。" 27 | password_not_required: "這不是一個需要密碼的帳號. 請使用 '%{provider}' 進行登入" 28 | missing_passwords: "必需填寫'密碼'與'確認密碼'。" 29 | successfully_updated: "您的密碼已被修改。" 30 | errors: 31 | messages: 32 | validate_sign_up_params: "請在request body中填入有效的註冊內容" 33 | validate_account_update_params: "請在request body中填入有效的更新帳號資料" 34 | not_email: "這不是一個合適的電郵。" 35 | devise: 36 | mailer: 37 | confirmation_instructions: 38 | confirm_link_msg: "可以使用下面連結確定你的電郵" 39 | confirm_account_link: "確定你的帳號" 40 | reset_password_instructions: 41 | request_reset_link_msg: "已申請修改您的密碼,你可以用下面連結進入" 42 | password_change_link: "修改我的密碼" 43 | ignore_mail_msg: "如你沒有申請,請忽略" 44 | no_changes_msg: "在你點擊上面連結前,你的密碼都沒有改變" 45 | unlock_instructions: 46 | account_lock_msg: "由於多失敗登入,我們已鎖定你的帳號" 47 | unlock_link_msg: "可以使用下面連結解鎖你的帳號" 48 | unlock_link: "解鎖帳號" 49 | hello: "你好" 50 | welcome: "歡迎" 51 | -------------------------------------------------------------------------------- /config/locales/zh-TW.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | zh-TW: 4 | devise_token_auth: 5 | sessions: 6 | not_confirmed: "您將在幾分鐘後收到一封電子郵件'%{email}',內有驗證帳號的步驟說明。" 7 | bad_credentials: "不正確的登入資料。請重試。" 8 | not_supported: "請使用 POST /sign_in 進行登入. GET 是不支援的." 9 | user_not_found: "未能找到帳號或未能成功登入。" 10 | token_validations: 11 | invalid: "不正確的登入資料。" 12 | registrations: 13 | missing_confirm_success_url: "欠缺數值 'confirm_success_url'" 14 | redirect_url_not_allowed: "不支援轉向到'%{redirect_url}'" 15 | email_already_exists: "電郵'%{email}'已被使用" 16 | account_with_uid_destroyed: "帳號 '%{uid}' 已被移除。" 17 | account_to_destroy_not_found: "無法找到目標帳號。" 18 | user_not_found: "找不到帳號。" 19 | omniauth: 20 | not_allowed_redirect_url: "不支援轉向到 '%{redirect_url}'" 21 | passwords: 22 | missing_email: "必需提供電郵。" 23 | missing_redirect_url: "欠缺 redirect URL." 24 | not_allowed_redirect_url: "不支援轉向到 '%{redirect_url}'" 25 | sended: "您將在幾分鐘後收到一封電子郵件'%{email},內含可重新設定密碼連結的電子郵件。" 26 | user_not_found: "找不到帳號 '%{email}'。" 27 | password_not_required: "這不是一個需要密碼的帳號. 請使用 '%{provider}' 進行登入" 28 | missing_passwords: "必需填寫'密碼'與'確認密碼'。" 29 | successfully_updated: "您的密碼已被修改。" 30 | errors: 31 | messages: 32 | validate_sign_up_params: "請在request body中填入有效的註冊內容" 33 | validate_account_update_params: "請在request body中填入有效的更新帳號資料" 34 | not_email: "這不是一個合適的電郵。" 35 | devise: 36 | mailer: 37 | confirmation_instructions: 38 | confirm_link_msg: "可以使用下面連結確定你的電郵" 39 | confirm_account_link: "確定你的帳號" 40 | reset_password_instructions: 41 | request_reset_link_msg: "已申請修改您的密碼,你可以用下面連結進入" 42 | password_change_link: "修改我的密碼" 43 | ignore_mail_msg: "如你沒有申請,請忽略" 44 | no_changes_msg: "在你點擊上面連結前,你的密碼都沒有改變" 45 | unlock_instructions: 46 | account_lock_msg: "由於多失敗登入,我們已鎖定你的帳號" 47 | unlock_link_msg: "可以使用下面連結解鎖你的帳號" 48 | unlock_link: "解鎖帳號" 49 | hello: "你好" 50 | welcome: "歡迎" 51 | -------------------------------------------------------------------------------- /devise_token_auth.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | $:.push File.expand_path('lib', __dir__) 4 | 5 | # Maintain your gem's version: 6 | require 'devise_token_auth/version' 7 | 8 | # Describe your gem and declare its dependencies: 9 | Gem::Specification.new do |s| 10 | s.name = 'devise_token_auth' 11 | s.version = DeviseTokenAuth::VERSION 12 | s.authors = ['Lynn Hurley'] 13 | s.email = ['lynn.dylan.hurley@gmail.com'] 14 | s.homepage = 'https://github.com/lynndylanhurley/devise_token_auth' 15 | s.summary = 'Token based authentication for rails. Uses Devise + OmniAuth.' 16 | s.description = 'For use with client side single page apps such as the venerable https://github.com/lynndylanhurley/ng-token-auth.' 17 | s.license = 'WTFPL' 18 | 19 | s.files = Dir['{app,config,db,lib}/**/*', 'LICENSE', 'Rakefile', 'README.md'] 20 | s.test_files = Dir['test/**/*'] 21 | s.test_files.reject! { |file| file.match(/[.log|.sqlite3]$/) } 22 | 23 | s.required_ruby_version = ">= 2.3.0" 24 | 25 | s.add_dependency 'rails', '>= 4.2.0', '< 8.1' 26 | s.add_dependency 'devise', '> 3.5.2', '< 5' 27 | s.add_dependency 'bcrypt', '~> 3.0' 28 | 29 | s.add_development_dependency 'appraisal' 30 | s.add_development_dependency 'sqlite3', '~> 1.4' 31 | s.add_development_dependency 'pg' 32 | s.add_development_dependency 'mysql2' 33 | s.add_development_dependency 'mongoid', '>= 4', '< 8' 34 | s.add_development_dependency 'mongoid-locker', '~> 2.0' 35 | end 36 | -------------------------------------------------------------------------------- /docs/conceptual.md: -------------------------------------------------------------------------------- 1 | # Conceptual 2 | 3 | None of the following information is required to use this gem, but read on if you're curious. 4 | 5 | ## About token management 6 | 7 | Tokens should be invalidated after each request to the API. The following diagram illustrates this concept: 8 | 9 | ![password reset flow](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/token-update-detail.jpg) 10 | 11 | During each request, a new token is generated. The `access-token` header that should be used in the next request is returned in the `access-token` header of the response to the previous request. The last request in the diagram fails because it tries to use a token that was invalidated by the previous request. 12 | 13 | The only case where an expired token is allowed is during [batch requests](#about-batch-requests). 14 | 15 | These measures are taken by default when using this gem. 16 | 17 | ## About batch requests 18 | 19 | By default, the API should update the auth token for each request ([read more](#about-token-management)). But sometimes it's necessary to make several concurrent requests to the API, for example: 20 | 21 | ##### Batch request example 22 | 23 | ~~~javascript 24 | $scope.getResourceData = function() { 25 | 26 | $http.get('/api/restricted_resource_1').success(function(resp) { 27 | // handle response 28 | $scope.resource1 = resp.data; 29 | }); 30 | 31 | $http.get('/api/restricted_resource_2').success(function(resp) { 32 | // handle response 33 | $scope.resource2 = resp.data; 34 | }); 35 | }; 36 | ~~~ 37 | 38 | In this case, it's impossible to update the `access-token` header for the second request with the `access-token` header of the first response because the second request will begin before the first one is complete. The server must allow these batches of concurrent requests to share the same auth token. This diagram illustrates how batch requests are identified by the server: 39 | 40 | ![batch request overview](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/batch-request-overview.jpg) 41 | 42 | The "5 second" buffer in the diagram is the default used by this gem. 43 | 44 | The following diagram details the relationship between the client, server, and access tokens used over time when dealing with batch requests: 45 | 46 | ![batch request detail](https://github.com/lynndylanhurley/ng-token-auth/raw/master/test/app/images/flow/batch-request-detail.jpg) 47 | 48 | Note that when the server identifies that a request is part of a batch request, the user's auth token is not updated. The auth token will be updated and returned with the first request in the batch, and the subsequent requests in the batch will not return a token. This is necessary because the order of the responses cannot be guaranteed to the client, and we need to be sure that the client does not receive an outdated token *after* the the last valid token is returned. 49 | 50 | This gem automatically manages batch requests. You can change the time buffer for what is considered a batch request using the `batch_request_buffer_throttle` parameter in `config/initializers/devise_token_auth.rb`. 51 | -------------------------------------------------------------------------------- /docs/config/README.md: -------------------------------------------------------------------------------- 1 | ## Configuration 2 | 3 | You will need to create a [user model](/docs/usage/model_concerns.md), [define routes](/docs/usage/routes.md), [include concerns](/docs/usage/controller_methods.md), and you may want to alter some of the [default settings](initialization.md) for this gem. Run the following command for an easy one-step installation: 4 | 5 | ~~~bash 6 | rails g devise_token_auth:install [USER_CLASS] [MOUNT_PATH] 7 | ~~~ 8 | 9 | or for `Mongoid` 10 | 11 | ~~~bash 12 | rails g devise_token_auth:install_mongoid [USER_CLASS] [MOUNT_PATH] 13 | ~~~ 14 | 15 | **Example**: 16 | 17 | ~~~bash 18 | rails g devise_token_auth:install User auth 19 | ~~~ 20 | 21 | This generator accepts the following optional arguments: 22 | 23 | | Argument | Default | Description | 24 | |---|---|---| 25 | | USER_CLASS | `User` | The name of the class to use for user authentication. | 26 | | MOUNT_PATH | `auth` | The path at which to mount the authentication routes. [Read more](/docs/usage/README.md). | 27 | 28 | The following events will take place when using the install generator: 29 | 30 | * An initializer will be created at `config/initializers/devise_token_auth.rb`. [Read more](initialization.md). 31 | 32 | * A model will be created in the `app/models` directory. If the model already exists, a concern (and fields for `Mongoid`) will be included at the file. [Read more](/docs/usage/model_concerns.md). 33 | 34 | * Routes will be appended to file at `config/routes.rb`. [Read more](/docs/usage/routes.md). 35 | 36 | * A concern will be included by your application controller at `app/controllers/application_controller.rb`. [Read more](/docs/usage/controller_methods.md). 37 | 38 | * For `ActiveRecord` a migration file will be created in the `db/migrate` directory. Inspect the migrations file, add additional columns if necessary, and then run the migration: 39 | 40 | ~~~bash 41 | rake db:migrate 42 | ~~~ 43 | 44 | You may also need to configure the following items: 45 | 46 | * **OmniAuth providers** when using 3rd party oauth2 authentication. [Read more](omniauth.md). 47 | * **Cross Origin Request Settings** when using cross-domain clients. [Read more](cors.md). 48 | * **Email** when using email registration. [Read more](email_auth.md). 49 | * **Multiple model support** may require additional steps. [Read more](/docs/usage/multiple_models.md). 50 | -------------------------------------------------------------------------------- /docs/config/cors.md: -------------------------------------------------------------------------------- 1 | ## CORS 2 | 3 | If your API and client live on different domains, you will need to configure your Rails API to allow [cross origin requests](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). The [rack-cors](https://github.com/cyu/rack-cors) gem can be used to accomplish this. 4 | 5 | The following **dangerous** example will allow cross domain requests from **any** domain. Make sure to whitelist only the needed domains. 6 | 7 | ##### Example rack-cors configuration: 8 | ~~~ruby 9 | # gemfile 10 | gem 'rack-cors', :require => 'rack/cors' 11 | 12 | # config/application.rb 13 | module YourApp 14 | class Application < Rails::Application 15 | config.middleware.use Rack::Cors do 16 | allow do 17 | origins '*' 18 | resource '*', 19 | headers: :any, 20 | expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], 21 | methods: [:get, :post, :options, :delete, :put] 22 | end 23 | end 24 | end 25 | end 26 | ~~~ 27 | 28 | Make extra sure that the `Access-Control-Expose-Headers` includes `access-token`, `expiry`, `token-type`, `uid`, and `client` (as is set in the example above by the`:expose` param). If your client experiences erroneous 401 responses, this is likely the cause. 29 | 30 | CORS may not be possible with older browsers (IE8, IE9). I usually set up a proxy for those browsers. See the [ng-token-auth readme](https://github.com/lynndylanhurley/ng-token-auth) or the [jToker readme](https://github.com/lynndylanhurley/j-toker) for more information. 31 | -------------------------------------------------------------------------------- /docs/config/devise.md: -------------------------------------------------------------------------------- 1 | ## Customizing Devise Verbiage 2 | 3 | Devise Token Auth ships with intelligent default wording for everything you need. But that doesn't mean you can't make it more awesome. You can override the [devise defaults](https://github.com/plataformatec/devise/blob/master/config/locales/en.yml) by creating a YAML file at `config/locales/devise.en.yml` and assigning whatever custom values you want. For example, to customize the subject line of your devise e-mails, you could do this: 4 | 5 | ~~~yaml 6 | en: 7 | devise: 8 | mailer: 9 | confirmation_instructions: 10 | subject: "Please confirm your e-mail address" 11 | reset_password_instructions: 12 | subject: "Reset password request" 13 | ~~~ 14 | -------------------------------------------------------------------------------- /docs/config/email_auth.md: -------------------------------------------------------------------------------- 1 | ## Email authentication 2 | If you wish to use email authentication, you must configure your Rails application to send email. [Read here](http://guides.rubyonrails.org/action_mailer_basics.html) for more information. 3 | 4 | I recommend using [mailcatcher](https://mailcatcher.me/) for development. 5 | 6 | ##### mailcatcher development example configuration: 7 | ~~~ruby 8 | # config/environments/development.rb 9 | Rails.application.configure do 10 | config.action_mailer.default_url_options = { host: 'your-dev-host.dev' } 11 | config.action_mailer.delivery_method = :smtp 12 | config.action_mailer.smtp_settings = { address: 'your-dev-host.dev', port: 1025 } 13 | end 14 | ~~~ 15 | You also may want to configure `mail_sender` at devise initializer if you don't use your own mailer class 16 | ##### devise configuration: 17 | ~~~ruby 18 | # config/initializers/devise.rb 19 | Devise.setup do |config| 20 | config.mailer_sender = "example@example.com" 21 | end 22 | ~~~ 23 | 24 | If you wish to send custom e-mails instead of using the default devise templates, you can [do that too](/docs/usage/overrides.md#email-template-overrides). 25 | -------------------------------------------------------------------------------- /docs/installation.md: -------------------------------------------------------------------------------- 1 | ## Installation 2 | 3 | Add the following to your `Gemfile`: 4 | 5 | ~~~ruby 6 | gem 'devise_token_auth' 7 | ~~~ 8 | 9 | Then install the gem using bundle: 10 | 11 | ~~~bash 12 | bundle install 13 | ~~~ 14 | -------------------------------------------------------------------------------- /docs/password_diagram_reset.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lynndylanhurley/devise_token_auth/74ec935c6b2a6edb2c0c44317abfc6bc58632657/docs/password_diagram_reset.jpg -------------------------------------------------------------------------------- /docs/security.md: -------------------------------------------------------------------------------- 1 | # Security 2 | 3 | This gem takes the following steps to ensure security. 4 | 5 | This gem uses auth tokens that are: 6 | * [changed after every request](/docs/conceptual.md#about-token-management) (can be [turned off](https://devise-token-auth.gitbook.io/devise-token-auth/config/initialization)), 7 | * [of cryptographic strength](https://ruby-doc.org/stdlib-2.1.0/libdoc/securerandom/rdoc/SecureRandom.html), 8 | * hashed using [BCrypt](https://github.com/codahale/bcrypt-ruby) (not stored in plain-text), 9 | * securely compared (to protect against timing attacks), 10 | * invalidated after 2 weeks (thus requiring users to login again) 11 | 12 | These measures were inspired by [this stackoverflow post](https://stackoverflow.com/questions/18605294/is-devises-token-authenticatable-secure). 13 | 14 | This gem further mitigates timing attacks by using [this technique](https://gist.github.com/josevalim/fb706b1e933ef01e4fb6). 15 | 16 | But the most important step is to use HTTPS. You are on the hook for that. 17 | -------------------------------------------------------------------------------- /docs/usage/excluding_models.md: -------------------------------------------------------------------------------- 1 | ## Excluding Modules 2 | 3 | By default, almost all of the Devise modules are included: 4 | * [`database_authenticatable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/database_authenticatable.rb) 5 | * [`registerable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/registerable.rb) 6 | * [`recoverable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/recoverable.rb) 7 | * [`trackable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/trackable.rb) 8 | * [`validatable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb) 9 | * [`confirmable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/confirmable.rb) 10 | * [`omniauthable`](https://github.com/plataformatec/devise/blob/master/lib/devise/models/omniauthable.rb) 11 | 12 | You may not want all of these features enabled in your app. That's OK! You can mix and match to suit your own unique style. 13 | 14 | The following example shows how to disable email confirmation. 15 | 16 | ##### Example: disable email confirmation 17 | 18 | Just list the devise modules that you want to include **before** including the `DeviseTokenAuth::Concerns::User` model concern. 19 | 20 | ~~~ruby 21 | # app/models/user.rb 22 | class User < ActiveRecord::Base 23 | 24 | # notice this comes BEFORE the include statement below 25 | # also notice that :confirmable is not included in this block 26 | devise :database_authenticatable, :recoverable, 27 | :trackable, :validatable, :registerable, 28 | :omniauthable 29 | 30 | # note that this include statement comes AFTER the devise block above 31 | include DeviseTokenAuth::Concerns::User 32 | end 33 | ~~~ 34 | 35 | Some features include routes that you may not want mounted to your app. The following example shows how to disable OAuth and its routes. 36 | 37 | ##### Example: disable OAuth authentication 38 | 39 | First instruct the model not to include the `omniauthable` module. 40 | 41 | ~~~ruby 42 | # app/models/user.rb 43 | class User < ActiveRecord::Base 44 | 45 | # notice that :omniauthable is not included in this block 46 | devise :database_authenticatable, :confirmable, 47 | :recoverable, :trackable, :validatable, 48 | :registerable 49 | 50 | include DeviseTokenAuth::Concerns::User 51 | end 52 | ~~~ 53 | 54 | Now tell the route helper to `skip` mounting the `omniauth_callbacks` controller: 55 | 56 | ~~~ruby 57 | Rails.application.routes.draw do 58 | # config/routes.rb 59 | mount_devise_token_auth_for 'User', at: 'auth', skip: [:omniauth_callbacks] 60 | end 61 | ~~~ 62 | -------------------------------------------------------------------------------- /docs/usage/model_concerns.md: -------------------------------------------------------------------------------- 1 | ## Model Concerns 2 | 3 | ##### DeviseTokenAuth::Concerns::User 4 | 5 | Typical use of this gem will not require the use of any of the following model methods. All authentication should be handled invisibly by the [controller concerns](controller_methods.md). 6 | 7 | Models that include the `DeviseTokenAuth::Concerns::User` concern will have access to the following public methods (read the above section for context on `token` and `client`): 8 | 9 | * **`valid_token?`**: check if an authentication token is valid. Accepts a `token` and `client` as arguments. Returns a boolean. 10 | 11 | **Example**: 12 | ~~~ruby 13 | # extract token + client from auth header 14 | client = request.headers['client'] 15 | token = request.headers['access-token'] 16 | 17 | @resource.valid_token?(token, client) 18 | ~~~ 19 | 20 | * **`create_new_auth_token`**: creates a new auth token with all of the necessary metadata. Accepts `client` as an optional argument. Will generate a new `client` if none is provided. Returns the authentication headers that should be sent by the client as an object. 21 | 22 | **Example**: 23 | ~~~ruby 24 | # extract client from auth header 25 | client = request.headers['client'] 26 | 27 | # update token, generate updated auth headers for response 28 | new_auth_header = @resource.create_new_auth_token(client) 29 | 30 | # update response with the header that will be required by the next request 31 | response.headers.merge!(new_auth_header) 32 | ~~~ 33 | 34 | * **`build_auth_headers`**: generates the auth header that should be sent to the client with the next request. Accepts `token` and `client` as arguments. Returns a string. 35 | 36 | **Example**: 37 | ~~~ruby 38 | # create token 39 | token = DeviseTokenAuth::TokenFactory.create 40 | 41 | # store client + token in user's token hash 42 | @resource.tokens[token.client] = { 43 | token: token.token_hash, 44 | expiry: token.expiry 45 | } 46 | 47 | # generate auth headers for response 48 | new_auth_header = @resource.build_auth_headers(token.token, token.client) 49 | 50 | # update response with the header that will be required by the next request 51 | response.headers.merge!(new_auth_header) 52 | ~~~ 53 | -------------------------------------------------------------------------------- /docs/usage/multiple_models.md: -------------------------------------------------------------------------------- 1 | ## Using multiple models 2 | 3 | ### View Live Multi-User Demos 4 | 5 | * [AngularJS](https://ng-token-auth-demo.herokuapp.com/multi-user) 6 | * [Angular2](https://angular2-token.herokuapp.com) 7 | * [React + jToker](https://j-toker-demo.herokuapp.com/#/alt-user) 8 | 9 | This gem supports the use of multiple user models. One possible use case is to authenticate visitors using a model called `User`, and to authenticate administrators with a model called `Admin`. Take the following steps to add another authentication model to your app: 10 | 11 | 1. Run the install generator for the new model. 12 | ~~~ 13 | rails g devise_token_auth:install Admin admin_auth 14 | ~~~ 15 | 16 | This will create the `Admin` model and define the model's authentication routes with the base path `/admin_auth`. 17 | 18 | 1. Define the routes to be used by the `Admin` user within a [`devise_scope`](https://github.com/plataformatec/devise#configuring-routes). 19 | 20 | **Example**: 21 | 22 | ~~~ruby 23 | Rails.application.routes.draw do 24 | # when using multiple models, controllers will default to the first available 25 | # devise mapping. routes for subsequent devise mappings will need to defined 26 | # within a `devise_scope` block 27 | 28 | # define :users as the first devise mapping: 29 | mount_devise_token_auth_for 'User', at: 'auth' 30 | 31 | # define :admins as the second devise mapping. routes using this class will 32 | # need to be defined within a devise_scope as shown below 33 | mount_devise_token_auth_for "Admin", at: 'admin_auth' 34 | 35 | # this route will authorize requests using the User class 36 | get 'demo/members_only', to: 'demo#members_only' 37 | 38 | # routes within this block will authorize requests using the Admin class 39 | devise_scope :admin do 40 | get 'demo/admins_only', to: 'demo#admins_only' 41 | end 42 | end 43 | ~~~ 44 | 45 | 1. Configure any `Admin` restricted controllers. Controllers will now have access to the methods [described here](#methods): 46 | * `before_action :authenticate_admin!` 47 | * `current_admin` 48 | * `admin_signed_in?` 49 | 50 | 51 | ### Group access 52 | 53 | It is also possible to control access to multiple user types at the same time using groups. The following example shows how to limit controller access to both `User` and `Admin` users. 54 | 55 | ##### Example: group authentication 56 | 57 | ~~~ruby 58 | class DemoGroupController < ApplicationController 59 | devise_token_auth_group :member, contains: [:user, :admin] 60 | before_action :authenticate_member! 61 | 62 | def members_only 63 | render json: { 64 | data: { 65 | message: "Welcome #{current_member.name}", 66 | user: current_member 67 | } 68 | }, status: 200 69 | end 70 | end 71 | ~~~ 72 | 73 | In the above example, the following methods will be available (in addition to `current_user`, `current_admin`, etc.): 74 | 75 | * `before_action: :authenticate_member!` 76 | * `current_member` 77 | * `member_signed_in?` 78 | -------------------------------------------------------------------------------- /docs/usage/routes.md: -------------------------------------------------------------------------------- 1 | ## Mounting Routes 2 | 3 | The authentication routes must be mounted to your project. This gem includes a route helper for this purpose: 4 | 5 | **`mount_devise_token_auth_for`** - similar to `devise_for`, this method is used to append the routes necessary for user authentication. This method accepts the following arguments: 6 | 7 | | Argument | Type | Default | Description | 8 | |---|---|---|---| 9 | |`class_name`| string | 'User' | The name of the class to use for authentication. This class must include the [model concern described here](#model-concerns). | 10 | | `options` | object | {at: 'auth'} | The [routes to be used for authentication](#usage) will be prefixed by the path specified in the `at` param of this object. | 11 | 12 | **Example**: 13 | ~~~ruby 14 | # config/routes.rb 15 | mount_devise_token_auth_for 'User', at: 'auth' 16 | ~~~ 17 | 18 | Any model class can be used, but the class will need to include [`DeviseTokenAuth::Concerns::User`](model_concerns.md) for authentication to work properly. 19 | 20 | You can mount this engine to any route that you like. `/auth` is used by default to conform with the defaults of the [ng-token-auth](https://github.com/lynndylanhurley/ng-token-auth) module and the [jToker](https://github.com/lynndylanhurley/j-toker) plugin. 21 | -------------------------------------------------------------------------------- /gemfiles/rails_4_2.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 4.2" 7 | gem "sqlite3", "~> 1.3.6" 8 | gem "mysql2", "~> 0.4.10" 9 | gem "pg", "~> 0.21" 10 | 11 | group :development, :test do 12 | gem "attr_encrypted" 13 | gem "figaro" 14 | gem "omniauth-facebook" 15 | gem "omniauth-github" 16 | gem "omniauth-google-oauth2" 17 | gem "omniauth-apple" 18 | gem "rack-cors" 19 | gem "thor" 20 | gem "database_cleaner" 21 | gem "factory_bot_rails" 22 | gem "faker" 23 | gem "fuzz_ball" 24 | gem "guard" 25 | gem "guard-minitest" 26 | gem "minitest" 27 | gem "minitest-focus" 28 | gem "minitest-rails" 29 | gem "minitest-reporters" 30 | gem "mocha", ">= 1.5" 31 | gem "pry" 32 | gem "pry-byebug" 33 | gem "pry-remote" 34 | gem "rubocop", require: false 35 | end 36 | 37 | group :test do 38 | gem "rails-controller-testing" 39 | gem "simplecov", "~> 0.10", "< 0.18", require: false 40 | end 41 | 42 | group :development do 43 | gem "github_changelog_generator" 44 | end 45 | 46 | gemspec path: "../" 47 | -------------------------------------------------------------------------------- /gemfiles/rails_4_2_mongoid_5.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 4.2" 7 | gem "mongoid", "~> 5.4" 8 | gem "mongoid-locker", "~> 1.0" 9 | 10 | group :development, :test do 11 | gem "attr_encrypted" 12 | gem "figaro" 13 | gem "omniauth-facebook" 14 | gem "omniauth-github" 15 | gem "omniauth-google-oauth2" 16 | gem "omniauth-apple" 17 | gem "rack-cors" 18 | gem "thor" 19 | gem "database_cleaner-mongoid" 20 | gem "factory_bot_rails" 21 | gem "faker" 22 | gem "fuzz_ball" 23 | gem "guard" 24 | gem "guard-minitest" 25 | gem "minitest" 26 | gem "minitest-focus" 27 | gem "minitest-rails" 28 | gem "minitest-reporters" 29 | gem "mocha", ">= 1.5" 30 | gem "pry" 31 | gem "pry-byebug" 32 | gem "pry-remote" 33 | gem "rubocop", require: false 34 | end 35 | 36 | group :test do 37 | gem "rails-controller-testing" 38 | gem "simplecov", "~> 0.10", "< 0.18", require: false 39 | end 40 | 41 | group :development do 42 | gem "github_changelog_generator" 43 | end 44 | 45 | gemspec path: "../" 46 | -------------------------------------------------------------------------------- /gemfiles/rails_5_0.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.0" 7 | gem "sqlite3", "~> 1.3.6" 8 | gem "mysql2" 9 | gem "pg" 10 | 11 | group :development, :test do 12 | gem "attr_encrypted" 13 | gem "figaro" 14 | gem "omniauth-facebook" 15 | gem "omniauth-github" 16 | gem "omniauth-google-oauth2" 17 | gem "omniauth-apple" 18 | gem "rack-cors" 19 | gem "thor" 20 | gem "database_cleaner" 21 | gem "factory_bot_rails" 22 | gem "faker" 23 | gem "fuzz_ball" 24 | gem "guard" 25 | gem "guard-minitest" 26 | gem "minitest" 27 | gem "minitest-focus" 28 | gem "minitest-rails" 29 | gem "minitest-reporters" 30 | gem "mocha", ">= 1.5" 31 | gem "pry" 32 | gem "pry-byebug" 33 | gem "pry-remote" 34 | gem "rubocop", require: false 35 | end 36 | 37 | group :test do 38 | gem "rails-controller-testing" 39 | gem "simplecov", "~> 0.10", "< 0.18", require: false 40 | end 41 | 42 | group :development do 43 | gem "github_changelog_generator" 44 | end 45 | 46 | gemspec path: "../" 47 | -------------------------------------------------------------------------------- /gemfiles/rails_5_1.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.1" 7 | gem "sqlite3", "~> 1.3.6" 8 | gem "mysql2" 9 | gem "pg" 10 | 11 | group :development, :test do 12 | gem "attr_encrypted" 13 | gem "figaro" 14 | gem "omniauth-facebook" 15 | gem "omniauth-github" 16 | gem "omniauth-google-oauth2" 17 | gem "omniauth-apple" 18 | gem "rack-cors" 19 | gem "thor" 20 | gem "database_cleaner" 21 | gem "factory_bot_rails" 22 | gem "faker" 23 | gem "fuzz_ball" 24 | gem "guard" 25 | gem "guard-minitest" 26 | gem "minitest" 27 | gem "minitest-focus" 28 | gem "minitest-rails" 29 | gem "minitest-reporters" 30 | gem "mocha", ">= 1.5" 31 | gem "pry" 32 | gem "pry-byebug" 33 | gem "pry-remote" 34 | gem "rubocop", require: false 35 | end 36 | 37 | group :test do 38 | gem "rails-controller-testing" 39 | gem "simplecov", "~> 0.10", "< 0.18", require: false 40 | end 41 | 42 | group :development do 43 | gem "github_changelog_generator" 44 | end 45 | 46 | gemspec path: "../" 47 | -------------------------------------------------------------------------------- /gemfiles/rails_5_1_mongoid_6.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.1" 7 | gem "mongoid", "~> 6.4" 8 | gem "mongoid-locker", "~> 1.0" 9 | 10 | group :development, :test do 11 | gem "attr_encrypted" 12 | gem "figaro" 13 | gem "omniauth-facebook" 14 | gem "omniauth-github" 15 | gem "omniauth-google-oauth2" 16 | gem "omniauth-apple" 17 | gem "rack-cors" 18 | gem "thor" 19 | gem "database_cleaner-mongoid" 20 | gem "factory_bot_rails" 21 | gem "faker" 22 | gem "fuzz_ball" 23 | gem "guard" 24 | gem "guard-minitest" 25 | gem "minitest" 26 | gem "minitest-focus" 27 | gem "minitest-rails" 28 | gem "minitest-reporters" 29 | gem "mocha", ">= 1.5" 30 | gem "pry" 31 | gem "pry-byebug" 32 | gem "pry-remote" 33 | gem "rubocop", require: false 34 | end 35 | 36 | group :test do 37 | gem "rails-controller-testing" 38 | gem "simplecov", "~> 0.10", "< 0.18", require: false 39 | end 40 | 41 | group :development do 42 | gem "github_changelog_generator" 43 | end 44 | 45 | gemspec path: "../" 46 | -------------------------------------------------------------------------------- /gemfiles/rails_5_1_mongoid_7.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.1" 7 | gem "mongoid", "~> 7.0" 8 | gem "mongoid-locker", "~> 1.0" 9 | 10 | group :development, :test do 11 | gem "attr_encrypted" 12 | gem "figaro" 13 | gem "omniauth-facebook" 14 | gem "omniauth-github" 15 | gem "omniauth-google-oauth2" 16 | gem "omniauth-apple" 17 | gem "rack-cors" 18 | gem "thor" 19 | gem "database_cleaner-mongoid" 20 | gem "factory_bot_rails" 21 | gem "faker" 22 | gem "fuzz_ball" 23 | gem "guard" 24 | gem "guard-minitest" 25 | gem "minitest" 26 | gem "minitest-focus" 27 | gem "minitest-rails" 28 | gem "minitest-reporters" 29 | gem "mocha", ">= 1.5" 30 | gem "pry" 31 | gem "pry-byebug" 32 | gem "pry-remote" 33 | gem "rubocop", require: false 34 | end 35 | 36 | group :test do 37 | gem "rails-controller-testing" 38 | gem "simplecov", "~> 0.10", "< 0.18", require: false 39 | end 40 | 41 | group :development do 42 | gem "github_changelog_generator" 43 | end 44 | 45 | gemspec path: "../" 46 | -------------------------------------------------------------------------------- /gemfiles/rails_5_2.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.2" 7 | gem "sqlite3", "~> 1.3.6" 8 | gem "mysql2" 9 | gem "pg" 10 | gem 'concurrent-ruby', '1.3.4' 11 | 12 | group :development, :test do 13 | gem "attr_encrypted" 14 | gem "figaro" 15 | gem "omniauth-facebook" 16 | gem "omniauth-github" 17 | gem "omniauth-google-oauth2" 18 | gem "omniauth-apple" 19 | gem "rack-cors" 20 | gem "thor" 21 | gem "database_cleaner" 22 | gem "factory_bot_rails" 23 | gem "faker" 24 | gem "fuzz_ball" 25 | gem "guard" 26 | gem "guard-minitest" 27 | gem "minitest" 28 | gem "minitest-focus" 29 | gem "minitest-rails" 30 | gem "minitest-reporters" 31 | gem "mocha", ">= 1.5" 32 | gem "pry" 33 | gem "pry-byebug" 34 | gem "pry-remote" 35 | gem "rubocop", require: false 36 | end 37 | 38 | group :test do 39 | gem "rails-controller-testing" 40 | gem "simplecov", "~> 0.10", "< 0.18", require: false 41 | end 42 | 43 | group :development do 44 | gem "github_changelog_generator" 45 | end 46 | 47 | gemspec path: "../" 48 | -------------------------------------------------------------------------------- /gemfiles/rails_5_2_mongoid_6.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.2" 7 | gem "mongoid", "~> 6.4" 8 | gem "mongoid-locker", "~> 1.0" 9 | 10 | group :development, :test do 11 | gem "attr_encrypted" 12 | gem "figaro" 13 | gem "omniauth-facebook" 14 | gem "omniauth-github" 15 | gem "omniauth-google-oauth2" 16 | gem "omniauth-apple" 17 | gem "rack-cors" 18 | gem "thor" 19 | gem "database_cleaner-mongoid" 20 | gem "factory_bot_rails" 21 | gem "faker" 22 | gem "fuzz_ball" 23 | gem "guard" 24 | gem "guard-minitest" 25 | gem "minitest" 26 | gem "minitest-focus" 27 | gem "minitest-rails" 28 | gem "minitest-reporters" 29 | gem "mocha", ">= 1.5" 30 | gem "pry" 31 | gem "pry-byebug" 32 | gem "pry-remote" 33 | gem "rubocop", require: false 34 | end 35 | 36 | group :test do 37 | gem "rails-controller-testing" 38 | gem "simplecov", "~> 0.10", "< 0.18", require: false 39 | end 40 | 41 | group :development do 42 | gem "github_changelog_generator" 43 | end 44 | 45 | gemspec path: "../" 46 | -------------------------------------------------------------------------------- /gemfiles/rails_5_2_mongoid_7.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 5.2" 7 | gem "mongoid", "~> 7.0" 8 | gem "mongoid-locker", "~> 1.0" 9 | gem 'concurrent-ruby', '1.3.4' 10 | 11 | group :development, :test do 12 | gem "attr_encrypted" 13 | gem "figaro" 14 | gem "omniauth-facebook" 15 | gem "omniauth-github" 16 | gem "omniauth-google-oauth2" 17 | gem "omniauth-apple" 18 | gem "rack-cors" 19 | gem "thor" 20 | gem "database_cleaner-mongoid" 21 | gem "factory_bot_rails" 22 | gem "faker" 23 | gem "fuzz_ball" 24 | gem "guard" 25 | gem "guard-minitest" 26 | gem "minitest" 27 | gem "minitest-focus" 28 | gem "minitest-rails" 29 | gem "minitest-reporters" 30 | gem "mocha", ">= 1.5" 31 | gem "pry" 32 | gem "pry-byebug" 33 | gem "pry-remote" 34 | gem "rubocop", require: false 35 | end 36 | 37 | group :test do 38 | gem "rails-controller-testing" 39 | gem "simplecov", "~> 0.10", "< 0.18", require: false 40 | end 41 | 42 | group :development do 43 | gem "github_changelog_generator" 44 | end 45 | 46 | gemspec path: "../" 47 | -------------------------------------------------------------------------------- /gemfiles/rails_6_0.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 6.0" 7 | gem "sqlite3", "~> 1.4.1" 8 | gem "mysql2" 9 | gem "pg" 10 | gem 'concurrent-ruby', '1.3.4' 11 | 12 | group :development, :test do 13 | gem "attr_encrypted" 14 | gem "figaro" 15 | gem "omniauth-facebook" 16 | gem "omniauth-github" 17 | gem "omniauth-google-oauth2" 18 | gem 'omniauth-apple' 19 | gem "rack-cors", require: "rack/cors" 20 | gem "thor" 21 | gem "database_cleaner" 22 | gem "factory_bot_rails" 23 | gem "faker" 24 | gem "fuzz_ball" 25 | gem "guard" 26 | gem "guard-minitest" 27 | gem "minitest" 28 | gem "minitest-focus" 29 | gem "minitest-rails" 30 | gem "minitest-reporters" 31 | gem "mocha", ">= 1.5" 32 | gem "pry", "< 0.13" 33 | gem "pry-byebug" 34 | gem "pry-remote" 35 | gem "rubocop", require: false 36 | end 37 | 38 | group :test do 39 | gem "rails-controller-testing" 40 | gem "simplecov", "~> 0.10", "< 0.18", require: false 41 | end 42 | 43 | group :development do 44 | gem "github_changelog_generator" 45 | end 46 | 47 | gemspec path: "../" 48 | -------------------------------------------------------------------------------- /gemfiles/rails_6_0_mongoid_7.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 1.9" 6 | gem "rails", "~> 6.0" 7 | gem "mongoid", "~> 7.0" 8 | gem "mongoid-locker", "~> 1.0" 9 | gem 'concurrent-ruby', '1.3.4' 10 | 11 | group :development, :test do 12 | gem "attr_encrypted" 13 | gem "figaro" 14 | gem "omniauth-facebook" 15 | gem "omniauth-github" 16 | gem "omniauth-google-oauth2" 17 | gem "omniauth-apple" 18 | gem "rack-cors" 19 | gem "thor" 20 | gem "database_cleaner-mongoid" 21 | gem "factory_bot_rails" 22 | gem "faker" 23 | gem "fuzz_ball" 24 | gem "guard" 25 | gem "guard-minitest" 26 | gem "minitest" 27 | gem "minitest-focus" 28 | gem "minitest-rails" 29 | gem "minitest-reporters" 30 | gem "mocha", ">= 1.5" 31 | gem "pry" 32 | gem "pry-byebug" 33 | gem "pry-remote" 34 | gem "rubocop", require: false 35 | end 36 | 37 | group :test do 38 | gem "rails-controller-testing" 39 | gem "simplecov", "~> 0.10", "< 0.18", require: false 40 | end 41 | 42 | group :development do 43 | gem "github_changelog_generator" 44 | end 45 | 46 | gemspec path: "../" 47 | -------------------------------------------------------------------------------- /gemfiles/rails_7_0.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 2.0" 6 | gem "omniauth-rails_csrf_protection" 7 | gem "rails", "~> 7.0" 8 | gem "sqlite3", "~> 1.4.1" 9 | gem "mysql2" 10 | gem "pg" 11 | gem 'concurrent-ruby', '1.3.4' 12 | 13 | group :development, :test do 14 | gem "attr_encrypted" 15 | gem "figaro", "~> 1.2" 16 | gem "omniauth-facebook" 17 | gem "omniauth-github" 18 | gem "omniauth-google-oauth2" 19 | gem 'omniauth-apple' 20 | gem "rack-cors" 21 | gem "thor", "~> 1.2" 22 | gem "database_cleaner" 23 | gem "factory_bot_rails" 24 | gem "faker", "~> 2.16" 25 | gem "fuzz_ball" 26 | gem "guard" 27 | gem "guard-minitest" 28 | gem "minitest" 29 | gem "minitest-focus" 30 | gem "minitest-rails", "~> 7" 31 | gem "minitest-reporters" 32 | gem "mocha", ">= 1.5" 33 | gem "pry" 34 | gem "pry-byebug" 35 | gem "pry-remote" 36 | gem "rubocop", require: false 37 | end 38 | 39 | group :test do 40 | gem "rails-controller-testing" 41 | gem "simplecov", require: false 42 | end 43 | 44 | group :development do 45 | gem "github_changelog_generator" 46 | end 47 | 48 | gemspec path: "../" 49 | -------------------------------------------------------------------------------- /gemfiles/rails_7_0_mongoid_7.gemfile: -------------------------------------------------------------------------------- 1 | # This file was generated by Appraisal 2 | 3 | source "https://rubygems.org" 4 | 5 | gem "omniauth", "~> 2.0" 6 | gem "rails", "~> 7.0" 7 | gem "omniauth-rails_csrf_protection" 8 | gem "mongoid", "~> 7.0" 9 | gem "mongoid-locker", "~> 1.0" 10 | gem 'concurrent-ruby', '1.3.4' 11 | 12 | group :development, :test do 13 | gem "attr_encrypted" 14 | gem "figaro", "~> 1.2" 15 | gem "omniauth-facebook" 16 | gem "omniauth-github" 17 | gem "omniauth-google-oauth2" 18 | gem "omniauth-apple" 19 | gem "rack-cors" 20 | gem "thor", "~> 1.2" 21 | gem "database_cleaner-mongoid" 22 | gem "factory_bot_rails" 23 | gem "faker", "~> 2.16" 24 | gem "fuzz_ball" 25 | gem "guard" 26 | gem "guard-minitest" 27 | gem "minitest" 28 | gem "minitest-focus" 29 | gem "minitest-rails", "~> 7" 30 | gem "minitest-reporters" 31 | gem "mocha", ">= 1.5" 32 | gem "pry" 33 | gem "pry-byebug" 34 | gem "pry-remote" 35 | gem "rubocop", require: false 36 | end 37 | 38 | group :test do 39 | gem "rails-controller-testing" 40 | gem "simplecov", require: false 41 | end 42 | 43 | group :development do 44 | gem "github_changelog_generator" 45 | end 46 | 47 | gemspec path: "../" 48 | -------------------------------------------------------------------------------- /lib/devise_token_auth.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'devise' 4 | 5 | module DeviseTokenAuth 6 | end 7 | 8 | require 'devise_token_auth/engine' 9 | require 'devise_token_auth/controllers/helpers' 10 | require 'devise_token_auth/controllers/url_helpers' 11 | require 'devise_token_auth/url' 12 | require 'devise_token_auth/errors' 13 | require 'devise_token_auth/blacklist' 14 | require 'devise_token_auth/token_factory' 15 | -------------------------------------------------------------------------------- /lib/devise_token_auth/blacklist.rb: -------------------------------------------------------------------------------- 1 | # don't serialize tokens 2 | if defined? Devise::Models::Authenticatable::UNSAFE_ATTRIBUTES_FOR_SERIALIZATION 3 | Devise::Models::Authenticatable::UNSAFE_ATTRIBUTES_FOR_SERIALIZATION << :tokens 4 | else 5 | Devise::Models::Authenticatable::BLACKLIST_FOR_SERIALIZATION << :tokens 6 | end 7 | -------------------------------------------------------------------------------- /lib/devise_token_auth/controllers/url_helpers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | module Controllers 5 | module UrlHelpers 6 | def self.define_helpers(mapping) 7 | end 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /lib/devise_token_auth/errors.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | module Errors 5 | class NoResourceDefinedError < StandardError; end 6 | class InvalidModel < StandardError; end 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /lib/devise_token_auth/url.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth::Url 4 | 5 | def self.generate(url, params = {}) 6 | uri = URI(url) 7 | 8 | res = "#{uri.scheme}://#{uri.host}" 9 | res += ":#{uri.port}" if (uri.port && uri.port != 80 && uri.port != 443) 10 | res += uri.path.to_s if uri.path 11 | query = [uri.query, params.to_query].reject(&:blank?).join('&') 12 | res += "?#{query}" 13 | res += "##{uri.fragment}" if uri.fragment 14 | # repeat any query params after the fragment to deal with Angular eating any pre fragment query params, used 15 | # in the reset password redirect url 16 | res += "?#{query}" if uri.fragment 17 | 18 | res 19 | end 20 | 21 | def self.whitelisted?(url) 22 | url.nil? || \ 23 | !!DeviseTokenAuth.redirect_whitelist.find do |pattern| 24 | !!Wildcat.new(pattern).match(url) 25 | end 26 | end 27 | 28 | # wildcard convenience class 29 | class Wildcat 30 | def self.parse_to_regex(str) 31 | escaped = Regexp.escape(str).gsub('\*','.*?') 32 | Regexp.new("^#{escaped}$", Regexp::IGNORECASE) 33 | end 34 | 35 | def initialize(str) 36 | @regex = self.class.parse_to_regex(str) 37 | end 38 | 39 | def match(str) 40 | !!@regex.match(str) 41 | end 42 | end 43 | 44 | end 45 | -------------------------------------------------------------------------------- /lib/devise_token_auth/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | VERSION = '1.2.5'.freeze 5 | end 6 | -------------------------------------------------------------------------------- /lib/generators/devise_token_auth/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | This generator will install all the necessary configuration and migration 3 | files for the devise_token_auth gem. See 4 | https://github.com/lynndylanhurley/devise_token_auth for more information. 5 | 6 | Arguments: 7 | USER_CLASS # The name of the class to use for user authentication. Default is 8 | # 'User' 9 | MOUNT_PATH # The path at which to mount the authentication routes. Default is 10 | # 'auth'. More detail documentation is here: 11 | # https://devise-token-auth.gitbook.io/devise-token-auth/usage 12 | 13 | Example: 14 | rails generate devise_token_auth:install User auth 15 | 16 | This will create: 17 | config/initializers/devise_token_auth.rb 18 | db/migrate/<%= Time.zone.now.utc.strftime("%Y%m%d%H%M%S") %>_create_devise_token_auth_create_users.rb 19 | app/models/user.rb 20 | 21 | If 'app/models/user.rb' already exists, the following line will be inserted 22 | after the class definition: 23 | include DeviseTokenAuth::Concerns::User 24 | 25 | The following line will be inserted into your application controller at 26 | app/controllers/application_controller.rb: 27 | include DeviseTokenAuth::Concerns::SetUserByToken 28 | 29 | The following line will be inserted at the top of 'config/routes.rb' if it 30 | does not already exist: 31 | mount_devise_token_auth_for "User", at: 'auth' 32 | -------------------------------------------------------------------------------- /lib/generators/devise_token_auth/install_mongoid_generator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'install_generator_helpers' 4 | 5 | module DeviseTokenAuth 6 | class InstallMongoidGenerator < Rails::Generators::Base 7 | include DeviseTokenAuth::InstallGeneratorHelpers 8 | 9 | def create_user_model 10 | fname = "app/models/#{user_class.underscore}.rb" 11 | if File.exist?(File.join(destination_root, fname)) 12 | inclusion = 'include DeviseTokenAuth::Concerns::User' 13 | unless parse_file_for_line(fname, inclusion) 14 | inject_into_file fname, before: /end\s\z/ do <<-'RUBY' 15 | 16 | include Mongoid::Locker 17 | 18 | field :locker_locked_at, type: Time 19 | field :locker_locked_until, type: Time 20 | 21 | locker locked_at_field: :locker_locked_at, 22 | locked_until_field: :locker_locked_until 23 | 24 | ## Required 25 | field :provider, type: String 26 | field :uid, type: String, default: '' 27 | 28 | ## Tokens 29 | field :tokens, type: Hash, default: {} 30 | 31 | # Include default devise modules. Others available are: 32 | # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 33 | devise :database_authenticatable, :registerable, 34 | :recoverable, :rememberable, :validatable 35 | include DeviseTokenAuth::Concerns::User 36 | 37 | index({ uid: 1, provider: 1}, { name: 'uid_provider_index', unique: true, background: true }) 38 | RUBY 39 | end 40 | end 41 | else 42 | template('user_mongoid.rb.erb', fname) 43 | end 44 | end 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /lib/generators/devise_token_auth/install_views_generator.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module DeviseTokenAuth 4 | class InstallViewsGenerator < Rails::Generators::Base 5 | source_root File.expand_path('../../../app/views/devise/mailer', __dir__) 6 | 7 | def copy_mailer_templates 8 | copy_file( 9 | 'confirmation_instructions.html.erb', 10 | 'app/views/devise/mailer/confirmation_instructions.html.erb' 11 | ) 12 | copy_file( 13 | 'reset_password_instructions.html.erb', 14 | 'app/views/devise/mailer/reset_password_instructions.html.erb' 15 | ) 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /lib/generators/devise_token_auth/templates/devise_token_auth_create_users.rb.erb: -------------------------------------------------------------------------------- 1 | class DeviseTokenAuthCreate<%= user_class.pluralize.gsub("::","") %> < ActiveRecord::Migration<%= "[#{Rails::VERSION::STRING[0..2]}]" if Rails::VERSION::MAJOR > 4 %> 2 | def change 3 | <% table_name = @user_class.pluralize.gsub("::","").underscore %> 4 | create_table(:<%= table_name %><%= primary_key_type %>) do |t| 5 | ## Required 6 | t.string :provider, :null => false, :default => "email" 7 | t.string :uid, :null => false, :default => "" 8 | 9 | ## Database authenticatable 10 | t.string :encrypted_password, :null => false, :default => "" 11 | 12 | ## Recoverable 13 | t.string :reset_password_token 14 | t.datetime :reset_password_sent_at 15 | t.boolean :allow_password_change, :default => false 16 | 17 | ## Rememberable 18 | t.datetime :remember_created_at 19 | 20 | ## Confirmable 21 | t.string :confirmation_token 22 | t.datetime :confirmed_at 23 | t.datetime :confirmation_sent_at 24 | t.string :unconfirmed_email # Only if using reconfirmable 25 | 26 | ## Lockable 27 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 28 | # t.string :unlock_token # Only if unlock strategy is :email or :both 29 | # t.datetime :locked_at 30 | 31 | ## User Info 32 | t.string :name 33 | t.string :nickname 34 | t.string :image 35 | t.string :email 36 | 37 | ## Tokens 38 | <%= json_supported_database? ? 't.json :tokens' : 't.text :tokens' %> 39 | 40 | t.timestamps 41 | end 42 | 43 | add_index :<%= table_name %>, :email, unique: true 44 | add_index :<%= table_name %>, [:uid, :provider], unique: true 45 | add_index :<%= table_name %>, :reset_password_token, unique: true 46 | add_index :<%= table_name %>, :confirmation_token, unique: true 47 | # add_index :<%= table_name %>, :unlock_token, unique: true 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /lib/generators/devise_token_auth/templates/user.rb.erb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class <%= user_class %> < ActiveRecord::Base 4 | # Include default devise modules. Others available are: 5 | # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 6 | devise :database_authenticatable, :registerable, 7 | :recoverable, :rememberable, :validatable 8 | include DeviseTokenAuth::Concerns::User 9 | end 10 | -------------------------------------------------------------------------------- /lib/generators/devise_token_auth/templates/user_mongoid.rb.erb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class <%= user_class %> 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## Database authenticatable 15 | field :email, type: String, default: '' 16 | field :encrypted_password, type: String, default: '' 17 | 18 | ## Recoverable 19 | field :reset_password_token, type: String 20 | field :reset_password_sent_at, type: Time 21 | field :reset_password_redirect_url, type: String 22 | field :allow_password_change, type: Boolean, default: false 23 | 24 | ## Rememberable 25 | field :remember_created_at, type: Time 26 | 27 | ## Confirmable 28 | field :confirmation_token, type: String 29 | field :confirmed_at, type: Time 30 | field :confirmation_sent_at, type: Time 31 | field :unconfirmed_email, type: String # Only if using reconfirmable 32 | 33 | ## Lockable 34 | # field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts 35 | # field :unlock_token, type: String # Only if unlock strategy is :email or :both 36 | # field :locked_at, type: Time 37 | 38 | ## Required 39 | field :provider, type: String 40 | field :uid, type: String, default: '' 41 | 42 | ## Tokens 43 | field :tokens, type: Hash, default: {} 44 | 45 | # Include default devise modules. Others available are: 46 | # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 47 | devise :database_authenticatable, :registerable, 48 | :recoverable, :rememberable, :validatable 49 | include DeviseTokenAuth::Concerns::User 50 | 51 | index({ email: 1 }, { name: 'email_index', unique: true, background: true }) 52 | index({ reset_password_token: 1 }, { name: 'reset_password_token_index', unique: true, sparse: true, background: true }) 53 | index({ confirmation_token: 1 }, { name: 'confirmation_token_index', unique: true, sparse: true, background: true }) 54 | index({ uid: 1, provider: 1}, { name: 'uid_provider_index', unique: true, background: true }) 55 | # index({ unlock_token: 1 }, { name: 'unlock_token_index', unique: true, sparse: true, background: true }) 56 | end 57 | -------------------------------------------------------------------------------- /lib/tasks/devise_token_auth_tasks.rake: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # desc "Explaining what the task does" 4 | # task :devise_token_auth do 5 | # # Task goes here 6 | # end 7 | -------------------------------------------------------------------------------- /test/controllers/custom/custom_confirmations_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Custom::ConfirmationsControllerTest < ActionController::TestCase 6 | describe Custom::ConfirmationsController do 7 | include CustomControllersRoutes 8 | 9 | before do 10 | @redirect_url = Faker::Internet.url 11 | @new_user = create(:user) 12 | @new_user.send_confirmation_instructions(redirect_url: @redirect_url) 13 | @mail = ActionMailer::Base.deliveries.last 14 | @token = @mail.body.match(/confirmation_token=([^&]*)[&"]/)[1] 15 | @client_config = @mail.body.match(/config=([^&]*)&/)[1] 16 | 17 | get :show, 18 | params: { confirmation_token: @token, redirect_url: @redirect_url } 19 | end 20 | 21 | test 'yield resource to block on show success' do 22 | assert @controller.show_block_called?, 'show failed to yield resource to provided block' 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /test/controllers/custom/custom_omniauth_callbacks_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Custom::OmniauthCallbacksControllerTest < ActionDispatch::IntegrationTest 6 | describe Custom::OmniauthCallbacksController do 7 | include CustomControllersRoutes 8 | 9 | setup do 10 | OmniAuth.config.test_mode = true 11 | OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new( 12 | provider: 'facebook', 13 | uid: '123545', 14 | info: { 15 | name: 'swong', 16 | email: 'swongsong@yandex.ru' 17 | } 18 | ) 19 | end 20 | 21 | test 'yield resource to block on omniauth_success success' do 22 | @redirect_url = 'http://ng-token-auth.dev/' 23 | post '/nice_user_auth/facebook', 24 | params: { auth_origin_url: @redirect_url, 25 | omniauth_window_type: 'newWindow' } 26 | 27 | follow_all_redirects! 28 | 29 | assert @controller.omniauth_success_block_called?, 30 | 'omniauth_success failed to yield resource to provided block' 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /test/controllers/custom/custom_registrations_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Custom::RegistrationsControllerTest < ActionDispatch::IntegrationTest 6 | describe Custom::RegistrationsController do 7 | include CustomControllersRoutes 8 | 9 | before do 10 | @create_params = attributes_for(:user, 11 | confirm_success_url: Faker::Internet.url, 12 | unpermitted_param: '(x_x)') 13 | 14 | @existing_user = create(:user, :confirmed) 15 | @auth_headers = @existing_user.create_new_auth_token 16 | @client_id = @auth_headers['client'] 17 | 18 | # ensure request is not treated as batch request 19 | age_token(@existing_user, @client_id) 20 | end 21 | 22 | test 'yield resource to block on create success' do 23 | post '/nice_user_auth', params: @create_params 24 | assert @controller.create_block_called?, 25 | 'create failed to yield resource to provided block' 26 | end 27 | 28 | test 'yield resource to block on create success with custom json' do 29 | post '/nice_user_auth', params: @create_params 30 | 31 | @data = JSON.parse(response.body) 32 | 33 | assert @controller.create_block_called?, 34 | 'create failed to yield resource to provided block' 35 | assert_equal @data['custom'], 'foo' 36 | end 37 | 38 | test 'yield resource to block on update success' do 39 | put '/nice_user_auth', 40 | params: { 41 | nickname: "Ol' Sunshine-face" 42 | }, 43 | headers: @auth_headers 44 | assert @controller.update_block_called?, 45 | 'update failed to yield resource to provided block' 46 | end 47 | 48 | test 'yield resource to block on destroy success' do 49 | delete '/nice_user_auth', headers: @auth_headers 50 | assert @controller.destroy_block_called?, 51 | 'destroy failed to yield resource to provided block' 52 | end 53 | 54 | describe 'when overriding #build_resource' do 55 | test 'it fails' do 56 | Custom::RegistrationsController.any_instance.stubs(:build_resource).returns(nil) 57 | assert_raises DeviseTokenAuth::Errors::NoResourceDefinedError do 58 | post '/nice_user_auth', params: @create_params 59 | end 60 | end 61 | end 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /test/controllers/custom/custom_sessions_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Custom::SessionsControllerTest < ActionController::TestCase 6 | describe Custom::SessionsController do 7 | include CustomControllersRoutes 8 | 9 | before do 10 | @existing_user = create(:user, :confirmed) 11 | end 12 | 13 | test 'yield resource to block on create success' do 14 | post :create, 15 | params: { 16 | email: @existing_user.email, 17 | password: @existing_user.password 18 | } 19 | assert @controller.create_block_called?, 20 | 'create failed to yield resource to provided block' 21 | end 22 | 23 | test 'yield resource to block on destroy success' do 24 | @auth_headers = @existing_user.create_new_auth_token 25 | request.headers.merge!(@auth_headers) 26 | delete :destroy, format: :json 27 | assert @controller.destroy_block_called?, 28 | 'destroy failed to yield resource to provided block' 29 | end 30 | 31 | test 'render method override' do 32 | post :create, 33 | params: { email: @existing_user.email, 34 | password: @existing_user.password } 35 | @data = JSON.parse(response.body) 36 | assert_equal @data['custom'], 'foo' 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /test/controllers/custom/custom_token_validations_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class Custom::TokenValidationsControllerTest < ActionDispatch::IntegrationTest 6 | describe Custom::TokenValidationsController do 7 | include CustomControllersRoutes 8 | 9 | before do 10 | @resource = create(:user, :confirmed) 11 | 12 | @auth_headers = @resource.create_new_auth_token 13 | 14 | @token = @auth_headers['access-token'] 15 | @client_id = @auth_headers['client'] 16 | @expiry = @auth_headers['expiry'] 17 | 18 | # ensure that request is not treated as batch request 19 | age_token(@resource, @client_id) 20 | end 21 | 22 | test 'yield resource to block on validate_token success' do 23 | get '/nice_user_auth/validate_token', 24 | params: {}, 25 | headers: @auth_headers 26 | assert @controller.validate_token_block_called?, 27 | 'validate_token failed to yield resource to provided block' 28 | end 29 | 30 | test 'yield resource to block on validate_token success with custom json' do 31 | get '/nice_user_auth/validate_token', 32 | params: {}, 33 | headers: @auth_headers 34 | 35 | @data = JSON.parse(response.body) 36 | 37 | assert @controller.validate_token_block_called?, 38 | 'validate_token failed to yield resource to provided block' 39 | assert_equal @data['custom'], 'foo' 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /test/controllers/overrides/confirmations_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | # was the web request successful? 6 | # was the user redirected to the right page? 7 | # was the user successfully authenticated? 8 | # was the correct object stored in the response? 9 | # was the appropriate message delivered in the json payload? 10 | 11 | class Overrides::ConfirmationsControllerTest < ActionDispatch::IntegrationTest 12 | include OverridesControllersRoutes 13 | 14 | describe Overrides::ConfirmationsController do 15 | before do 16 | @redirect_url = Faker::Internet.url 17 | @new_user = create(:user) 18 | 19 | # generate + send email 20 | @new_user.send_confirmation_instructions(redirect_url: @redirect_url) 21 | 22 | @mail = ActionMailer::Base.deliveries.last 23 | @confirmation_path = @mail.body.match(/localhost([^\"]*)\"/)[1] 24 | 25 | # visit confirmation link 26 | get @confirmation_path 27 | 28 | # reload user from db 29 | @new_user.reload 30 | end 31 | 32 | test 'user is confirmed' do 33 | assert @new_user.confirmed? 34 | end 35 | 36 | test 'user can be authenticated via confirmation link' do 37 | # hard coded in override controller 38 | override_proof_str = '(^^,)' 39 | 40 | # ensure present in redirect URL 41 | override_proof_param = CGI.unescape(response.headers['Location'] 42 | .match(/override_proof=([^&]*)&/)[1]) 43 | 44 | assert_equal override_proof_str, override_proof_param 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /test/controllers/overrides/omniauth_callbacks_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | # was the web request successful? 6 | # was the user redirected to the right page? 7 | # was the user successfully authenticated? 8 | # was the correct object stored in the response? 9 | # was the appropriate message delivered in the json payload? 10 | 11 | class Overrides::OmniauthCallbacksControllerTest < ActionDispatch::IntegrationTest 12 | include OverridesControllersRoutes 13 | 14 | describe Overrides::OmniauthCallbacksController do 15 | before do 16 | OmniAuth.config.test_mode = true 17 | OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new( 18 | provider: 'facebook', 19 | uid: '123545', 20 | info: { 21 | name: 'chong', 22 | email: 'chongbong@aol.com' 23 | } 24 | ) 25 | 26 | @favorite_color = 'gray' 27 | 28 | post '/evil_user_auth/facebook', 29 | params: { 30 | auth_origin_url: Faker::Internet.url, 31 | favorite_color: @favorite_color, 32 | omniauth_window_type: 'newWindow' 33 | } 34 | 35 | follow_all_redirects! 36 | 37 | @resource = assigns(:resource) 38 | end 39 | 40 | test 'request is successful' do 41 | assert_equal 200, response.status 42 | end 43 | 44 | test 'controller was overridden' do 45 | assert_equal @resource.nickname, 46 | Overrides::OmniauthCallbacksController::DEFAULT_NICKNAME 47 | end 48 | 49 | test 'whitelisted param was allowed' do 50 | assert_equal @favorite_color, @resource.favorite_color 51 | end 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /test/controllers/overrides/passwords_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | # was the web request successful? 6 | # was the user redirected to the right page? 7 | # was the user successfully authenticated? 8 | # was the correct object stored in the response? 9 | # was the appropriate message delivered in the json payload? 10 | 11 | class Overrides::PasswordsControllerTest < ActionDispatch::IntegrationTest 12 | include OverridesControllersRoutes 13 | 14 | describe Overrides::PasswordsController do 15 | before do 16 | @resource = create(:user, :confirmed) 17 | 18 | post '/evil_user_auth/password', 19 | params: { 20 | email: @resource.email, 21 | redirect_url: Faker::Internet.url 22 | } 23 | 24 | mail = ActionMailer::Base.deliveries.last 25 | @resource.reload 26 | 27 | mail_reset_token = mail.body.match(/reset_password_token=(.*)\"/)[1] 28 | mail_redirect_url = CGI.unescape(mail.body.match(/redirect_url=([^&]*)&/)[1]) 29 | 30 | get '/evil_user_auth/password/edit', 31 | params: { 32 | reset_password_token: mail_reset_token, 33 | redirect_url: mail_redirect_url 34 | } 35 | 36 | @resource.reload 37 | 38 | _, raw_query_string = response.location.split('?') 39 | @query_string = Rack::Utils.parse_nested_query(raw_query_string) 40 | end 41 | 42 | test 'response should have success redirect status' do 43 | assert_equal 302, response.status 44 | end 45 | 46 | test 'response should contain auth params + override proof' do 47 | assert @query_string['access-token'] 48 | assert @query_string['client'] 49 | assert @query_string['client_id'] 50 | assert @query_string['expiry'] 51 | assert @query_string['override_proof'] 52 | assert @query_string['reset_password'] 53 | assert @query_string['token'] 54 | assert @query_string['uid'] 55 | end 56 | 57 | test 'override proof is correct' do 58 | assert_equal( 59 | @query_string['override_proof'], 60 | Overrides::PasswordsController::OVERRIDE_PROOF 61 | ) 62 | end 63 | end 64 | end 65 | -------------------------------------------------------------------------------- /test/controllers/overrides/registrations_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | # was the web request successful? 6 | # was the user redirected to the right page? 7 | # was the user successfully authenticated? 8 | # was the correct object stored in the response? 9 | # was the appropriate message delivered in the json payload? 10 | 11 | class Overrides::RegistrationsControllerTest < ActionDispatch::IntegrationTest 12 | include OverridesControllersRoutes 13 | 14 | describe Overrides::RegistrationsController do 15 | describe 'Succesful Registration update' do 16 | before do 17 | @existing_user = create(:user, :confirmed) 18 | @auth_headers = @existing_user.create_new_auth_token 19 | @client_id = @auth_headers['client'] 20 | @favorite_color = 'pink' 21 | 22 | # ensure request is not treated as batch request 23 | age_token(@existing_user, @client_id) 24 | 25 | # test valid update param 26 | @new_operating_thetan = 1_000_000 27 | 28 | put '/evil_user_auth', 29 | params: { favorite_color: @favorite_color }, 30 | headers: @auth_headers 31 | 32 | @data = JSON.parse(response.body) 33 | @existing_user.reload 34 | end 35 | 36 | test 'user was updated' do 37 | assert_equal @favorite_color, @existing_user.favorite_color 38 | end 39 | 40 | test 'controller was overridden' do 41 | assert_equal Overrides::RegistrationsController::OVERRIDE_PROOF, 42 | @data['override_proof'] 43 | end 44 | end 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /test/controllers/overrides/sessions_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | # was the web request successful? 6 | # was the user redirected to the right page? 7 | # was the user successfully authenticated? 8 | # was the correct object stored in the response? 9 | # was the appropriate message delivered in the json payload? 10 | 11 | class Overrides::RegistrationsControllerTest < ActionDispatch::IntegrationTest 12 | include OverridesControllersRoutes 13 | 14 | describe Overrides::RegistrationsController do 15 | before do 16 | @existing_user = create(:user, :confirmed) 17 | 18 | post '/evil_user_auth/sign_in', 19 | params: { email: @existing_user.email, 20 | password: @existing_user.password } 21 | 22 | @resource = assigns(:resource) 23 | @data = JSON.parse(response.body) 24 | end 25 | 26 | test 'request should succeed' do 27 | assert_equal 200, response.status 28 | end 29 | 30 | test 'controller was overridden' do 31 | assert_equal Overrides::RegistrationsController::OVERRIDE_PROOF, 32 | @data['override_proof'] 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /test/controllers/overrides/token_validations_controller_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | # was the web request successful? 6 | # was the user redirected to the right page? 7 | # was the user successfully authenticated? 8 | # was the correct object stored in the response? 9 | # was the appropriate message delivered in the json payload? 10 | 11 | class Overrides::TokenValidationsControllerTest < ActionDispatch::IntegrationTest 12 | include OverridesControllersRoutes 13 | 14 | describe Overrides::TokenValidationsController do 15 | before do 16 | @resource = create(:user, :confirmed) 17 | 18 | @auth_headers = @resource.create_new_auth_token 19 | 20 | @token = @auth_headers['access-token'] 21 | @client_id = @auth_headers['client'] 22 | @expiry = @auth_headers['expiry'] 23 | 24 | # ensure that request is not treated as batch request 25 | age_token(@resource, @client_id) 26 | 27 | get '/evil_user_auth/validate_token', 28 | params: {}, 29 | headers: @auth_headers 30 | 31 | @resp = JSON.parse(response.body) 32 | end 33 | 34 | test 'token valid' do 35 | assert_equal 200, response.status 36 | end 37 | 38 | test 'controller was overridden' do 39 | assert_equal Overrides::TokenValidationsController::OVERRIDE_PROOF, 40 | @resp['override_proof'] 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /test/dummy/.powder: -------------------------------------------------------------------------------- 1 | devise-token-auth 2 | -------------------------------------------------------------------------------- /test/dummy/README.rdoc: -------------------------------------------------------------------------------- 1 | == README 2 | 3 | This README would normally document whatever steps are necessary to get the 4 | application up and running. 5 | 6 | Things you may want to cover: 7 | 8 | * Ruby version 9 | 10 | * System dependencies 11 | 12 | * Configuration 13 | 14 | * Database creation 15 | 16 | * Database initialization 17 | 18 | * How to run the test suite 19 | 20 | * Services (job queues, cache servers, search engines, etc.) 21 | 22 | * Deployment instructions 23 | 24 | * ... 25 | 26 | 27 | Please feel free to use a different markup language if you do not plan to run 28 | rake doc:app. 29 | -------------------------------------------------------------------------------- /test/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Add your own tasks in files placed in lib/tasks ending in .rake, 4 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 5 | 6 | require File.expand_path('config/application', __dir__) 7 | 8 | Rails.application.load_tasks 9 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/confirmable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ConfirmableUser < ActiveRecord::Base 4 | # Include default devise modules. 5 | devise :database_authenticatable, :registerable, 6 | :recoverable, :rememberable, 7 | :validatable, :confirmable 8 | DeviseTokenAuth.send_confirmation_email = true 9 | include DeviseTokenAuth::Concerns::User 10 | DeviseTokenAuth.send_confirmation_email = false 11 | end 12 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/lockable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class LockableUser < ActiveRecord::Base 4 | # Include default devise modules. 5 | devise :database_authenticatable, :registerable, :lockable 6 | include DeviseTokenAuth::Concerns::User 7 | end 8 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/mang.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Mang < ActiveRecord::Base 4 | include DeviseTokenAuth::Concerns::User 5 | end 6 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/only_email_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class OnlyEmailUser < ActiveRecord::Base 4 | # Include default devise modules. 5 | devise :database_authenticatable, :registerable 6 | include DeviseTokenAuth::Concerns::User 7 | end 8 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/scoped_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ScopedUser < ActiveRecord::Base 4 | # Include default devise modules. 5 | devise :database_authenticatable, :registerable, 6 | :recoverable, :rememberable, 7 | :validatable, :confirmable, :omniauthable 8 | include DeviseTokenAuth::Concerns::User 9 | end 10 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/unconfirmable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class UnconfirmableUser < ActiveRecord::Base 4 | # Include default devise modules. 5 | devise :database_authenticatable, :registerable, 6 | :recoverable, :rememberable, 7 | :validatable, :omniauthable 8 | include DeviseTokenAuth::Concerns::User 9 | end 10 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/unregisterable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class UnregisterableUser < ActiveRecord::Base 4 | # Include default devise modules. 5 | devise :database_authenticatable, :recoverable, 6 | :validatable, :confirmable, 7 | :omniauthable 8 | include DeviseTokenAuth::Concerns::User 9 | end 10 | -------------------------------------------------------------------------------- /test/dummy/app/active_record/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User < ActiveRecord::Base 4 | include DeviseTokenAuth::Concerns::User 5 | include FavoriteColor 6 | end 7 | -------------------------------------------------------------------------------- /test/dummy/app/assets/images/logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lynndylanhurley/devise_token_auth/74ec935c6b2a6edb2c0c44317abfc6bc58632657/test/dummy/app/assets/images/logo.jpg -------------------------------------------------------------------------------- /test/dummy/app/assets/images/omniauth-provider-settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lynndylanhurley/devise_token_auth/74ec935c6b2a6edb2c0c44317abfc6bc58632657/test/dummy/app/assets/images/omniauth-provider-settings.png -------------------------------------------------------------------------------- /test/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationController < ActionController::Base 4 | include DeviseTokenAuth::Concerns::SetUserByToken 5 | 6 | before_action :configure_permitted_parameters, if: :devise_controller? 7 | 8 | protected 9 | 10 | def configure_permitted_parameters 11 | devise_parameter_sanitizer.permit(:sign_up, keys: [:operating_thetan, :favorite_color]) 12 | devise_parameter_sanitizer.permit(:account_update, keys: [:operating_thetan, :favorite_color, :current_password]) 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/auth_origin_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class AuthOriginController < ApplicationController 4 | def redirected 5 | head :ok 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/custom/confirmations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Custom::ConfirmationsController < DeviseTokenAuth::ConfirmationsController 4 | def show 5 | super do |resource| 6 | @show_block_called = true unless resource.nil? 7 | end 8 | end 9 | 10 | def show_block_called? 11 | @show_block_called == true 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/custom/omniauth_callbacks_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Custom::OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController 4 | def omniauth_success 5 | super do |resource| 6 | @omniauth_success_block_called = true unless resource.nil? 7 | end 8 | end 9 | 10 | def omniauth_success_block_called? 11 | @omniauth_success_block_called == true 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/custom/passwords_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Custom::PasswordsController < DeviseTokenAuth::PasswordsController 4 | def create 5 | super do |resource| 6 | @create_block_called = true unless resource.nil? 7 | end 8 | end 9 | 10 | def edit 11 | super do |resource| 12 | @edit_block_called = true unless resource.nil? 13 | end 14 | end 15 | 16 | def update 17 | super do |resource| 18 | @update_block_called = true unless resource.nil? 19 | end 20 | end 21 | 22 | def create_block_called? 23 | @create_block_called == true 24 | end 25 | 26 | def edit_block_called? 27 | @edit_block_called == true 28 | end 29 | 30 | def update_block_called? 31 | @update_block_called == true 32 | end 33 | 34 | protected 35 | 36 | def render_update_success 37 | render json: { custom: 'foo' } 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/custom/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Custom::RegistrationsController < DeviseTokenAuth::RegistrationsController 4 | def create 5 | super do |resource| 6 | @create_block_called = true 7 | end 8 | end 9 | 10 | def update 11 | super do |resource| 12 | @update_block_called = true unless resource.nil? 13 | end 14 | end 15 | 16 | def destroy 17 | super do |resource| 18 | @destroy_block_called = true unless resource.nil? 19 | end 20 | end 21 | 22 | def create_block_called? 23 | @create_block_called == true 24 | end 25 | 26 | def update_block_called? 27 | @update_block_called == true 28 | end 29 | 30 | def destroy_block_called? 31 | @destroy_block_called == true 32 | end 33 | 34 | protected 35 | 36 | def render_create_success 37 | render json: { custom: 'foo' } 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/custom/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Custom::SessionsController < DeviseTokenAuth::SessionsController 4 | def create 5 | super do |resource| 6 | @create_block_called = true unless resource.nil? 7 | end 8 | end 9 | 10 | def destroy 11 | super do |resource| 12 | @destroy_block_called = true unless resource.nil? 13 | end 14 | end 15 | 16 | def create_block_called? 17 | @create_block_called == true 18 | end 19 | 20 | def destroy_block_called? 21 | @destroy_block_called == true 22 | end 23 | 24 | protected 25 | 26 | def render_create_success 27 | render json: { custom: 'foo' } 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/custom/token_validations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Custom::TokenValidationsController < DeviseTokenAuth::TokenValidationsController 4 | def validate_token 5 | super do |resource| 6 | @validate_token_block_called = true unless resource.nil? 7 | end 8 | end 9 | 10 | def validate_token_block_called? 11 | @validate_token_block_called == true 12 | end 13 | 14 | protected 15 | 16 | def render_validate_token_success 17 | render json: { custom: 'foo' } 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/demo_group_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DemoGroupController < ApplicationController 4 | devise_token_auth_group :member, contains: [:user, :mang] 5 | before_action :authenticate_member! 6 | 7 | def members_only 8 | render json: { 9 | data: { 10 | message: "Welcome #{current_member.name}", 11 | user: current_member 12 | } 13 | }, status: 200 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/demo_mang_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DemoMangController < ApplicationController 4 | before_action :authenticate_mang! 5 | 6 | def members_only 7 | render json: { 8 | data: { 9 | message: "Welcome #{current_mang.name}", 10 | user: current_mang 11 | } 12 | }, status: 200 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/demo_user_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DemoUserController < ApplicationController 4 | before_action :authenticate_user! 5 | 6 | def members_only 7 | render json: { 8 | data: { 9 | message: "Welcome #{current_user.name}", 10 | user: current_user 11 | } 12 | }, status: 200 13 | end 14 | 15 | def members_only_remove_token 16 | u = User.find(current_user.id) 17 | u.tokens = {} 18 | u.save! 19 | 20 | render json: { 21 | data: { 22 | message: "Welcome #{current_user.name}", 23 | user: current_user 24 | } 25 | }, status: 200 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/overrides/confirmations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Overrides 4 | class ConfirmationsController < DeviseTokenAuth::ConfirmationsController 5 | def show 6 | @resource = resource_class.confirm_by_token(params[:confirmation_token]) 7 | 8 | if @resource && @resource.id 9 | token = @resource.create_token 10 | @resource.save! 11 | 12 | redirect_header_options = { 13 | account_confirmation_success: true, 14 | config: params[:config], 15 | override_proof: '(^^,)' 16 | } 17 | redirect_headers = build_redirect_headers(token.token, 18 | token.client, 19 | redirect_header_options) 20 | 21 | redirect_to(@resource.build_auth_url(params[:redirect_url], 22 | redirect_headers), 23 | redirect_options) 24 | else 25 | raise ActionController::RoutingError, 'Not Found' 26 | end 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/overrides/omniauth_callbacks_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Overrides 4 | class OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController 5 | DEFAULT_NICKNAME = 'stimpy'.freeze 6 | 7 | def assign_provider_attrs(user, auth_hash) 8 | user.assign_attributes( 9 | nickname: DEFAULT_NICKNAME, 10 | name: auth_hash['info']['name'], 11 | image: auth_hash['info']['image'], 12 | email: auth_hash['info']['email'] 13 | ) 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/overrides/passwords_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Overrides 4 | class PasswordsController < DeviseTokenAuth::PasswordsController 5 | OVERRIDE_PROOF = '(^^,)'.freeze 6 | 7 | # this is where users arrive after visiting the email confirmation link 8 | def edit 9 | @resource = resource_class.reset_password_by_token( 10 | reset_password_token: resource_params[:reset_password_token] 11 | ) 12 | 13 | if @resource && @resource.id 14 | token = @resource.create_token 15 | 16 | # ensure that user is confirmed 17 | @resource.skip_confirmation! unless @resource.confirmed_at 18 | 19 | @resource.save! 20 | 21 | redirect_header_options = { 22 | override_proof: OVERRIDE_PROOF, 23 | reset_password: true 24 | } 25 | redirect_headers = build_redirect_headers(token.token, 26 | token.client, 27 | redirect_header_options) 28 | redirect_to(@resource.build_auth_url(params[:redirect_url], 29 | redirect_headers), 30 | redirect_options) 31 | else 32 | raise ActionController::RoutingError, 'Not Found' 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/overrides/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Overrides 4 | class RegistrationsController < DeviseTokenAuth::RegistrationsController 5 | OVERRIDE_PROOF = '(^^,)'.freeze 6 | 7 | def update 8 | if @resource 9 | if @resource.update(account_update_params) 10 | render json: { 11 | status: 'success', 12 | data: @resource.as_json, 13 | override_proof: OVERRIDE_PROOF 14 | } 15 | else 16 | render json: { 17 | status: 'error', 18 | errors: @resource.errors 19 | }, status: 422 20 | end 21 | else 22 | render json: { 23 | status: 'error', 24 | errors: ['User not found.'] 25 | }, status: 404 26 | end 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/overrides/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Overrides 4 | class SessionsController < DeviseTokenAuth::SessionsController 5 | OVERRIDE_PROOF = '(^^,)'.freeze 6 | 7 | def create 8 | @resource = resource_class.dta_find_by(email: resource_params[:email]) 9 | 10 | if @resource && valid_params?(:email, resource_params[:email]) && @resource.valid_password?(resource_params[:password]) && @resource.confirmed? 11 | @token = @resource.create_token 12 | @resource.save 13 | 14 | render json: { 15 | data: @resource.as_json(except: %i[tokens created_at updated_at]), 16 | override_proof: OVERRIDE_PROOF 17 | } 18 | 19 | elsif @resource && (not @resource.confirmed?) 20 | render json: { 21 | success: false, 22 | errors: [ 23 | "A confirmation email was sent to your account at #{@resource.email}. "\ 24 | 'You must follow the instructions in the email before your account '\ 25 | 'can be activated' 26 | ] 27 | }, status: 401 28 | 29 | else 30 | render json: { 31 | errors: ['Invalid login credentials. Please try again.'] 32 | }, status: 401 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /test/dummy/app/controllers/overrides/token_validations_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Overrides 4 | class TokenValidationsController < DeviseTokenAuth::TokenValidationsController 5 | OVERRIDE_PROOF = '(^^,)'.freeze 6 | 7 | def validate_token 8 | # @resource will have been set by set_user_by_token concern 9 | if @resource 10 | render json: { 11 | success: true, 12 | data: @resource.as_json(except: %i[tokens created_at updated_at]), 13 | override_proof: OVERRIDE_PROOF 14 | } 15 | else 16 | render json: { 17 | success: false, 18 | errors: ['Invalid login credentials'] 19 | }, status: 401 20 | end 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /test/dummy/app/models/concerns/favorite_color.rb: -------------------------------------------------------------------------------- 1 | module FavoriteColor 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :operating_thetan, numericality: true, allow_nil: true 6 | validate :ensure_correct_favorite_color 7 | end 8 | 9 | def ensure_correct_favorite_color 10 | if favorite_color && (favorite_color != '') 11 | unless ApplicationHelper::COLOR_NAMES.any?{ |s| s.casecmp(favorite_color)==0 } 12 | matches = ApplicationHelper::COLOR_SEARCH.search(favorite_color) 13 | closest_match = matches.last[:string] 14 | second_closest_match = matches[-2][:string] 15 | errors.add(:favorite_color, "We've never heard of the color \"#{favorite_color}\". Did you mean \"#{closest_match}\"? Or perhaps \"#{second_closest_match}\"?") 16 | end 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/confirmable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ConfirmableUser 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Recoverable 24 | field :reset_password_token, type: String 25 | field :reset_password_sent_at, type: Time 26 | field :reset_password_redirect_url, type: String 27 | field :allow_password_change, type: Boolean, default: false 28 | 29 | ## Rememberable 30 | field :remember_created_at, type: Time 31 | 32 | ## Confirmable 33 | field :confirmation_token, type: String 34 | field :confirmed_at, type: Time 35 | field :confirmation_sent_at, type: Time 36 | field :unconfirmed_email, type: String # Only if using reconfirmable 37 | 38 | ## Required 39 | field :provider, type: String 40 | field :uid, type: String, default: '' 41 | 42 | ## Tokens 43 | field :tokens, type: Hash, default: {} 44 | 45 | # Include default devise modules. 46 | devise :database_authenticatable, :registerable, 47 | :recoverable, :rememberable, :trackable, 48 | :validatable, :confirmable 49 | DeviseTokenAuth.send_confirmation_email = true 50 | include DeviseTokenAuth::Concerns::User 51 | DeviseTokenAuth.send_confirmation_email = false 52 | end 53 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/lockable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class LockableUser 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Lockable 24 | field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts 25 | field :unlock_token, type: String # Only if unlock strategy is :email or :both 26 | field :locked_at, type: Time 27 | 28 | ## Required 29 | field :provider, type: String 30 | field :uid, type: String, default: '' 31 | 32 | ## Tokens 33 | field :tokens, type: Hash, default: {} 34 | 35 | # Include default devise modules. 36 | devise :database_authenticatable, :registerable, :lockable 37 | include DeviseTokenAuth::Concerns::User 38 | end 39 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/mang.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Mang 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Recoverable 24 | field :reset_password_token, type: String 25 | field :reset_password_sent_at, type: Time 26 | field :reset_password_redirect_url, type: String 27 | field :allow_password_change, type: Boolean, default: false 28 | 29 | ## Rememberable 30 | field :remember_created_at, type: Time 31 | 32 | ## Confirmable 33 | field :confirmation_token, type: String 34 | field :confirmed_at, type: Time 35 | field :confirmation_sent_at, type: Time 36 | field :unconfirmed_email, type: String # Only if using reconfirmable 37 | 38 | ## Required 39 | field :provider, type: String 40 | field :uid, type: String, default: '' 41 | 42 | ## Tokens 43 | field :tokens, type: Hash, default: {} 44 | 45 | include DeviseTokenAuth::Concerns::User 46 | end 47 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/only_email_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class OnlyEmailUser 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Required 24 | field :provider, type: String 25 | field :uid, type: String, default: '' 26 | 27 | ## Tokens 28 | field :tokens, type: Hash, default: {} 29 | 30 | # Include default devise modules. 31 | devise :database_authenticatable, :registerable 32 | include DeviseTokenAuth::Concerns::User 33 | end 34 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/scoped_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ScopedUser 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Recoverable 24 | field :reset_password_token, type: String 25 | field :reset_password_sent_at, type: Time 26 | field :reset_password_redirect_url, type: String 27 | field :allow_password_change, type: Boolean, default: false 28 | 29 | ## Rememberable 30 | field :remember_created_at, type: Time 31 | 32 | ## Confirmable 33 | field :confirmation_token, type: String 34 | field :confirmed_at, type: Time 35 | field :confirmation_sent_at, type: Time 36 | field :unconfirmed_email, type: String # Only if using reconfirmable 37 | 38 | ## Required 39 | field :provider, type: String 40 | field :uid, type: String, default: '' 41 | 42 | ## Tokens 43 | field :tokens, type: Hash, default: {} 44 | 45 | # Include default devise modules. 46 | devise :database_authenticatable, :registerable, 47 | :recoverable, :rememberable, :trackable, 48 | :validatable, :confirmable, :omniauthable 49 | include DeviseTokenAuth::Concerns::User 50 | end 51 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/unconfirmable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class UnconfirmableUser 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Recoverable 24 | field :reset_password_token, type: String 25 | field :reset_password_sent_at, type: Time 26 | field :reset_password_redirect_url, type: String 27 | field :allow_password_change, type: Boolean, default: false 28 | 29 | ## Rememberable 30 | field :remember_created_at, type: Time 31 | 32 | ## Required 33 | field :provider, type: String 34 | field :uid, type: String, default: '' 35 | 36 | ## Tokens 37 | field :tokens, type: Hash, default: {} 38 | 39 | # Include default devise modules. 40 | devise :database_authenticatable, :registerable, 41 | :recoverable, :rememberable, :trackable, 42 | :validatable, :omniauthable 43 | include DeviseTokenAuth::Concerns::User 44 | end 45 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/unregisterable_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class UnregisterableUser 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | 19 | ## Database authenticatable 20 | field :email, type: String, default: '' 21 | field :encrypted_password, type: String, default: '' 22 | 23 | ## Recoverable 24 | field :reset_password_token, type: String 25 | field :reset_password_sent_at, type: Time 26 | field :reset_password_redirect_url, type: String 27 | field :allow_password_change, type: Boolean, default: false 28 | 29 | ## Confirmable 30 | field :confirmation_token, type: String 31 | field :confirmed_at, type: Time 32 | field :confirmation_sent_at, type: Time 33 | field :unconfirmed_email, type: String # Only if using reconfirmable 34 | 35 | ## Required 36 | field :provider, type: String 37 | field :uid, type: String, default: '' 38 | 39 | ## Tokens 40 | field :tokens, type: Hash, default: {} 41 | 42 | # Include default devise modules. 43 | devise :database_authenticatable, :recoverable, 44 | :trackable, :validatable, :confirmable, 45 | :omniauthable 46 | include DeviseTokenAuth::Concerns::User 47 | end 48 | -------------------------------------------------------------------------------- /test/dummy/app/mongoid/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User 4 | include Mongoid::Document 5 | include Mongoid::Timestamps 6 | include Mongoid::Locker 7 | 8 | field :locker_locked_at, type: Time 9 | field :locker_locked_until, type: Time 10 | 11 | locker locked_at_field: :locker_locked_at, 12 | locked_until_field: :locker_locked_until 13 | 14 | ## User Info 15 | field :name, type: String 16 | field :nickname, type: String 17 | field :image, type: String 18 | field :favorite_color, type: String 19 | field :operating_thetan, type: Integer 20 | 21 | ## Database authenticatable 22 | field :email, type: String, default: '' 23 | field :encrypted_password, type: String, default: '' 24 | 25 | ## Recoverable 26 | field :reset_password_token, type: String 27 | field :reset_password_sent_at, type: Time 28 | field :reset_password_redirect_url, type: String 29 | field :allow_password_change, type: Boolean, default: false 30 | 31 | ## Rememberable 32 | field :remember_created_at, type: Time 33 | 34 | ## Confirmable 35 | field :confirmation_token, type: String 36 | field :confirmed_at, type: Time 37 | field :confirmation_sent_at, type: Time 38 | field :unconfirmed_email, type: String # Only if using reconfirmable 39 | 40 | ## Required 41 | field :provider, type: String 42 | field :uid, type: String, default: '' 43 | 44 | ## Tokens 45 | field :tokens, type: Hash, default: {} 46 | 47 | include DeviseTokenAuth::Concerns::User 48 | include FavoriteColor 49 | end 50 | -------------------------------------------------------------------------------- /test/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | <%= csrf_meta_tags %> 6 | 7 | 8 | 9 | <%= yield %> 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /test/dummy/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 5 | load Gem.bin_path('bundler', 'bundle') 6 | -------------------------------------------------------------------------------- /test/dummy/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | begin 5 | load File.expand_path('spring', __dir__) 6 | rescue LoadError 7 | end 8 | APP_PATH = File.expand_path('../config/application', __dir__) 9 | require_relative '../config/boot' 10 | require 'rails/commands' 11 | -------------------------------------------------------------------------------- /test/dummy/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | begin 5 | load File.expand_path('spring', __dir__) 6 | rescue LoadError 7 | end 8 | require_relative '../config/boot' 9 | require 'rake' 10 | Rake.application.run 11 | -------------------------------------------------------------------------------- /test/dummy/bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # This file loads spring without using Bundler, in order to be fast 5 | # It gets overwritten when you run the `spring binstub` command 6 | 7 | unless defined?(Spring) 8 | require 'rubygems' 9 | require 'bundler' 10 | 11 | if match = Bundler.default_lockfile.read.match(/^GEM$.*?^ spring \((.*?)\)$.*?^$/m) 12 | ENV['GEM_PATH'] = ([Bundler.bundle_path.to_s] + Gem.path).join(File::PATH_SEPARATOR) 13 | ENV['GEM_HOME'] = '' 14 | Gem.paths = ENV 15 | 16 | gem 'spring', match[1] 17 | require 'spring/binstub' 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /test/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is used by Rack-based servers to start the application. 4 | 5 | require ::File.expand_path('../config/environment', __FILE__) 6 | run Rails.application 7 | 8 | # allow cross origin requests 9 | require 'rack/cors' 10 | use Rack::Cors do 11 | allow do 12 | origins '*' 13 | resource '*', 14 | headers: :any, 15 | expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], 16 | methods: %i[get post options delete put] 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /test/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require File.expand_path('boot', __dir__) 4 | 5 | require 'action_controller/railtie' 6 | require 'action_mailer/railtie' 7 | require 'rails/generators' 8 | require 'rack/cors' 9 | 10 | Bundler.require(*Rails.groups) 11 | 12 | begin 13 | case DEVISE_TOKEN_AUTH_ORM 14 | when :active_record 15 | require 'active_record/railtie' 16 | when :mongoid 17 | require 'mongoid' 18 | require 'mongoid-locker' 19 | end 20 | rescue LoadError 21 | end 22 | 23 | require 'devise_token_auth' 24 | 25 | module Dummy 26 | class Application < Rails::Application 27 | # Settings in config/environments/* take precedence over those specified here. 28 | # Application configuration should go into files in config/initializers 29 | # -- all .rb files in that directory are automatically loaded. 30 | 31 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 32 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 33 | # config.time_zone = 'Central Time (US & Canada)' 34 | 35 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 36 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 37 | # config.i18n.default_locale = :de 38 | config.autoload_paths << Rails.root.join('lib') 39 | config.autoload_paths += ["#{config.root}/app/#{DEVISE_TOKEN_AUTH_ORM}"] 40 | 41 | if DEVISE_TOKEN_AUTH_ORM == :mongoid 42 | Mongoid.configure do |config| 43 | config.load! Rails.root.join('./config/mongoid.yml') 44 | end 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /test/dummy/config/application.yml.bk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lynndylanhurley/devise_token_auth/74ec935c6b2a6edb2c0c44317abfc6bc58632657/test/dummy/config/application.yml.bk -------------------------------------------------------------------------------- /test/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | unless defined?(DEVISE_TOKEN_AUTH_ORM) 4 | DEVISE_TOKEN_AUTH_ORM = (ENV["DEVISE_TOKEN_AUTH_ORM"] || :active_record).to_sym 5 | end 6 | 7 | # Set up gems listed in the Gemfile. 8 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) 9 | 10 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 11 | $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) 12 | -------------------------------------------------------------------------------- /test/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | sqlite: &sqlite 2 | adapter: sqlite3 3 | database: db/<%= Rails.env %>.sqlite3 4 | 5 | mysql: &mysql 6 | adapter: mysql2 7 | username: root 8 | password: 9 | database: "devise_token_auth_<%= Rails.env %>" 10 | 11 | postgresql: &postgresql 12 | adapter: postgresql 13 | username: postgres 14 | password: postgres 15 | database: "devise_token_auth_<%= Rails.env %>" 16 | min_messages: ERROR 17 | 18 | defaults: &defaults 19 | pool: 5 20 | timeout: 5000 21 | host: 127.0.0.1 22 | <<: *<%= ENV['DB'] || "sqlite" %> 23 | 24 | development: 25 | <<: *defaults 26 | 27 | test: 28 | <<: *defaults 29 | 30 | production: 31 | <<: *defaults 32 | -------------------------------------------------------------------------------- /test/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Load the Rails application. 4 | require File.expand_path('application', __dir__) 5 | 6 | # Initialize the Rails application. 7 | Rails.application.initialize! 8 | -------------------------------------------------------------------------------- /test/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded on 7 | # every request. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports and disable caching. 15 | config.consider_all_requests_local = true 16 | config.action_controller.perform_caching = false 17 | 18 | # Don't care if the mailer can't send. 19 | config.action_mailer.raise_delivery_errors = true 20 | 21 | # use mailcatcher for development 22 | config.action_mailer.default_url_options = { host: 'devise-token-auth.dev' } 23 | config.action_mailer.delivery_method = :smtp 24 | config.action_mailer.smtp_settings = { address: 'localhost', port: 1025 } 25 | 26 | # Print deprecation notices to the Rails logger. 27 | config.active_support.deprecation = :log 28 | 29 | # Raise an error on page load if there are pending migrations. 30 | config.active_record.migration_error = :page_load 31 | 32 | # Raises error for missing translations 33 | # config.action_view.raise_on_missing_translations = true 34 | 35 | OmniAuth.config.full_host = 'http://devise-token-auth.dev' 36 | end 37 | -------------------------------------------------------------------------------- /test/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | config.action_controller.perform_caching = true 18 | 19 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 20 | # Add `rack-cache` to your Gemfile before enabling this. 21 | # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. 22 | # config.action_dispatch.rack_cache = true 23 | 24 | # Disable Rails's static asset server (Apache or nginx will already do this). 25 | config.serve_static_files = false 26 | 27 | # Specifies the header that your server uses for sending files. 28 | # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache 29 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx 30 | 31 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 32 | # config.force_ssl = true 33 | 34 | # Set to :debug to see everything in the log. 35 | config.log_level = :info 36 | 37 | # Prepend all log lines with the following tags. 38 | # config.log_tags = [ :subdomain, :uuid ] 39 | 40 | # Use a different logger for distributed setups. 41 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 42 | 43 | # Use a different cache store in production. 44 | # config.cache_store = :mem_cache_store 45 | 46 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 47 | # config.action_controller.asset_host = "http://assets.example.com" 48 | 49 | # Ignore bad email addresses and do not raise email delivery errors. 50 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 51 | # config.action_mailer.raise_delivery_errors = false 52 | 53 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 54 | # the I18n.default_locale when a translation cannot be found). 55 | config.i18n.fallbacks = true 56 | 57 | # Send deprecation notices to registered listeners. 58 | config.active_support.deprecation = :notify 59 | 60 | # Disable automatic flushing of the log to improve performance. 61 | # config.autoflush_log = false 62 | 63 | # Use default logging formatter so that PID and timestamp are not suppressed. 64 | config.log_formatter = ::Logger::Formatter.new 65 | 66 | # Do not dump schema after migrations. 67 | config.active_record.dump_schema_after_migration = false 68 | end 69 | -------------------------------------------------------------------------------- /test/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # The test environment is used exclusively to run your application's 7 | # test suite. You never need to work with it otherwise. Remember that 8 | # your test database is "scratch space" for the test suite and is wiped 9 | # and recreated between test runs. Don't rely on the data there! 10 | config.cache_classes = true 11 | 12 | # Do not eager load code on boot. This avoids loading your whole application 13 | # just for the purpose of running a single test. If you are using a tool that 14 | # preloads Rails for running tests, you may have to set it to true. 15 | config.eager_load = false 16 | 17 | # Configure static asset server for tests with Cache-Control for performance. 18 | Rails::VERSION::MAJOR >= 5 ? 19 | (config.public_file_server.enabled = true) : 20 | (config.serve_static_files = true) 21 | 22 | Rails::VERSION::MAJOR >= 5 ? 23 | (config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }) : 24 | (config.static_cache_control = 'public, max-age=3600') 25 | 26 | if Rails::VERSION::MAJOR < 7 && ENV['DEVISE_TOKEN_AUTH_ORM'] != 'mongoid' 27 | config.active_record.legacy_connection_handling = false 28 | end 29 | 30 | # Show full error reports and disable caching. 31 | config.consider_all_requests_local = true 32 | config.action_controller.perform_caching = false 33 | 34 | # Raise exceptions instead of rendering exception templates. 35 | if Rails::VERSION::MAJOR >= 7 && Rails::VERSION::MINOR > 0 36 | config.action_dispatch.show_exceptions = :none 37 | else 38 | config.action_dispatch.show_exceptions = false 39 | end 40 | 41 | # Disable request forgery protection in test environment. 42 | config.action_controller.allow_forgery_protection = false 43 | 44 | # Tell Action Mailer not to deliver emails to the real world. 45 | # The :test delivery method accumulates sent emails in the 46 | # ActionMailer::Base.deliveries array. 47 | config.action_mailer.delivery_method = :test 48 | config.action_mailer.default_url_options = { host: 'localhost' } 49 | 50 | # Print deprecation notices to the stderr. 51 | config.active_support.deprecation = :stderr 52 | 53 | # Raises error for missing translations 54 | # config.action_view.raise_on_missing_translations = true 55 | 56 | # randomize test order 57 | config.active_support.test_order = :random 58 | end 59 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 6 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 7 | 8 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 9 | # Rails.backtrace_cleaner.remove_silencers! 10 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | Rails.application.config.action_dispatch.cookies_serializer = :json 6 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/devise_token_auth.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | DeviseTokenAuth.setup do |config| 4 | # By default the authorization headers will change after each request. The 5 | # client is responsible for keeping track of the changing tokens. Change 6 | # this to false to prevent the Authorization header from changing after 7 | # each request. 8 | # config.change_headers_on_each_request = true 9 | 10 | # By default, users will need to re-authenticate after 2 weeks. This setting 11 | # determines how long tokens will remain valid after they are issued. 12 | # config.token_lifespan = 2.weeks 13 | 14 | # Limiting the token_cost to just 4 in testing will increase the performance of 15 | # your test suite dramatically. The possible cost value is within range from 4 16 | # to 31. It is recommended to not use a value more than 10 in other environments. 17 | config.token_cost = Rails.env.test? ? 4 : 10 18 | 19 | # Sets the max number of concurrent devices per user, which is 10 by default. 20 | # After this limit is reached, the oldest tokens will be removed. 21 | # config.max_number_of_devices = 10 22 | 23 | # Sometimes it's necessary to make several requests to the API at the same 24 | # time. In this case, each request in the batch will need to share the same 25 | # auth token. This setting determines how far apart the requests can be while 26 | # still using the same auth token. 27 | # config.batch_request_buffer_throttle = 5.seconds 28 | 29 | # This route will be the prefix for all oauth2 redirect callbacks. For 30 | # example, using the default '/omniauth', the github oauth2 provider will 31 | # redirect successful authentications to '/omniauth/github/callback' 32 | # config.omniauth_prefix = "/omniauth" 33 | 34 | # By default sending current password is not needed for the password update. 35 | # Uncomment to enforce current_password param to be checked before all 36 | # attribute updates. Set it to :password if you want it to be checked only if 37 | # password is updated. 38 | # config.check_current_password_before_update = :attributes 39 | 40 | # By default we will use callbacks for single omniauth. 41 | # It depends on fields like email, provider and uid. 42 | # config.default_callbacks = true 43 | 44 | # Makes it possible to change the headers names 45 | # config.headers_names = {:'access-token' => 'access-token', 46 | # :'client' => 'client', 47 | # :'expiry' => 'expiry', 48 | # :'uid' => 'uid', 49 | # :'token-type' => 'token-type' } 50 | 51 | # By default, only Bearer Token authentication is implemented out of the box. 52 | # If, however, you wish to integrate with legacy Devise authentication, you can 53 | # do so by enabling this flag. NOTE: This feature is highly experimental! 54 | # config.enable_standard_devise_support = false 55 | end 56 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/figaro.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | #Figaro.require("GITHUB_KEY", "GITHUB_SECRET", "FACEBOOK_KEY", "FACEBOOK_SECRET", "GOOGLE_KEY", "GOOGLE_SECRET", "APPLE_CLIENT_ID", "APPLE_TEAM_ID", "APPLE_KEY", "APPLE_PEM") 4 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Configure sensitive parameters which will be filtered from the log file. 6 | Rails.application.config.filter_parameters += [:password] 7 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Add new inflection rules using the following format. Inflections 6 | # are locale specific, and you may define rules for as many different 7 | # locales as you wish. All of these examples are active by default: 8 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 9 | # inflect.plural /^(ox)$/i, '\1en' 10 | # inflect.singular /^(ox)en/i, '\1' 11 | # inflect.irregular 'person', 'people' 12 | # inflect.uncountable %w( fish sheep ) 13 | # end 14 | 15 | # These inflection rules are supported but not enabled by default: 16 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 17 | # inflect.acronym 'RESTful' 18 | # end 19 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Add new mime types for use in respond_to blocks: 6 | # Mime::Type.register "text/richtext", :rtf 7 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/omniauth.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.config.middleware.use OmniAuth::Builder do |b| 4 | provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope: 'email,profile' 5 | provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'] 6 | provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'] 7 | provider :apple, ENV['APPLE_CLIENT_ID'], '', { scope: 'email name', team_id: ENV['APPLE_TEAM_ID'], key_id: ENV['APPLE_KEY'], pem: ENV['APPLE_PEM'] } 8 | provider :developer, 9 | fields: [:first_name, :last_name], 10 | uid_field: :last_name 11 | end 12 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | Rails.application.config.session_store :cookie_store, key: '_dummy_session' 6 | -------------------------------------------------------------------------------- /test/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # This file contains settings for ActionController::ParamsWrapper which 6 | # is enabled by default. 7 | 8 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 9 | ActiveSupport.on_load(:action_controller) do 10 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 11 | end 12 | 13 | # To enable root element in JSON for ActiveRecord objects. 14 | # ActiveSupport.on_load(:active_record) do 15 | # self.include_root_in_json = true 16 | # end 17 | -------------------------------------------------------------------------------- /test/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /test/dummy/config/mongoid.yml: -------------------------------------------------------------------------------- 1 | test: 2 | clients: 3 | default: 4 | database: devise_token_auth_test 5 | hosts: 6 | - localhost:27017 7 | options: 8 | read: 9 | mode: :primary 10 | max_pool_size: 1 11 | -------------------------------------------------------------------------------- /test/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | # when using multiple models, controllers will default to the first available 5 | # devise mapping. routes for subsequent devise mappings will need to defined 6 | # within a `devise_scope` block 7 | 8 | # define :users as the first devise mapping: 9 | mount_devise_token_auth_for 'User', at: 'auth' 10 | 11 | # define :mangs as the second devise mapping. routes using this class will 12 | # need to be defined within a devise_scope as shown below 13 | mount_devise_token_auth_for 'Mang', at: 'mangs' 14 | 15 | mount_devise_token_auth_for 'OnlyEmailUser', at: 'only_email_auth', skip: [:omniauth_callbacks] 16 | 17 | mount_devise_token_auth_for 'UnregisterableUser', at: 'unregisterable_user_auth', skip: [:registrations] 18 | 19 | mount_devise_token_auth_for 'UnconfirmableUser', at: 'unconfirmable_user_auth' 20 | 21 | mount_devise_token_auth_for 'LockableUser', at: 'lockable_user_auth' 22 | 23 | mount_devise_token_auth_for 'ConfirmableUser', at: 'confirmable_user_auth' 24 | 25 | # test namespacing 26 | namespace :api do 27 | scope :v1 do 28 | mount_devise_token_auth_for 'User', at: 'auth' 29 | end 30 | end 31 | 32 | # test namespacing with not created devise mapping 33 | namespace :api_v2, defaults: { format: :json } do 34 | mount_devise_token_auth_for 'ScopedUser', 35 | at: 'auth', 36 | controllers: { 37 | omniauth_callbacks: 'api_v2/omniauth_callbacks', 38 | sessions: 'api_v2/sessions', 39 | registrations: 'api_v2/registrations', 40 | confirmations: 'api_v2/confirmations', 41 | passwords: 'api_v2/passwords' 42 | } 43 | end 44 | 45 | # this route will authorize visitors using the User class 46 | get 'demo/members_only', to: 'demo_user#members_only' 47 | get 'demo/members_only_remove_token', to: 'demo_user#members_only_remove_token' 48 | 49 | # routes within this block will authorize visitors using the Mang class 50 | get 'demo/members_only_mang', to: 'demo_mang#members_only' 51 | 52 | # routes within this block will authorize visitors using the Mang or User class 53 | get 'demo/members_only_group', to: 'demo_group#members_only' 54 | 55 | # we need a route for omniauth_callback_controller to redirect to in sameWindow case 56 | get 'auth_origin', to: 'auth_origin#redirected' 57 | end 58 | -------------------------------------------------------------------------------- /test/dummy/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: 0bf8734819590884c2187d13a26dbda06f965098cf51c8fbdae0281364610b14dc8f487eeb5fd1410ccddc7de0b56e4a535f57a27a487606d1af8965cffd2fa5 15 | 16 | test: 17 | secret_key_base: 1e35bf6c80d7987805e9cdfd6957271312a3fe583d5cf8e51dc051b92f74eb7d299dbeba25e4f5d13cdc44d70922b9620d037800ddfaad05d72870b09be04c1f 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /test/dummy/config/spring.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Spring.application_root = './test/dummy' 4 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20140715061447_devise_token_auth_create_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:users) do |t| 8 | ## Database authenticatable 9 | t.string :email 10 | t.string :encrypted_password, null: false, default: '' 11 | 12 | ## Recoverable 13 | t.string :reset_password_token 14 | t.datetime :reset_password_sent_at 15 | t.string :reset_password_redirect_url 16 | t.boolean :allow_password_change, default: false 17 | 18 | ## Rememberable 19 | t.datetime :remember_created_at 20 | 21 | ## Confirmable 22 | t.string :confirmation_token 23 | t.datetime :confirmed_at 24 | t.datetime :confirmation_sent_at 25 | t.string :unconfirmed_email # Only if using reconfirmable 26 | 27 | ## Lockable 28 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 29 | # t.string :unlock_token # Only if unlock strategy is :email or :both 30 | # t.datetime :locked_at 31 | 32 | ## User Info 33 | t.string :name 34 | t.string :nickname 35 | t.string :image 36 | 37 | ## unique oauth id 38 | t.string :provider 39 | t.string :uid, null: false, default: '' 40 | 41 | ## Tokens 42 | if json_supported_database? 43 | t.json :tokens 44 | else 45 | t.text :tokens 46 | end 47 | 48 | t.timestamps 49 | end 50 | 51 | add_index :users, :email 52 | add_index :users, [:uid, :provider], unique: true 53 | add_index :users, :reset_password_token, unique: true 54 | add_index :users, :confirmation_token, unique: true 55 | add_index :users, :nickname, unique: true 56 | # add_index :users, :unlock_token, :unique => true 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20140715061805_devise_token_auth_create_mangs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateMangs < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:mangs) do |t| 8 | ## Database authenticatable 9 | t.string :email 10 | t.string :encrypted_password, null: false, default: '' 11 | 12 | ## Recoverable 13 | t.string :reset_password_token 14 | t.datetime :reset_password_sent_at 15 | t.string :reset_password_redirect_url 16 | t.boolean :allow_password_change, default: false 17 | 18 | ## Rememberable 19 | t.datetime :remember_created_at 20 | 21 | ## Confirmable 22 | t.string :confirmation_token 23 | t.datetime :confirmed_at 24 | t.datetime :confirmation_sent_at 25 | t.string :unconfirmed_email # Only if using reconfirmable 26 | 27 | ## Lockable 28 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 29 | # t.string :unlock_token # Only if unlock strategy is :email or :both 30 | # t.datetime :locked_at 31 | 32 | ## User Info 33 | t.string :name 34 | t.string :nickname 35 | t.string :image 36 | 37 | ## unique oauth id 38 | t.string :provider 39 | t.string :uid, null: false, default: '' 40 | 41 | ## Tokens 42 | if json_supported_database? 43 | t.json :tokens 44 | else 45 | t.text :tokens 46 | end 47 | 48 | t.timestamps 49 | end 50 | 51 | add_index :mangs, :email 52 | add_index :mangs, [:uid, :provider], unique: true 53 | add_index :mangs, :reset_password_token, unique: true 54 | add_index :mangs, :confirmation_token, unique: true 55 | # add_index :mangs, :unlock_token, :unique => true 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20140829044006_add_operating_thetan_to_user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class AddOperatingThetanToUser < ActiveRecord::Migration[4.2] 4 | def change 5 | add_column :users, :operating_thetan, :integer 6 | add_column :users, :favorite_color, :string 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20140916224624_add_favorite_color_to_mangs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class AddFavoriteColorToMangs < ActiveRecord::Migration[4.2] 4 | def change 5 | add_column :mangs, :favorite_color, :string 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20141222035835_devise_token_auth_create_only_email_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateOnlyEmailUsers < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:only_email_users) do |t| 8 | ## Required 9 | t.string :provider, null: false 10 | t.string :uid, null: false, default: '' 11 | 12 | ## Database authenticatable 13 | t.string :encrypted_password, null: false, default: '' 14 | 15 | ## Recoverable 16 | #t.string :reset_password_token 17 | #t.datetime :reset_password_sent_at 18 | 19 | ## Rememberable 20 | #t.datetime :remember_created_at 21 | 22 | ## Confirmable 23 | #t.string :confirmation_token 24 | #t.datetime :confirmed_at 25 | #t.datetime :confirmation_sent_at 26 | #t.string :unconfirmed_email # Only if using reconfirmable 27 | 28 | ## Lockable 29 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 30 | # t.string :unlock_token # Only if unlock strategy is :email or :both 31 | # t.datetime :locked_at 32 | 33 | ## User Info 34 | t.string :name 35 | t.string :nickname 36 | t.string :image 37 | t.string :email 38 | 39 | ## Tokens 40 | if json_supported_database? 41 | t.json :tokens 42 | else 43 | t.text :tokens 44 | end 45 | 46 | t.timestamps 47 | end 48 | 49 | add_index :only_email_users, :email 50 | add_index :only_email_users, [:uid, :provider], unique: true 51 | #add_index :only_email_users, :reset_password_token, :unique => true 52 | # add_index :only_email_users, :confirmation_token, :unique => true 53 | # add_index :only_email_users, :unlock_token, :unique => true 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20141222053502_devise_token_auth_create_unregisterable_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateUnregisterableUsers < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:unregisterable_users) do |t| 8 | ## Required 9 | t.string :provider, null: false 10 | t.string :uid, null: false, default: '' 11 | 12 | ## Database authenticatable 13 | t.string :encrypted_password, null: false, default: '' 14 | 15 | ## Recoverable 16 | t.string :reset_password_token 17 | t.datetime :reset_password_sent_at 18 | t.boolean :allow_password_change, default: false 19 | 20 | ## Rememberable 21 | t.datetime :remember_created_at 22 | 23 | ## Confirmable 24 | t.string :confirmation_token 25 | t.datetime :confirmed_at 26 | t.datetime :confirmation_sent_at 27 | t.string :unconfirmed_email # Only if using reconfirmable 28 | 29 | ## Lockable 30 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 31 | # t.string :unlock_token # Only if unlock strategy is :email or :both 32 | # t.datetime :locked_at 33 | 34 | ## User Info 35 | t.string :name 36 | t.string :nickname 37 | t.string :image 38 | t.string :email 39 | 40 | ## Tokens 41 | if json_supported_database? 42 | t.json :tokens 43 | else 44 | t.text :tokens 45 | end 46 | 47 | t.timestamps 48 | end 49 | 50 | add_index :unregisterable_users, :email 51 | add_index :unregisterable_users, [:uid, :provider], unique: true 52 | add_index :unregisterable_users, :reset_password_token, unique: true 53 | # add_index :unregisterable_users, :confirmation_token, :unique => true 54 | # add_index :unregisterable_users, :unlock_token, :unique => true 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20150708104536_devise_token_auth_create_unconfirmable_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateUnconfirmableUsers < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:unconfirmable_users) do |t| 8 | ## Required 9 | t.string :provider, null: false 10 | t.string :uid, null: false, default: '' 11 | 12 | ## Database authenticatable 13 | t.string :encrypted_password, null: false, default: '' 14 | 15 | ## Recoverable 16 | t.string :reset_password_token 17 | t.datetime :reset_password_sent_at 18 | t.boolean :allow_password_change, default: false 19 | 20 | ## Rememberable 21 | t.datetime :remember_created_at 22 | 23 | ## Confirmable 24 | # t.string :confirmation_token 25 | # t.datetime :confirmed_at 26 | # t.datetime :confirmation_sent_at 27 | # t.string :unconfirmed_email # Only if using reconfirmable 28 | 29 | ## Lockable 30 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 31 | # t.string :unlock_token # Only if unlock strategy is :email or :both 32 | # t.datetime :locked_at 33 | 34 | ## User Info 35 | t.string :name 36 | t.string :nickname 37 | t.string :image 38 | t.string :email 39 | 40 | ## Tokens 41 | if json_supported_database? 42 | t.json :tokens 43 | else 44 | t.text :tokens 45 | end 46 | 47 | t.timestamps 48 | end 49 | 50 | add_index :unconfirmable_users, :email 51 | add_index :unconfirmable_users, [:uid, :provider], unique: true 52 | add_index :unconfirmable_users, :reset_password_token, unique: true 53 | # add_index :nice_users, :confirmation_token, :unique => true 54 | # add_index :nice_users, :unlock_token, :unique => true 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20160103235141_devise_token_auth_create_scoped_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateScopedUsers < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:scoped_users) do |t| 8 | ## Required 9 | t.string :provider, null: false 10 | t.string :uid, null: false, default: '' 11 | 12 | ## Database authenticatable 13 | t.string :encrypted_password, null: false, default: '' 14 | 15 | ## Recoverable 16 | t.string :reset_password_token 17 | t.datetime :reset_password_sent_at 18 | t.boolean :allow_password_change, default: false 19 | 20 | ## Rememberable 21 | t.datetime :remember_created_at 22 | 23 | ## Confirmable 24 | t.string :confirmation_token 25 | t.datetime :confirmed_at 26 | t.datetime :confirmation_sent_at 27 | t.string :unconfirmed_email # Only if using reconfirmable 28 | 29 | ## Lockable 30 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 31 | # t.string :unlock_token # Only if unlock strategy is :email or :both 32 | # t.datetime :locked_at 33 | 34 | ## User Info 35 | t.string :name 36 | t.string :nickname 37 | t.string :image 38 | t.string :email 39 | 40 | ## Tokens 41 | if json_supported_database? 42 | t.json :tokens 43 | else 44 | t.text :tokens 45 | end 46 | 47 | t.timestamps 48 | end 49 | 50 | add_index :scoped_users, :email 51 | add_index :scoped_users, [:uid, :provider], unique: true 52 | add_index :scoped_users, :reset_password_token, unique: true 53 | # add_index :scoped_users, :confirmation_token, :unique => true 54 | # add_index :scoped_users, :unlock_token, :unique => true 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20160629184441_devise_token_auth_create_lockable_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | include MigrationDatabaseHelper 4 | 5 | class DeviseTokenAuthCreateLockableUsers < ActiveRecord::Migration[4.2] 6 | def change 7 | create_table(:lockable_users) do |t| 8 | ## Required 9 | t.string :provider, null: false 10 | t.string :uid, null: false, default: '' 11 | 12 | ## Database authenticatable 13 | t.string :encrypted_password, null: false, default: '' 14 | 15 | ## Recoverable 16 | # t.string :reset_password_token 17 | # t.datetime :reset_password_sent_at 18 | # t.boolean :allow_password_change, :default => false 19 | 20 | ## Rememberable 21 | # t.datetime :remember_created_at 22 | 23 | ## Confirmable 24 | # t.string :confirmation_token 25 | # t.datetime :confirmed_at 26 | # t.datetime :confirmation_sent_at 27 | # t.string :unconfirmed_email # Only if using reconfirmable 28 | 29 | ## Lockable 30 | t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 31 | t.string :unlock_token # Only if unlock strategy is :email or :both 32 | t.datetime :locked_at 33 | 34 | ## User Info 35 | t.string :name 36 | t.string :nickname 37 | t.string :image 38 | t.string :email 39 | 40 | ## Tokens 41 | if json_supported_database? 42 | t.json :tokens 43 | else 44 | t.text :tokens 45 | end 46 | 47 | t.timestamps 48 | end 49 | 50 | add_index :lockable_users, :email 51 | add_index :lockable_users, [:uid, :provider], unique: true 52 | # add_index :lockable_users, :reset_password_token, :unique => true 53 | # add_index :lockable_users, :confirmation_token, :unique => true 54 | add_index :lockable_users, :unlock_token, unique: true 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /test/dummy/db/migrate/20190924101113_devise_token_auth_create_confirmable_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseTokenAuthCreateConfirmableUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | 4 | create_table(:confirmable_users) do |t| 5 | ## Required 6 | t.string :provider, :null => false, :default => "email" 7 | t.string :uid, :null => false, :default => "" 8 | 9 | ## Database authenticatable 10 | t.string :encrypted_password, :null => false, :default => "" 11 | 12 | ## Recoverable 13 | t.string :reset_password_token 14 | t.datetime :reset_password_sent_at 15 | t.boolean :allow_password_change, :default => false 16 | 17 | ## Rememberable 18 | t.datetime :remember_created_at 19 | 20 | ## Confirmable 21 | t.string :confirmation_token 22 | t.datetime :confirmed_at 23 | t.datetime :confirmation_sent_at 24 | t.string :unconfirmed_email # Only if using reconfirmable 25 | 26 | ## Lockable 27 | # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 28 | # t.string :unlock_token # Only if unlock strategy is :email or :both 29 | # t.datetime :locked_at 30 | 31 | ## User Info 32 | t.string :name 33 | t.string :nickname 34 | t.string :image 35 | t.string :email 36 | 37 | ## Tokens 38 | t.text :tokens 39 | 40 | t.timestamps 41 | end 42 | 43 | add_index :confirmable_users, :email, unique: true 44 | add_index :confirmable_users, [:uid, :provider], unique: true 45 | add_index :confirmable_users, :reset_password_token, unique: true 46 | add_index :confirmable_users, :confirmation_token, unique: true 47 | # add_index :confirmable_users, :unlock_token, unique: true 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /test/dummy/lib/migration_database_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # polyfill Rails >= 5 versioned migrations 4 | 5 | unless ActiveRecord::Migration.respond_to?(:[]) 6 | module ActiveRecord 7 | class Migration 8 | def self.[](_version) 9 | self 10 | end 11 | end 12 | end 13 | end 14 | 15 | module MigrationDatabaseHelper 16 | def json_supported_database? 17 | (postgres? && postgres_correct_version?) || (mysql? && mysql_correct_version?) 18 | end 19 | 20 | def postgres? 21 | database_name == 'ActiveRecord::ConnectionAdapters::PostgreSQLAdapter' 22 | end 23 | 24 | def postgres_correct_version? 25 | database_version > '9.3' 26 | end 27 | 28 | def mysql? 29 | database_name == 'ActiveRecord::ConnectionAdapters::MysqlAdapter' 30 | end 31 | 32 | def mysql_correct_version? 33 | database_version > '5.7.7' 34 | end 35 | 36 | def database_name 37 | ActiveRecord::Base.connection.class.name 38 | end 39 | 40 | def database_version 41 | ActiveRecord::Base.connection.select_value('SELECT VERSION()') 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /test/dummy/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /test/dummy/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /test/dummy/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /test/dummy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lynndylanhurley/devise_token_auth/74ec935c6b2a6edb2c0c44317abfc6bc58632657/test/dummy/public/favicon.ico -------------------------------------------------------------------------------- /test/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | email { Faker::Internet.unique.email } 4 | password { Faker::Internet.password } 5 | provider { 'email' } 6 | 7 | transient do 8 | allow_unconfirmed_period { Time.now.utc - Devise.allow_unconfirmed_access_for } 9 | end 10 | 11 | trait :with_nickname do 12 | nickname { Faker::Internet.username } 13 | end 14 | 15 | trait :confirmed do 16 | after(:create) { |user| user.confirm } 17 | end 18 | 19 | # confirmation period is expired 20 | trait :unconfirmed do 21 | after(:create) do |user, evaluator| 22 | user.update_attribute(:confirmation_sent_at, evaluator.allow_unconfirmed_period - 1.day ) 23 | end 24 | end 25 | 26 | trait :facebook do 27 | uid { Faker::Number.number } 28 | provider { 'facebook' } 29 | end 30 | 31 | trait :locked do 32 | after(:create) { |user| user.lock_access! } 33 | end 34 | 35 | factory :lockable_user, class: 'LockableUser' 36 | factory :mang_user, class: 'Mang' 37 | factory :only_email_user, class: 'OnlyEmailUser' 38 | factory :scoped_user, class: 'ScopedUser' 39 | factory :confirmable_user, class: 'ConfirmableUser' 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /test/lib/devise_token_auth/blacklist_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class DeviseTokenAuth::BlacklistTest < ActiveSupport::TestCase 6 | if defined? Devise::Models::Authenticatable::UNSAFE_ATTRIBUTES_FOR_SERIALIZATION 7 | describe Devise::Models::Authenticatable::UNSAFE_ATTRIBUTES_FOR_SERIALIZATION do 8 | test 'should include :tokens' do 9 | assert Devise::Models::Authenticatable::UNSAFE_ATTRIBUTES_FOR_SERIALIZATION.include?(:tokens) 10 | end 11 | end 12 | else 13 | describe Devise::Models::Authenticatable::BLACKLIST_FOR_SERIALIZATION do 14 | test 'should include :tokens' do 15 | assert Devise::Models::Authenticatable::BLACKLIST_FOR_SERIALIZATION.include?(:tokens) 16 | end 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /test/lib/devise_token_auth/rails/custom_routes_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class DeviseTokenAuth::CustomRoutesTest < ActiveSupport::TestCase 6 | after do 7 | Rails.application.reload_routes! 8 | end 9 | test 'custom controllers' do 10 | class ActionDispatch::Routing::Mapper 11 | include Mocha::ParameterMatchers 12 | end 13 | Rails.application.routes.draw do 14 | self.expects(:devise_for).with( 15 | :users, 16 | has_entries( 17 | controllers: has_entries( 18 | invitations: "custom/invitations", foo: "custom/foo" 19 | ) 20 | ) 21 | ) 22 | 23 | mount_devise_token_auth_for 'User', at: 'my_custom_users', controllers: { 24 | invitations: 'custom/invitations', 25 | foo: 'custom/foo' 26 | } 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/lib/devise_token_auth/url_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class DeviseTokenAuth::UrlTest < ActiveSupport::TestCase 6 | describe 'DeviseTokenAuth::Url#generate' do 7 | test 'URI fragment should appear at the end of URL with repeat of query params' do 8 | params = { client_id: 123 } 9 | url = 'http://example.com#fragment' 10 | assert_equal DeviseTokenAuth::Url.send(:generate, url, params), 'http://example.com?client_id=123#fragment?client_id=123' 11 | end 12 | 13 | describe 'with existing query params' do 14 | test 'should preserve existing query params' do 15 | url = 'http://example.com?a=1' 16 | assert_equal DeviseTokenAuth::Url.send(:generate, url), 'http://example.com?a=1' 17 | end 18 | 19 | test 'should marge existing query params with new ones' do 20 | params = { client_id: 123 } 21 | url = 'http://example.com?a=1' 22 | assert_equal DeviseTokenAuth::Url.send(:generate, url, params), 'http://example.com?a=1&client_id=123' 23 | end 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /test/lib/generators/devise_token_auth/install_views_generator_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | require 'fileutils' 5 | require 'generators/devise_token_auth/install_views_generator' 6 | 7 | module DeviseTokenAuth 8 | class InstallViewsGeneratorTest < Rails::Generators::TestCase 9 | tests InstallViewsGenerator 10 | destination Rails.root.join('tmp/generators') 11 | 12 | describe 'default values, clean install' do 13 | setup :prepare_destination 14 | 15 | before do 16 | run_generator 17 | end 18 | 19 | test 'files are copied' do 20 | assert_file 'app/views/devise/mailer/reset_password_instructions.html.erb' 21 | assert_file 'app/views/devise/mailer/confirmation_instructions.html.erb' 22 | end 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /test/models/concerns/mongoid_support_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | if DEVISE_TOKEN_AUTH_ORM == :mongoid 6 | class DeviseTokenAuth::Concerns::MongoidSupportTest < ActiveSupport::TestCase 7 | describe DeviseTokenAuth::Concerns::MongoidSupport do 8 | before do 9 | @user = create(:user) 10 | end 11 | 12 | describe '#as_json' do 13 | test 'should be defined' do 14 | assert @user.methods.include?(:as_json) 15 | end 16 | 17 | test 'should except _id attribute' do 18 | refute @user.as_json.key?('_id') 19 | end 20 | 21 | test 'should return with id attribute' do 22 | assert_equal @user._id.to_s, @user.as_json['id'] 23 | end 24 | 25 | test 'should accept options' do 26 | refute @user.as_json(except: [:created_at]).key?('created_at') 27 | end 28 | end 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /test/models/concerns/tokens_serialization_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | if DEVISE_TOKEN_AUTH_ORM == :active_record 4 | describe 'DeviseTokenAuth::Concerns::TokensSerialization' do 5 | let(:ts) { DeviseTokenAuth::Concerns::TokensSerialization } 6 | let(:user) { FactoryBot.create(:user) } 7 | let(:tokens) do 8 | # Сreate all possible token's attributes combinations 9 | user.create_token 10 | 2.times { user.create_new_auth_token(user.tokens.first[0]) } 11 | user.create_new_auth_token 12 | user.create_token 13 | 14 | user.tokens 15 | end 16 | 17 | it 'is defined' do 18 | assert_equal(ts.present?, true) 19 | assert_kind_of(Module, ts) 20 | end 21 | 22 | describe '.load(json)' do 23 | 24 | let(:json) { JSON.generate(tokens) } 25 | 26 | let(:default) { {} } 27 | 28 | it 'is defined' do 29 | assert_respond_to(ts, :load) 30 | end 31 | 32 | it 'handles nil' do 33 | assert_equal(ts.load(nil), default) 34 | end 35 | 36 | it 'handles string' do 37 | assert_equal(ts.load(json), JSON.parse(json)) 38 | end 39 | 40 | it 'returns object of undesirable class' do 41 | assert_equal(ts.load([]), []) 42 | end 43 | end 44 | 45 | describe '.dump(object)' do 46 | let(:default) { 'null' } 47 | 48 | it 'is defined' do 49 | assert_respond_to(ts, :dump) 50 | end 51 | 52 | it 'handles nil' do 53 | assert_equal(ts.dump(nil), default) 54 | end 55 | 56 | it 'handles empty hash' do 57 | assert_equal(ts.dump({}), '{}') 58 | end 59 | 60 | it 'removes nil values' do 61 | new_tokens = tokens.dup 62 | new_tokens[new_tokens.first[0]][:kos] = nil 63 | 64 | assert_equal(ts.dump(tokens), ts.dump(new_tokens)) 65 | end 66 | 67 | describe 'updated_at' do 68 | before do 69 | @default_format = ::Time::DATE_FORMATS[:default] 70 | ::Time::DATE_FORMATS[:default] = 'imprecise format' 71 | end 72 | 73 | after do 74 | ::Time::DATE_FORMATS[:default] = @default_format 75 | end 76 | 77 | def updated_ats(tokens) 78 | tokens. 79 | values. 80 | flat_map do |token| 81 | [:updated_at, 'updated_at'].map do |key| 82 | token[key] 83 | end 84 | end. 85 | compact 86 | end 87 | 88 | it 'is defined' do 89 | refute_empty updated_ats(tokens) 90 | end 91 | 92 | it 'uses iso8601' do 93 | updated_ats(JSON.parse(ts.dump(tokens))).each do |updated_at| 94 | Time.strptime(updated_at, '%Y-%m-%dT%H:%M:%SZ') 95 | end 96 | end 97 | 98 | it 'does not rely on Time#to_s' do 99 | refute_includes(updated_ats(tokens), 'imprecise format') 100 | end 101 | end 102 | end 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /test/models/confirmable_user_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class ConfirmableUserTest < ActiveSupport::TestCase 6 | describe ConfirmableUser do 7 | describe 'creation' do 8 | test 'email should be saved' do 9 | @resource = create(:confirmable_user) 10 | assert @resource.email.present? 11 | end 12 | end 13 | 14 | describe 'updating email' do 15 | test 'new email should be saved to unconfirmed_email' do 16 | @resource = create(:confirmable_user, email: 'old_address@example.com') 17 | @resource.update(email: 'new_address@example.com') 18 | assert @resource.unconfirmed_email == 'new_address@example.com' 19 | end 20 | 21 | test 'old email should be kept in email' do 22 | @resource = create(:confirmable_user, email: 'old_address@example.com') 23 | @resource.update(email: 'new_address@example.com') 24 | assert @resource.email == 'old_address@example.com' 25 | end 26 | 27 | test 'confirmation_token should be changed' do 28 | @resource = create(:confirmable_user, email: 'old_address@example.com') 29 | old_token = @resource.confirmation_token 30 | @resource.update(email: 'new_address@example.com') 31 | assert @resource.confirmation_token != old_token 32 | end 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /test/models/only_email_user_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'test_helper' 4 | 5 | class OnlyEmailUserTest < ActiveSupport::TestCase 6 | describe OnlyEmailUser do 7 | test 'confirmable is disabled' do 8 | refute OnlyEmailUser.method_defined?(:confirmation_token) 9 | refute OnlyEmailUser.method_defined?(:confirmed_at) 10 | refute OnlyEmailUser.method_defined?(:confirmation_sent_at) 11 | refute OnlyEmailUser.method_defined?(:unconfirmed_email) 12 | end 13 | 14 | test 'lockable is disabled' do 15 | refute OnlyEmailUser.method_defined?(:failed_attempts) 16 | refute OnlyEmailUser.method_defined?(:unlock_token) 17 | refute OnlyEmailUser.method_defined?(:locked_at) 18 | end 19 | 20 | test 'recoverable is disabled' do 21 | refute OnlyEmailUser.method_defined?(:reset_password_token) 22 | refute OnlyEmailUser.method_defined?(:reset_password_sent_at) 23 | end 24 | 25 | test 'rememberable is disabled' do 26 | refute OnlyEmailUser.method_defined?(:remember_created_at) 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/support/controllers/routes.rb: -------------------------------------------------------------------------------- 1 | class Module 2 | include Minitest::Spec::DSL 3 | end 4 | 5 | module ControllerRoutesAfterBlock 6 | after do 7 | Rails.application.reload_routes! 8 | end 9 | end 10 | 11 | module CustomControllersRoutes 12 | include ControllerRoutesAfterBlock 13 | 14 | before do 15 | Rails.application.routes.draw do 16 | mount_devise_token_auth_for 'User', at: 'nice_user_auth', controllers: { 17 | registrations: 'custom/registrations', 18 | confirmations: 'custom/confirmations', 19 | passwords: 'custom/passwords', 20 | sessions: 'custom/sessions', 21 | token_validations: 'custom/token_validations', 22 | omniauth_callbacks: 'custom/omniauth_callbacks' 23 | } 24 | end 25 | end 26 | end 27 | 28 | module OverridesControllersRoutes 29 | include ControllerRoutesAfterBlock 30 | 31 | before do 32 | Rails.application.routes.draw do 33 | mount_devise_token_auth_for 'User', at: 'evil_user_auth', controllers: { 34 | confirmations: 'overrides/confirmations', 35 | passwords: 'overrides/passwords', 36 | omniauth_callbacks: 'overrides/omniauth_callbacks', 37 | registrations: 'overrides/registrations', 38 | sessions: 'overrides/sessions', 39 | token_validations: 'overrides/token_validations' 40 | } 41 | end 42 | end 43 | end 44 | --------------------------------------------------------------------------------