ToolJet/app/services/restapi_query_service.rb

69 lines
2.5 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
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"]
if data_source
url = "#{source_options['url']}#{url}"
end
method = options["method"] || "GET"
headers = (options["headers"] || []).reject { |header| header[0].empty? }
2021-05-20 04:38:11 +00:00
headers = headers.to_h
body = options["body"]
url_params = options["url_params"]
2021-04-29 06:41:23 +00:00
if source_options["auth_type"] === "oauth2"
2021-04-29 06:41:23 +00:00
oauth_tokens = DataSourceUserOauth2.where(user: current_user,
data_source: data_source).order("created_at desc")
2021-04-29 06:41:23 +00:00
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",
2021-04-29 06:41:23 +00:00
data: { auth_url: auth_url } } }
else
token = JSON.parse(oauth_tokens.first.options)["access_token"]
2021-04-29 06:41:23 +00:00
end
if source_options["add_token_to"] === "header"
2021-04-29 06:41:23 +00:00
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
response = if method.downcase === "get"
2021-04-29 06:41:23 +00:00
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",
2021-04-29 06:41:23 +00:00
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