lynndylanhurley / devise_token_auth

Token based authentication for Rails JSON APIs. Designed to work with jToker and ng-token-auth.
Do What The F*ck You Want To Public License
3.52k stars 1.14k forks source link

NoMethodError (undefined method `dta_find_by' #1286

Open tomkaos opened 5 years ago

tomkaos commented 5 years ago

I am getting this error on /auth/sign_in route.

Do you have any idea why i get this one?

Thanks.

Tamas

Completed 500 Internal Server Error in 14ms (ActiveRecord: 0.0ms | Allocations: 4174)

NoMethodError (undefined method `dta_find_by' for #):

activerecord (6.0.0.rc1) lib/active_record/dynamic_matchers.rb:22:in method_missing' devise_token_auth (1.1.0) app/controllers/devise_token_auth/concerns/resource_finder.rb:27:infind_resource' devise_token_auth (1.1.0) app/controllers/devise_token_auth/sessions_controller.rb:21:in create' actionpack (6.0.0.rc1) lib/action_controller/metal/basic_implicit_render.rb:6:insend_action' actionpack (6.0.0.rc1) lib/abstract_controller/base.rb:196:in process_action' actionpack (6.0.0.rc1) lib/action_controller/metal/rendering.rb:30:inprocess_action' actionpack (6.0.0.rc1) lib/abstract_controller/callbacks.rb:42:in block in process_action' activesupport (6.0.0.rc1) lib/active_support/callbacks.rb:135:inrun_callbacks' actionpack (6.0.0.rc1) lib/abstract_controller/callbacks.rb:41:in process_action' actionpack (6.0.0.rc1) lib/action_controller/metal/rescue.rb:22:inprocess_action' actionpack (6.0.0.rc1) lib/action_controller/metal/instrumentation.rb:33:in block in process_action' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:180:inblock in instrument' activesupport (6.0.0.rc1) lib/active_support/notifications/instrumenter.rb:24:in instrument' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:180:ininstrument' actionpack (6.0.0.rc1) lib/action_controller/metal/instrumentation.rb:32:in process_action' actionpack (6.0.0.rc1) lib/action_controller/metal/params_wrapper.rb:245:inprocess_action' activerecord (6.0.0.rc1) lib/active_record/railties/controller_runtime.rb:27:in process_action' actionpack (6.0.0.rc1) lib/abstract_controller/base.rb:136:inprocess' actionpack (6.0.0.rc1) lib/action_controller/metal.rb:191:in dispatch' actionpack (6.0.0.rc1) lib/action_controller/metal.rb:252:indispatch' actionpack (6.0.0.rc1) lib/action_dispatch/routing/route_set.rb:51:in dispatch' actionpack (6.0.0.rc1) lib/action_dispatch/routing/route_set.rb:33:inserve' actionpack (6.0.0.rc1) lib/action_dispatch/routing/mapper.rb:18:in block in <class:Constraints>' actionpack (6.0.0.rc1) lib/action_dispatch/routing/mapper.rb:48:inserve' actionpack (6.0.0.rc1) lib/action_dispatch/journey/router.rb:49:in block in serve' actionpack (6.0.0.rc1) lib/action_dispatch/journey/router.rb:32:ineach' actionpack (6.0.0.rc1) lib/action_dispatch/journey/router.rb:32:in serve' actionpack (6.0.0.rc1) lib/action_dispatch/routing/route_set.rb:837:incall' warden (1.2.8) lib/warden/manager.rb:36:in block in call' warden (1.2.8) lib/warden/manager.rb:34:incatch' warden (1.2.8) lib/warden/manager.rb:34:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' rack (2.0.7) lib/rack/etag.rb:25:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' rack (2.0.7) lib/rack/conditional_get.rb:38:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' rack (2.0.7) lib/rack/head.rb:12:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' activerecord (6.0.0.rc1) lib/active_record/migration.rb:567:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/callbacks.rb:27:in block in call' activesupport (6.0.0.rc1) lib/active_support/callbacks.rb:101:inrun_callbacks' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/callbacks.rb:26:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/executor.rb:14:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/debug_exceptions.rb:32:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/show_exceptions.rb:33:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:inblock in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:in instrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:incall' railties (6.0.0.rc1) lib/rails/rack/logger.rb:38:in call_app' railties (6.0.0.rc1) lib/rails/rack/logger.rb:26:inblock in call' activesupport (6.0.0.rc1) lib/active_support/tagged_logging.rb:80:in block in tagged' activesupport (6.0.0.rc1) lib/active_support/tagged_logging.rb:28:intagged' activesupport (6.0.0.rc1) lib/active_support/tagged_logging.rb:80:in tagged' railties (6.0.0.rc1) lib/rails/rack/logger.rb:26:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/remote_ip.rb:81:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/request_id.rb:27:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' rack (2.0.7) lib/rack/runtime.rb:22:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' activesupport (6.0.0.rc1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/executor.rb:14:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/static.rb:126:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' rack (2.0.7) lib/rack/sendfile.rb:111:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/host_authorization.rb:83:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' rack-cors (1.0.3) lib/rack/cors.rb:95:incall' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:57:in block in call' activesupport (6.0.0.rc1) lib/active_support/notifications.rb:182:ininstrument' actionpack (6.0.0.rc1) lib/action_dispatch/middleware/stack.rb:56:in call' railties (6.0.0.rc1) lib/rails/engine.rb:526:incall' puma (3.12.1) lib/puma/configuration.rb:227:in call' puma (3.12.1) lib/puma/server.rb:660:inhandle_request' puma (3.12.1) lib/puma/server.rb:474:in process_client' puma (3.12.1) lib/puma/server.rb:334:inblock in run' puma (3.12.1) lib/puma/thread_pool.rb:135:in `block in spawn_thread'

dks17 commented 5 years ago

Hello. You need generate Devise config file with

rails generate devise:install

And specify orm you want to use in devise config file.

If you don not have that task you need declare devise gem explicitly in Gemfile.

Jellyfishboy commented 5 years ago

Hey @dks17 @tomkaos

I am also receiving this error:

undefined method 'dta_find_by' for #<Class:0x0000000006a805b0>

I have devise.rb already set up and the ORM is set to devise/orm/active_record

I have been using this setup for over 2 years now but suddenly today this error started popping up.

Devise token auth v1.1.0 Devise v4.6.2 Ruby v2.4.4

Any ideas?

Thanks

Jellyfishboy commented 5 years ago

Hey @dks17 @tomkaos,

My master branch was still working without that error. I rolled back to devise_token_auth 0.1.43 and devise 4.4.3 which resulted in the error disappearing.

Not sure why this has suddenly happened?

Regards

Jellyfishboy commented 5 years ago

Hey @dks17 @tomkaos

I can confirm it was due to a gem version change in my instance.

Last night/this early morning at 1:15am:

Using devise 4.4.3
Using rails 5.2.0
Using devise_token_auth 0.1.43

This morning at 11:44am:

Installing devise 4.6.2
Fetching devise_token_auth 1.1.0
Installing devise_token_auth 1.1.0

I only started seeing the error this morning after my 11:44am deployment, so there must be an issue with those 2 gem versions.

Regards

dks17 commented 5 years ago

devise gem and devise_token_auth gem do not support rails 6+. You can found tests here.

dta_find_by was implemented only in the last version of the gem. Try to use rails 5.2 and the last version of the gem.

MaicolBen commented 5 years ago

@Jellyfishboy In 11:44am deployment, do you have rails 6?

asanger commented 5 years ago

Just want to confirm that I am also seeing this on Rails v5.2.2, Devise 4.6.1, and Devise Token Auth 1.1.0

Jellyfishboy commented 5 years ago

@MaicolBen I am using Rails 5.2.0

dks17 commented 5 years ago

So, please someone of @asanger or @Jellyfishboy provide here: Gemfile model/user.rb config/initializers/devise.rb config/initializers/devise_token_auth.rb

I will check your configuration.

To solve your issue right now, try this in your user.rb model:

include DeviseTokenAuth::Concerns::ActiveRecordSupport
include DeviseTokenAuth::Concerns::User
Jellyfishboy commented 5 years ago

@dks17 I will provide the details momentarily. In regards to resolving the issue, I just downgraded the gem versions and all working as expected.

Jellyfishboy commented 5 years ago
source 'https://rubygems.org'
ruby '2.4.4'

# Core
gem 'rails', '~> 5.2.0'
gem 'puma', '~> 3.0'
gem 'figaro'
gem 'minitest', '5.10.1'

# Database management
gem 'pg', '~> 0.18'
gem 'paper_trail'
gem 'scout_apm'

# Asset management
gem 'sass-rails', '~> 5.0'
gem 'compass-rails'
gem 'uglifier', '>= 1.3.0'
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'bootstrap-sass', '~> 3.3.6'
gem "font-awesome-rails"
gem 'simple_form'

group :development, :test do
  gem 'byebug', platform: :mri
  gem 'pry'
  gem 'pry-nav'
  gem 'pry-rails'
end

group :development do
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'better_errors'
  gem 'binding_of_caller'
  gem 'bullet'
  gem 'rack-mini-profiler'
  gem 'annotate'
  gem 'meta_request'
  gem 'thin'
end

group :test do
  gem 'rspec-rails'
  gem 'rspec-collection_matchers'
  gem "factory_bot_rails"
  gem 'capybara'
  gem 'capybara-screenshot'
  gem 'poltergeist'
  gem 'database_cleaner'
  gem 'shoulda-matchers', '2.8.0'
  gem 'email_spec'
  gem 'timecop'
  gem "json_matchers"
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

# Misc
gem 'rollbar'
gem 'faker'
gem 'friendly_id', '~> 5.1.0'
gem 'newrelic_rpm', '~> 3.15'
gem 'kaminari'

# Background processing
gem 'sidekiq'
gem 'sidekiq-failures'
gem 'sidekiq-status'
gem 'sinatra', require: nil

gem 'rack-timeout'

# Colour console
gem 'colorize'

# cache
gem 'dalli'

# Auth
gem 'devise'
gem 'devise_token_auth'

# Pagination
gem 'will_paginate', '~> 3.0.6'

# CORS
gem "rack-cors", :require => "rack/cors"

# Asset management
gem 'mini_magick'
gem 'carrierwave'
gem 'carrierwave-base64'
gem 'cloudinary'
gem 'aws-sdk', '~> 2'

# CMS
gem 'active-campaign-rails'
gem 'convertkit-ruby', git: 'https://github.com/HookOps/convertkit-ruby', require: 'convertkit'
gem 'drip-ruby', require: 'drip'

# tree hierarchy
gem 'ancestry'

# turbo counter column
gem 'counter_culture', '~> 1.0'

gem 'deep_cloneable', '~> 2.3.0'

gem 'searchkick'

gem "attr_encrypted", "~> 3.0.0"
gem 'gon'
gem 'money'
gem 'gibbon'
gem 'redis'
gem 'redis-namespace'

gem 'impressionist'

gem 'acts_as_list'

# short url generator
# gem 'httparty'
# gem 'kutt', git: 'https://github.com/launchii/kutt.rb'
Jellyfishboy commented 5 years ago
# == Schema Information
#
# Table name: users
#
#  id                         :uuid             not null, primary key
#  email                      :string           default(""), not null
#  name                       :string           default(""), not null
#  encrypted_password         :string           default(""), not null
#  reset_password_token       :string
#  reset_password_sent_at     :datetime
#  remember_created_at        :datetime
#  sign_in_count              :integer          default(0), not null
#  current_sign_in_at         :datetime
#  last_sign_in_at            :datetime
#  current_sign_in_ip         :inet
#  last_sign_in_ip            :inet
#  confirmation_token         :string
#  confirmed_at               :datetime
#  confirmation_sent_at       :datetime
#  unconfirmed_email          :string
#  failed_attempts            :integer          default(0), not null
#  unlock_token               :string
#  locked_at                  :datetime
#  created_at                 :datetime         not null
#  updated_at                 :datetime         not null
#  status                     :integer          default("active")
#  role                       :integer          default("customer")
#  provider                   :string           default("email"), not null
#  uid                        :string           default(""), not null
#  tokens                     :json
#  notes                      :text
#  unread_notifications_count :integer          default(0)
#  read_notifications_count   :integer          default(0)
#  session_id                 :string
#  account_setup_token        :string
#  account_setup_at           :datetime
#  account_setup_sent_at      :datetime
#  store_id                   :uuid
#  is_master_vendor           :boolean          default(FALSE), not null
#  downgrade                  :integer          default("disabled"), not null
#
# Indexes
#
#  index_users_on_account_setup_token   (account_setup_token) UNIQUE
#  index_users_on_confirmation_token    (confirmation_token) UNIQUE
#  index_users_on_reset_password_token  (reset_password_token) UNIQUE
#  index_users_on_uid_and_provider      (uid,provider) UNIQUE
#  index_users_on_unlock_token          (unlock_token) UNIQUE
#

class User < ApplicationRecord
    include HasConfirmableDevise
    include HasCustomDeviseValidations
    include CustomDeviseAuth
    include HasActiveCampaign
    include HasAdmins
    include HasFollowings
    include HasRandomUserData
    include HasUserAccountSetup
    include HasMasterSlaveVendor
    has_paper_trail

    devise :database_authenticatable, :registerable,
            :recoverable, :rememberable, :trackable,
            :confirmable, :timeoutable #, :omniauthable, :validatable

    belongs_to :store

    has_many :coupons,                                      dependent: :destroy
    has_many :reviews,                                      dependent: :restrict_with_exception
    has_many :notifications,                                dependent: :destroy
    has_many :email_integration_notifications,              class_name: 'EmailIntegrationNotification', dependent: :destroy
    has_many :vendor_notifications,                         class_name: 'VendorNotification', dependent: :destroy

    validates :email,                                       uniqueness: true, if: :active?
    validates :name,                                        presence: true
    validates :is_master_vendor,                            inclusion: { in: [true, false] }
    validates :session_id,                                  uniqueness: true, allow_nil: true

    before_save :assign_new_store,                          on: :create, if: :master_vendor?

    scope :search,                                          -> (query, page, per_page_count, limit_count) { where("lower(users.name) LIKE :search OR lower(users.email) LIKE :search", search: "%#{query}%").page(page).per_page(per_page_count) }
    scope :master_vendor,                                   -> { vendor.where(is_master_vendor: true) }

    enum status: [:active, :inactive]
    enum role: [:customer, :vendor, :admin]
    enum downgrade: [:disabled, :enabled], _prefix: true

    def unconfirmed_max_coupons?
        unconfirmed? && max_coupons?
    end

    def max_coupons?
        coupons.to_a.reject{|c| c.deal.try(:upsell?) }.count >= 1 ? true : false
    end

    def unconfirmed?
        !self.confirmed?
    end

    def has_assigned_coupons?
        coupons.empty? ? false : true
    end

    def current_deal_coupon deal
        deal.rocket_deal_discount? ? coupons.includes(:rocket_deal).where(rocket_deals: { id: deal.rocket_deal.id }).first : coupons.includes(:deal).where(deals: { id: deal.id }).first
    end

    def has_current_deal_coupon? deal
        current_deal_coupon(deal).present? ? true : false
    end

    def has_current_deal_review? deal_id
        reviews.where(deal_id: deal_id).present? ? true : false
    end

    def cached_store
        return nil unless store.present?
        store_cache = Rails.cache.read("stores_#{store.id}")
        if store_cache.nil?
            Rails.cache.write("stores_#{id}", store) 
            store_cache = Rails.cache.read("stores_#{id}")
        end
        store_cache
    end

    def store_free_plan?
        vendor? && store.present? && store.plan.present? && store.plan.free? ? true : false
    end

    private

    def assign_new_store
        return if store.present?
        store = Store.create
        self.store_id = store.id
    end
end
Jellyfishboy commented 5 years ago
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
  # The secret key used by Devise. Devise uses this key to generate
  # random tokens. Changing this key will render invalid all existing
  # confirmation, reset password and unlock tokens in the database.
  # Devise will use the `secret_key_base` as its `secret_key`
  # by default. You can change it below and use your own secret key.
  config.secret_key = ENV["DEVISE_SECRET_KEY"]

  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class
  # with default "from" parameter.
  config.mailer_sender = 'Launchii <hello@launchii.com>'

  # Configure the class responsible to send e-mails.
  # config.mailer = 'Devise::Mailer'
  config.mailer = "AuthBackgroundMailer"

  # Configure the parent class responsible to send e-mails.
  # config.parent_mailer = 'ActionMailer::Base'

  # ==> ORM configuration
  # Load and configure the ORM. Supports :active_record (default) and
  # :mongoid (bson_ext recommended) by default. Other ORMs may be
  # available as additional gems.
  require 'devise/orm/active_record'

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.
  # config.authentication_keys = [:email]

  # Configure parameters from the request object used for authentication. Each entry
  # given should be a request method and it will automatically be passed to the
  # find_for_authentication method and considered in your model lookup. For instance,
  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  # The same considerations mentioned for authentication_keys also apply to request_keys.
  # config.request_keys = []

  # Configure which authentication keys should be case-insensitive.
  # These keys will be downcased upon creating or modifying a user and when used
  # to authenticate or find a user. Default is :email.
  config.case_insensitive_keys = [:email]

  # Configure which authentication keys should have whitespace stripped.
  # These keys will have whitespace before and after removed upon creating or
  # modifying a user and when used to authenticate or find a user. Default is :email.
  config.strip_whitespace_keys = [:email]

  # Tell if authentication through request.params is enabled. True by default.
  # It can be set to an array that will enable params authentication only for the
  # given strategies, for example, `config.params_authenticatable = [:database]` will
  # enable it only for database (email + password) authentication.
  # config.params_authenticatable = true

  # Tell if authentication through HTTP Auth is enabled. False by default.
  # It can be set to an array that will enable http authentication only for the
  # given strategies, for example, `config.http_authenticatable = [:database]` will
  # enable it only for database authentication. The supported strategies are:
  # :database      = Support basic authentication with authentication key + password
  # config.http_authenticatable = false

  # If 401 status code should be returned for AJAX requests. True by default.
  # config.http_authenticatable_on_xhr = true

  # The realm used in Http Basic Authentication. 'Application' by default.
  # config.http_authentication_realm = 'Application'

  # It will change confirmation, password recovery and other workflows
  # to behave the same regardless if the e-mail provided was right or wrong.
  # Does not affect registerable.
  # config.paranoid = true

  # By default Devise will store the user in session. You can skip storage for
  # particular strategies by setting this option.
  # Notice that if you are skipping storage for all authentication paths, you
  # may want to disable generating routes to Devise's sessions controller by
  # passing skip: :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth]

  # By default, Devise cleans up the CSRF token on authentication to
  # avoid CSRF token fixation attacks. This means that, when using AJAX
  # requests for sign in and sign up, you need to get a new CSRF token
  # from the server. You can disable this option at your own risk.
  # config.clean_up_csrf_token_on_authentication = true

  # When false, Devise will not attempt to reload routes on eager load.
  # This can reduce the time taken to boot the app but if your application
  # requires the Devise mappings to be loaded during boot time the application
  # won't boot properly.
  # config.reload_routes = true

  # ==> Configuration for :database_authenticatable
  # For bcrypt, this is the cost for hashing the password and defaults to 11. If
  # using other algorithms, it sets how many times you want the password to be hashed.
  #
  # Limiting the stretches to just one in testing will increase the performance of
  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  # a value less than 10 in other environments. Note that, for bcrypt (the default
  # algorithm), the cost increases exponentially with the number of stretches (e.g.
  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
  config.stretches = Rails.env.test? ? 1 : 11

  # Set up a pepper to generate the hashed password.
  # config.pepper = '8bc18ae2a415823f17a02fd7512a7aa302140690a7e1b3272a5da7bb4f90f719394dc5a069be5ea7b64bcdda444246d0ce73077d50b560eec381eb8c439e837c'

  # Send a notification email when the user's password is changed
  # config.send_password_change_notification = false

  # ==> Configuration for :confirmable
  # A period that the user is allowed to access the website even without
  # confirming their account. For instance, if set to 2.days, the user will be
  # able to access the website for two days without confirming their account,
  # access will be blocked just in the third day. Default is 0.days, meaning
  # the user cannot access the website without confirming their account.
  config.allow_unconfirmed_access_for = 30.days

  # A period that the user is allowed to confirm their account before their
  # token becomes invalid. For example, if set to 3.days, the user can confirm
  # their account within 3 days after the mail was sent, but on the fourth day
  # their account can't be confirmed with the token any more.
  # Default is nil, meaning there is no restriction on how long a user can take
  # before confirming their account.
  # config.confirm_within = 3.days

  # If true, requires any email changes to be confirmed (exactly the same way as
  # initial account confirmation) to be applied. Requires additional unconfirmed_email
  # db field (see migrations). Until confirmed, new email is stored in
  # unconfirmed_email column, and copied to email column on successful confirmation.
  config.reconfirmable = true

  # Defines which key will be used when confirming an account
  # config.confirmation_keys = [:email]

  # ==> Configuration for :rememberable
  # The time the user will be remembered without asking for credentials again.
  # config.remember_for = 2.weeks

  # Invalidates all the remember me tokens when the user signs out.
  config.expire_all_remember_me_on_sign_out = true

  # If true, extends the user's remember period when remembered via cookie.
  # config.extend_remember_period = false

  # Options to be passed to the created cookie. For instance, you can set
  # secure: true in order to force SSL only cookies.
  # config.rememberable_options = {}

  # ==> Configuration for :validatable
  # Range for password length.
  config.password_length = 6..128

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  # config.timeout_in = 30.minutes

  # ==> Configuration for :lockable
  # Defines which strategy will be used to lock an account.
  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  # config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  # config.unlock_keys = [:email]

  # Defines which strategy will be used to unlock an account.
  # :email = Sends an unlock link to the user email
  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
  # :both  = Enables both strategies
  # :none  = No unlock strategy. You should handle unlocking by yourself.
  # config.unlock_strategy = :both

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # config.maximum_attempts = 20

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # config.unlock_in = 1.hour

  # Warn on the last attempt before the account is locked.
  # config.last_attempt_warning = true

  # ==> Configuration for :recoverable
  #
  # Defines which key will be used when recovering the password for an account
  # config.reset_password_keys = [:email]

  # Time interval you can reset your password with a reset password key.
  # Don't put a too small interval or your users won't have the time to
  # change their passwords.
  config.reset_password_within = 6.hours

  # When set to false, does not sign a user in automatically after their password is
  # reset. Defaults to true, so a user is signed in automatically after a reset.
  # config.sign_in_after_reset_password = true

  # ==> Configuration for :encryptable
  # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
  # You can use :sha1, :sha512 or algorithms from others authentication tools as
  # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
  # for default behavior) and :restful_authentication_sha1 (then you should set
  # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
  #
  # Require the `devise-encryptable` gem when using anything other than bcrypt
  # config.encryptor = :sha512

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  # config.scoped_views = false

  # Configure the default scope given to Warden. By default it's the first
  # devise role declared in your routes (usually :user).
  # config.default_scope = :user

  # Set this configuration to false if you want /users/sign_out to sign out
  # only the current scope. By default, Devise signs out all scopes.
  # config.sign_out_all_scopes = true

  # ==> Navigation configuration
  # Lists the formats that should be treated as navigational. Formats like
  # :html, should redirect to the sign in page when the user does not have
  # access, but formats like :xml or :json, should return 401.
  #
  # If you have any extra navigational formats, like :iphone or :mobile, you
  # should add them to the navigational formats lists.
  #
  # The "*/*" below is required to match Internet Explorer requests.
  # config.navigational_formats = ['*/*', :html]

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :delete

  # ==> OmniAuth
  # Add a new OmniAuth provider. Check the wiki for more information on setting
  # up on your models and hooks.
  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'

  # ==> Warden configuration
  # If you want to use other strategies, that are not supported by Devise, or
  # change the failure app, you can configure them inside the config.warden block.
  #
  # config.warden do |manager|
  #   manager.intercept_401 = false
  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
  # end

  # ==> Mountable engine configurations
  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  # is mountable, there are some extra configurations to be taken into account.
  # The following options are available, assuming the engine is mounted as:
  #
  #     mount MyEngine, at: '/my_engine'
  #
  # The router that invoked `devise_for`, in the example above, would be:
  # config.router_name = :my_engine
  #
  # When using OmniAuth, Devise cannot automatically set OmniAuth path,
  # so you need to do it manually. For the users scope, it would be:
  # config.omniauth_path_prefix = '/my_engine/users/auth'
end
Jellyfishboy commented 5 years ago
DeviseTokenAuth.setup do |config|
  # By default the authorization headers will change after each request. The
  # client is responsible for keeping track of the changing tokens. Change
  # this to false to prevent the Authorization header from changing after
  # each request.
  config.change_headers_on_each_request = false

  # By default, users will need to re-authenticate after 2 weeks. This setting
  # determines how long tokens will remain valid after they are issued.
  # config.token_lifespan = 2.weeks

  # Sets the max number of concurrent devices per user, which is 10 by default.
  # After this limit is reached, the oldest tokens will be removed.
  # config.max_number_of_devices = 10

  # Sometimes it's necessary to make several requests to the API at the same
  # time. In this case, each request in the batch will need to share the same
  # auth token. This setting determines how far apart the requests can be while
  # still using the same auth token.
  # config.batch_request_buffer_throttle = 5.seconds

  # This route will be the prefix for all oauth2 redirect callbacks. For
  # example, using the default '/omniauth', the github oauth2 provider will
  # redirect successful authentications to '/omniauth/github/callback'
  # config.omniauth_prefix = "/omniauth"

  # By default sending current password is not needed for the password update.
  # Uncomment to enforce current_password param to be checked before all
  # attribute updates. Set it to :password if you want it to be checked only if
  # password is updated.
  # config.check_current_password_before_update = :attributes

  # By default we will use callbacks for single omniauth.
  # It depends on fields like email, provider and uid.
  # config.default_callbacks = true

  # Makes it possible to change the headers names
  # config.headers_names = {:'access-token' => 'access-token',
  #                        :'client' => 'client',
  #                        :'expiry' => 'expiry',
  #                        :'uid' => 'uid',
  #                        :'token-type' => 'token-type' }

  # By default, only Bearer Token authentication is implemented out of the box.
  # If, however, you wish to integrate with legacy Devise authentication, you can
  # do so by enabling this flag. NOTE: This feature is highly experimental!
  # config.enable_standard_devise_support = false
end
dks17 commented 5 years ago

Thanks. You inherit ApplicationRecord for your User class.

class User < ApplicationRecord

And the gem expects ActiveRecord::Base

https://github.com/lynndylanhurley/devise_token_auth/blob/ce2cf2c180e6632dd054dd4b099e27f5a264de83/app/models/devise_token_auth/concerns/user.rb#L24-L26

I think here there is the issue for your application. I need time to check my guess.

dks17 commented 5 years ago

@Jellyfishboy I have checked my guess in console. And it is not confirmed.

I have:

class ApplicationRecord < ActiveRecord::Base
class User < ApplicationRecord
User.const_defined?('ActiveRecord') && User.ancestors.include?(ActiveRecord::Base)
=> true
Jellyfishboy commented 5 years ago

@dks17 ApplicationRecord in turn inherits from ActiveRecord::Base. No issue there.

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  scope :sort_by_created_at, -> {order(created_at: :desc)}
end
dks17 commented 5 years ago

@Jellyfishboy Do not see in you User model:

include DeviseTokenAuth::Concerns::User

Do you include this concern somewhere else?

Jellyfishboy commented 5 years ago

@dks17

Model concern included on my User model.

require 'bcrypt'

module CustomDeviseAuth
  extend ActiveSupport::Concern

  def self.tokens_match?(token_hash, token)
    @token_equality_cache ||= {}

    key = "#{token_hash}/#{token}"
    result = @token_equality_cache[key] ||= (::BCrypt::Password.new(token_hash) == token)
    if @token_equality_cache.size > 10000
      @token_equality_cache = {}
    end
    result
  end

  included do
    # Hack to check if devise is already enabled
    unless self.method_defined?(:devise_modules)
      devise :database_authenticatable, :registerable,
          :recoverable, :trackable, :confirmable #:validatable
    else
      self.devise_modules.delete(:omniauthable)
    end

    unless tokens_has_json_column_type?
      serialize :tokens, JSON
    end

    if DeviseTokenAuth.default_callbacks
      include DeviseTokenAuth::Concerns::UserOmniauthCallbacks
    end

    # can't set default on text fields in mysql, simulate here instead.
    after_save :set_empty_token_hash
    after_initialize :set_empty_token_hash

    # get rid of dead tokens
    before_save :destroy_expired_tokens

    # remove old tokens if password has changed
    before_save :remove_tokens_after_password_reset

    # allows user to change password without current_password
    attr_writer :allow_password_change
    def allow_password_change
      @allow_password_change || false
    end

    # don't use default devise email validation
    def email_required?
      false
    end

    def email_changed?
      false
    end

    # override devise method to include additional info as opts hash
    def send_confirmation_instructions(opts=nil)
      unless @raw_confirmation_token
        generate_confirmation_token!
      end

      opts ||= {}

      # fall back to "default" config name
      opts[:client_config] ||= "default"

      if pending_reconfirmation?
        opts[:to] = unconfirmed_email
      end
      opts[:redirect_url] ||= DeviseTokenAuth.default_confirm_success_url

      send_devise_notification(:confirmation_instructions, @raw_confirmation_token, opts)
    end

    # override devise method to include additional info as opts hash
    def send_reset_password_instructions(opts=nil)
      token = set_reset_password_token

      opts ||= {}

      # fall back to "default" config name
      opts[:client_config] ||= "default"

      send_devise_notification(:reset_password_instructions, token, opts)

      token
    end
  end

  module ClassMethods
    protected

    def tokens_has_json_column_type?
      database_exists? && table_exists? && self.columns_hash['tokens'] && self.columns_hash['tokens'].type.in?([:json, :jsonb])
    end

    def database_exists?
      ActiveRecord::Base.connection
    rescue ActiveRecord::NoDatabaseError
      false
    else
      true
    end
  end

  def valid_token?(token, client_id='default')
    client_id ||= 'default'

    return false unless self.tokens[client_id]

    return true if token_is_current?(token, client_id)
    return true if token_can_be_reused?(token, client_id)

    # return false if none of the above conditions are met
    return false
  end

  # this must be done from the controller so that additional params
  # can be passed on from the client
  def send_confirmation_notification?
    false
  end

  def token_is_current?(token, client_id)
    # ghetto HashWithIndifferentAccess
    expiry     = self.tokens[client_id]['expiry'] || self.tokens[client_id][:expiry]
    token_hash = self.tokens[client_id]['token'] || self.tokens[client_id][:token]

    return true if (
      # ensure that expiry and token are set
      expiry && token &&

      # ensure that the token has not yet expired
      DateTime.strptime(expiry.to_s, '%s') > Time.now &&

      # ensure that the token is valid
      DeviseTokenAuth::Concerns::User.tokens_match?(token_hash, token)
    )
  end

  # allow batch requests to use the previous token
  def token_can_be_reused?(token, client_id)
    # ghetto HashWithIndifferentAccess
    updated_at = self.tokens[client_id]['updated_at'] || self.tokens[client_id][:updated_at]
    last_token = self.tokens[client_id]['last_token'] || self.tokens[client_id][:last_token]

    return true if (
      # ensure that the last token and its creation time exist
      updated_at && last_token &&

      # ensure that previous token falls within the batch buffer throttle time of the last request
      Time.parse(updated_at) > Time.now - DeviseTokenAuth.batch_request_buffer_throttle &&

      # ensure that the token is valid
      ::BCrypt::Password.new(last_token) == token
    )
  end

  # update user's auth token (should happen on each request)
  def create_new_auth_token(client_id=nil)
    client_id  ||= SecureRandom.urlsafe_base64(nil, false)
    last_token ||= nil
    token        = SecureRandom.urlsafe_base64(nil, false)
    token_hash   = ::BCrypt::Password.create(token)
    expiry       = (Time.now + DeviseTokenAuth.token_lifespan).to_i

    if self.tokens[client_id] && self.tokens[client_id]['token']
      last_token = self.tokens[client_id]['token']
    end

    self.tokens[client_id] = {
      token:      token_hash,
      expiry:     expiry,
      last_token: last_token,
      updated_at: Time.now
    }

    return build_auth_header(token, client_id)
  end

  def build_auth_header(token, client_id='default')
    client_id ||= 'default'

    # client may use expiry to prevent validation request if expired
    # must be cast as string or headers will break
    expiry = self.tokens[client_id]['expiry'] || self.tokens[client_id][:expiry]

    max_clients = DeviseTokenAuth.max_number_of_devices
    while self.tokens.keys.length > 0 && max_clients < self.tokens.keys.length
      oldest_token = self.tokens.min_by { |cid, v| v[:expiry] || v["expiry"] }
      self.tokens.delete(oldest_token.first)
    end

    self.save!

    return {
      DeviseTokenAuth.headers_names[:"access-token"] => token,
      DeviseTokenAuth.headers_names[:"token-type"]   => "Bearer",
      DeviseTokenAuth.headers_names[:"client"]       => client_id,
      DeviseTokenAuth.headers_names[:"expiry"]       => expiry.to_s,
      DeviseTokenAuth.headers_names[:"uid"]          => self.uid
    }
  end

  def build_auth_url(base_url, args)
    args[:uid]    = self.uid
    args[:expiry] = self.tokens[args[:client_id]]['expiry']

    DeviseTokenAuth::Url.generate(base_url, args)
  end

  def extend_batch_buffer(token, client_id)
    self.tokens[client_id]['updated_at'] = Time.now

    return build_auth_header(token, client_id)
  end

  def confirmed?
    self.devise_modules.exclude?(:confirmable) || super
  end

  def token_validation_response
    self.as_json(except: [
      :tokens, :created_at, :updated_at
    ])
  end

  protected

  def set_empty_token_hash
    self.tokens ||= {} if has_attribute?(:tokens)
  end

  def destroy_expired_tokens
    if self.tokens
      self.tokens.delete_if do |cid, v|
        expiry = v[:expiry] || v["expiry"]
        DateTime.strptime(expiry.to_s, '%s') < Time.now
      end
    end
  end

  def remove_tokens_after_password_reset
    there_is_more_than_one_token = self.tokens && self.tokens.keys.length > 1
    should_remove_old_tokens = DeviseTokenAuth.remove_tokens_after_password_reset &&
                               encrypted_password_changed? && there_is_more_than_one_token

    if should_remove_old_tokens
      latest_token = self.tokens.max_by { |cid, v| v[:expiry] || v["expiry"] }
      self.tokens = { latest_token.first => latest_token.last }
    end
  end

end
dks17 commented 5 years ago

@Jellyfishboy Try to put in your CustomDeviseAuth


  included do
    # Hack to check if devise is already enabled
    unless self.method_defined?(:devise_modules)
      devise :database_authenticatable, :registerable,
          :recoverable, :trackable, :confirmable #:validatable
    else
      self.devise_modules.delete(:omniauthable)
    end

    => this
    include DeviseTokenAuth::Concerns::ActiveRecordSupport

    unless tokens_has_json_column_type?
      serialize :tokens, JSON
    end
``
dks17 commented 5 years ago

@Jellyfishboy What is custom in your CustomDeviseAuth? I think be better do something like this:

class User < ApplicationRecord
    include DeviseTokenAuth::Concerns::User
    include YouCustomMethodsHere

    # or put your custom methods right here.
end

Otherwise you never can follow the gem updates.

Jellyfishboy commented 5 years ago

@dks17 Honestly can't recall. I will update concern and change include ordering on the User model then revert back with outcome. Thanks!

experimatt commented 4 years ago

I haven't read through this full thread, but I had the exact same error when using devise_token_auth, paper_trail and active_admin together. Calling set_paper_trail_whodunnit within the ApplicationController was what caused the problem.

With ActiveAdmin, which uses regular devise under the hood, the admin_user.rb was an abstract class, whereas user.rb was not an abstract class. I was seeing the dta_find_by' for #Class:0x00007fd54e8eaf78 error on the admin user, which yielded a confusing stack trace because it was an abstract class.

It's been a long time, but I believe the solution was to move set_paper_trail_whodunnit out of the ApplicationController, to the ApiController, which is where DeviseTokenAuth was actually being used. (I also moved it to the active admin views, which was where they were being used for admin users)

Here's a snippet from my ApiController:

class ApiController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken

  before_action :set_paper_trail_whodunnit

  protected

  def user_for_paper_trail
    current_user&.id || 'Unknown User'
  end

  def info_for_paper_trail
    { whodunnit_type: current_user&.class&.name } if user_signed_in?
  end
end
SimonBrazell commented 4 years ago

@Jellyfishboy what version did you revert to that enabled this to work?

Having the same problem on an existing app that I'm trying to add this gem to.

Jellyfishboy commented 4 years ago

@SimonBrazell v1.1.3

SimonBrazell commented 4 years ago

Cheers! I'm beginning to think that my issue is unrelated but I'll give it a go.

pnghai commented 4 years ago

I haven't read through this full thread, but I had the exact same error when using devise_token_auth, paper_trail and active_admin together. Calling set_paper_trail_whodunnit within the ApplicationController was what caused the problem.

With ActiveAdmin, which uses regular devise under the hood, the admin_user.rb was an abstract class, whereas user.rb was not an abstract class. I was seeing the dta_find_by' for #Class:0x00007fd54e8eaf78 error on the admin user, which yielded a confusing stack trace because it was an abstract class.

It's been a long time, but I believe the solution was to move set_paper_trail_whodunnit out of the ApplicationController, to the ApiController, which is where DeviseTokenAuth was actually being used. (I also moved it to the active admin views, which was where they were being used for admin users)

Here's a snippet from my ApiController:

class ApiController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken

  before_action :set_paper_trail_whodunnit

  protected

  def user_for_paper_trail
    current_user&.id || 'Unknown User'
  end

  def info_for_paper_trail
    { whodunnit_type: current_user&.class&.name } if user_signed_in?
  end
end

Hi, how did you move the user_for_paper_trail callback into active_admin and separate from application_controller?

experimatt commented 4 years ago

@pnghai in an active admin model (e.g app/admin/books.rb):

ActiveAdmin.register Book do

...

  controller do
    before_action :set_paper_trail_whodunnit

    # manually set the user for paper trail, instead of in ApplicationController
    def user_for_paper_trail
      current_admin_user&.id || 'Unknown Admin User'
    end

    def info_for_paper_trail
      { whodunnit_type: current_admin_user.class.name } if admin_user_signed_in?
    end
  end

...
carloslima18 commented 3 weeks ago

put include DeviseTokenAuth::Concerns::SetUserByToken in the model