初期化されていない定数 CustomTokenResponse(NameError) と有効なトークンに対する不正アクセス

概要

RailsアプリをAPIに移行しようとしていて、認証用にdoorkeeper gemをインストールしたところ、有効なユーザーのトークンが生成されます。今、私には2つの問題があります

このガイドに従ってプロセスを進めました

https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://scotch.io/@jiggs/rails-api-doorkeeper-devise

# frozen_string_literal: true

#Doorkeeper.rb

Doorkeeper.configure do
  # Change the ORM that doorkeeper will use (needs plugins)
  orm :active_record

  # This block will be called to check whether the resource owner is authenticated or not.
  resource_owner_authenticator do
    # raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}"
    # Put your resource owner authentication logic here.
    # Example implementation:
    current_user || warden.authenticate!(:scope => :user)
  end

   resource_owner_from_credentials do |routes|
    user = User.find_for_database_authentication(:email => params[:email])
    if user && user.valid_for_authentication? { user.valid_password?(params[:password]) }
      user
    end
  end

  skip_authorization do
    true
  end

  Doorkeeper::OAuth::TokenResponse.send :prepend, CustomTokenResponse
  Doorkeeper::OAuth::ErrorResponse.send :prepend, CustomTokenErrorResponse

  # WWW-Authenticate Realm (default "Doorkeeper").
  #
  # realm "Doorkeeper"
end


# lib/custom_token_response.rb

module CustomTokenResponse
  def body
    user_details = User.find(@token.resource_owner_id)
    # call original `#body` method and merge its result with the additional data hash
       super.merge({
           status_code: 200,
           message: I18n.t('devise.sessions.signed_in'),
           result: user_details
       })
  end
end
# lib/custom_token_error_response.rb

module CustomTokenErrorResponse
  def body
    {
      status_code: 401,
      message: I18n.t('devise.failure.invalid', authentication_keys: User.authentication_keys.join('/')),
      result: []
    }
    # or merge with existing values by
    # super.merge({key: value})
  end
end

1: /home/rubyians/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/active_support.rb:8:in without_bootsnap_cache から /home/rubyians/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/active_support.rb:79:inblock inload_missing_constant’: 初期化されていない定数 CustomTokenResponse (NameError)

解決策

doorkeeper.rb の下部を to_prepare にネストされるように更新しました。

Rails.application.config.to_prepare do
  Doorkeeper::OAuth::TokenResponse.prepend CustomTokenResponse
end

Railsのアップグレードに関する問題を修正しました。