Class: TwitchOAuth2::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/twitch_oauth2/client.rb

Overview

Client for making requests

Constant Summary collapse

CONNECTION =
Faraday.new(
	url: 'https://id.twitch.tv/oauth2/'
) do |connection|
	connection.request :json

	connection.response :parse_dates

	connection.response :json,
		content_type: /\bjson$/,
		parser_options: { symbolize_names: true }
end.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id:, client_secret:, redirect_uri: 'http://localhost') ⇒ Client

Returns a new instance of Client.



24
25
26
27
28
# File 'lib/twitch_oauth2/client.rb', line 24

def initialize(client_id:, client_secret:, redirect_uri: 'http://localhost')
	@client_id = client_id
	@client_secret = client_secret
	@redirect_uri = redirect_uri
end

Instance Attribute Details

#client_idObject (readonly)

Returns the value of attribute client_id.



22
23
24
# File 'lib/twitch_oauth2/client.rb', line 22

def client_id
  @client_id
end

Instance Method Details

#authorize(scopes:) ⇒ Object

Raises:



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/twitch_oauth2/client.rb', line 30

def authorize(scopes:)
	response = CONNECTION.get(
		'authorize',
		client_id: @client_id,
		redirect_uri: @redirect_uri,
		scope: Array(scopes).join(' '),
		response_type: :code
	)

	location = response.headers[:location]
	return location if location

	raise Error, response.body[:message]
end

#refresh(refresh_token:) ⇒ Object

Raises:



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/twitch_oauth2/client.rb', line 68

def refresh(refresh_token:)
	response = CONNECTION.post(
		'token',
		client_id: @client_id,
		client_secret: @client_secret,
		grant_type: :refresh_token,
		refresh_token: refresh_token
	)

	return response.body if response.success?

	raise Error, response.body[:message]
end

#token(token_type:, code: nil) ⇒ Object

Raises:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/twitch_oauth2/client.rb', line 45

def token(token_type:, code: nil)
	response = CONNECTION.post(
		'token',
		client_id: @client_id,
		client_secret: @client_secret,
		code: code,
		grant_type: grant_type_by_token_type(token_type),
		redirect_uri: @redirect_uri
	)

	return response.body if response.success?

	raise Error, response.body[:message]
end

#validate(access_token:) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/twitch_oauth2/client.rb', line 60

def validate(access_token:)
	response = CONNECTION.get(
		'validate', {}, { 'Authorization' => "OAuth #{access_token}" }
	)

	response.body
end