Skip to content

A platform for community discussion. Free, open, simple.

1.3 KB
Raw Blame
# frozen_string_literal: true

class OmniAuth::Strategies::Oauth2Basic < ::OmniAuth::Strategies::OAuth2
  option :name, "oauth2_basic"

  uid do
    if path = SiteSetting.oauth2_callback_user_id_path.split(".")
      recurse(access_token, [*path]) if path.present?
    end
  end

  info do
    if paths = SiteSetting.oauth2_callback_user_info_paths.split("|")
      result = Hash.new
      paths.each do |p|
        segments = p.split(":")
        if segments.length == 2
          key = segments.first
          path = [*segments.last.split(".")]
          result[key] = recurse(access_token, path)
        end
      end
      result
    end
  end

  def callback_phase
    response = super
    raise env["omniauth.error"] if env["omniauth.error"].is_a?(Faraday::Error)
    response
  rescue Faraday::Error => e
    detail =
      if e.is_a?(Faraday::TimeoutError)
        "timed out after #{GlobalSetting.oauth2_request_timeout_seconds}s"
      else
        "failed"
      end
    Rails.logger.warn("OAuth2 Basic: token request #{detail}: #{e.class}")
    fail!(:oauth2_basic_request_failed, e)
  end

  def callback_url
    Discourse.base_url_no_prefix + script_name + callback_path
  end

  def recurse(obj, keys)
    return nil if !obj
    k = keys.shift
    result = obj.respond_to?(k) ? obj.send(k) : obj[k]
    keys.empty? ? result : recurse(result, keys)
  end
end