Class: TiktokOAuth2Client

Inherits:
OAuth2::Client
  • Object
show all
Defined in:
lib/strategies/tiktok_oauth2_client.rb

Overview

Overriding a few methods for the OAuth2::Client (github.com/oauth-xx/oauth2/blob/422d3132343227cec84d5d34a7a8ce4825439bdb/lib/oauth2/client.rb)

TikTok Returns it’s access_token inside of a data attribute which is unexpected by OAuth2. Overriding methods to look inside of the data attribute for the access_token

Instance Method Summary collapse

Instance Method Details

#get_token(params, access_token_opts = {}, access_token_class = OAuth2::AccessToken) ⇒ AccessToken

Initializes an AccessToken by making a request to the token endpoint

Parameters:

  • params (Hash)

    a Hash of params for the token endpoint

  • access_token_opts (Hash) (defaults to: {})

    access token options, to pass to the AccessToken object

  • access_token_class (Class) (defaults to: OAuth2::AccessToken)

    class of access token for easier subclassing OAuth2::AccessToken

Returns:

  • (AccessToken)

    the initialized AccessToken

Raises:

  • (OAuth2::Error)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/strategies/tiktok_oauth2_client.rb', line 15

def get_token(params, access_token_opts = {}, access_token_class = OAuth2::AccessToken) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  params = params.map do |key, value|
    if RESERVED_PARAM_KEYS.include?(key)
      [key.to_sym, value]
    else
      [key, value]
    end
  end

  params = authenticator.apply(params.to_h)
  opts = { raise_errors: options[:raise_errors], parse: params.delete(:parse) }
  headers = params.delete(:headers) || {}
  if options[:token_method] == :post
    opts[:body] = params
    opts[:headers] = { "Content-Type" => "application/x-www-form-urlencoded" }
  else
    opts[:params] = params
    opts[:headers] = {}
  end
  opts[:headers].merge!(headers)
  http_method = options[:token_method] == :post_with_query_string ? :post : options[:token_method]
  response = request(http_method, token_url, opts)
  response_contains_token = response.parsed.is_a?(Hash) &&
                            (response.parsed.dig("data", "access_token") || response.parsed.dig("data", "id_token"))

  raise OAuth2::Error, response if options[:raise_errors] && !response_contains_token

  return nil if !response_contains_token

  build_access_token(response, access_token_opts, access_token_class)
end