diff --git a/app/services/google_oauth_service.rb b/app/services/google_oauth_service.rb index 8cea16d07e..bc0c272595 100644 --- a/app/services/google_oauth_service.rb +++ b/app/services/google_oauth_service.rb @@ -31,4 +31,30 @@ class GoogleOauthService [['access_token', access_token], ['refresh_token', refresh_token]] end + + def self.refresh_access_token(refresh_token, data_source) + access_token_url = 'https://oauth2.googleapis.com/token' + client_id = ENV.fetch('GOOGLE_CLIENT_ID') + client_secret = ENV.fetch('GOOGLE_CLIENT_SECRET') + grant_type = 'refresh_token' + + response = HTTParty.post(access_token_url, + body: { refresh_token: refresh_token, + client_id: client_id, + client_secret: client_secret, + grant_type: grant_type, + redirect_uri: "#{ENV.fetch('TOOLJET_HOST')}/oauth2/authorize" + }.to_json, + headers: { 'Content-Type' => 'application/json' }) + + result = JSON.parse(response.body) + + access_token = result['access_token'] + + credential_id = data_source.options["access_token"]["credential_id"] + credential = Credential.find(credential_id) + credential.update(value: access_token) + + access_token + end end diff --git a/app/services/googlesheets_query_service.rb b/app/services/googlesheets_query_service.rb index 7d8fef585a..2688c8770b 100644 --- a/app/services/googlesheets_query_service.rb +++ b/app/services/googlesheets_query_service.rb @@ -18,7 +18,7 @@ class GooglesheetsQueryService result = read_data(access_token) if result.code === 401 - refresh_access_token + access_token = refresh_access_token result = read_data(access_token) end @@ -33,7 +33,7 @@ class GooglesheetsQueryService headers.each_with_index do |header, index| row[header] = value[index] end - parsed_values << row + data << row end else @@ -62,6 +62,6 @@ class GooglesheetsQueryService end def refresh_access_token - + GoogleOauthService.refresh_access_token(source_options['refresh_token'], @source ) end end