ToolJet/app/services/restapi_query_service.rb

62 lines
2.4 KiB
Ruby
Raw Normal View History

2021-04-04 17:07:03 +00:00
class RestapiQueryService
2021-04-29 06:41:23 +00:00
attr_accessor :data_query, :options, :source_options, :current_user, :data_source
def initialize(data_query, data_source, options, source_options, current_user)
2021-04-29 06:41:23 +00:00
@data_query = data_query
@options = options
@source_options = source_options
@current_user = current_user
@data_source = data_source
2021-04-29 06:41:23 +00:00
end
def process
url = options['url']
method = options['method']
headers = (options['headers'] || []).reject { |header| header[0].empty? }
2021-05-20 04:38:11 +00:00
headers = headers.to_h
2021-04-29 06:41:23 +00:00
body = options['body']
url_params = options['url_params']
if source_options['auth_type'] === 'oauth2'
oauth_tokens = DataSourceUserOauth2.where(user: current_user,
data_source: data_source).order('created_at desc')
if oauth_tokens.size == 0
auth_url = "#{source_options['auth_url']}?response_type=code&client_id=#{source_options['client_id']}&redirect_uri=#{ENV.fetch('TOOLJET_HOST')}/oauth2/authorize&scope=#{source_options['scopes']}"
return { error: { message: 'needs authorization', code: 'oauth2_needs_auth',
data: { auth_url: auth_url } } }
else
token = JSON.parse(oauth_tokens.first.options)['access_token']
end
if source_options['add_token_to'] === 'header'
headers = {
2021-05-20 04:38:11 +00:00
**headers,
2021-04-29 06:41:23 +00:00
'Authorization': "Bearer #{token}"
}
end
2021-04-04 17:07:03 +00:00
end
2021-04-29 06:41:23 +00:00
response = if method.downcase === 'get'
HTTParty.send(method.downcase,
url,
2021-04-29 06:41:23 +00:00
headers: headers,
query: url_params.to_h)
else
HTTParty.send(method.downcase,
url,
2021-04-29 06:41:23 +00:00
headers: headers,
query: url_params.to_h,
body: body.to_h)
end
if response.code == 401
auth_url = "#{source_options['auth_url']}?response_type=code&client_id=#{source_options['client_id']}&redirect_uri=#{ENV.fetch('TOOLJET_HOST')}/oauth2/authorize&scope=#{source_options['scopes']}"
return { error: { message: 'needs authorization', code: 'oauth2_needs_auth',
data: { auth_url: auth_url } } }
2021-04-04 17:07:03 +00:00
end
2021-04-29 06:41:23 +00:00
{ code: response.code, data: JSON.parse(response.body) }
end
2021-04-04 17:07:03 +00:00
end