require 'oauth2'

module OAuth2
  class Client
    alias_method :original_request, :request

    # PATCH: Prevent "multiple client credentials" error.
    # Okta rejects requests that provide credentials in both the Authorization header
    # and the POST body. This patch strips credentials from the body ONLY when
    # :basic_auth (Header-based) is explicitly configured.
    def request(verb, url, opts = {})
      is_basic_auth = options[:auth_scheme] == :basic_auth

      if is_basic_auth && verb == :post && opts[:body].is_a?(Hash)
        [:client_id, 'client_id', :client_secret, 'client_secret'].each do |key|
          opts[:body].delete(key)
        end
      end

      original_request(verb, url, opts)
    end
  end
end

module OmniAuth
  module Strategies
    class Okta < OmniAuth::Strategies::OAuth2
      # PATCH: Fix hardcoded UserInfo endpoint.
      # The legacy omniauth-okta gem (0.1.1) hardcodes '/oauth2/v1/userinfo',
      # which bypasses the '/oauth2/default' path required by Okta Custom
      # Authorization Servers. This patch allows using the user_info_url
      # defined in the strategy configuration.
      def raw_info
        url = options.client_options.user_info_url || "/oauth2/default/v1/userinfo"
        @_raw_info ||= access_token.get(url).parsed || {}
      rescue ::Errno::ETIMEDOUT
        raise ::Timeout::Error
      end
    end
  end
end
