Module: CsvToGsheet

Defined in:
lib/csv_to_gsheet.rb

Defined Under Namespace

Modules: Runner

Constant Summary collapse

OOB_URI =
'urn:ietf:wg:oauth:2.0:oob'.freeze
APPLICATION_NAME =
'csv_to_gsheet_managed_by_you'.freeze
CREDENTIALS_PATH =
"#{ENV['HOME']}/.csv_to_gsheet_google_api_credentials.json".freeze
TOKEN_PATH =

The file token.yaml stores the user’s access and refresh tokens, and is created automatically when the authorization flow completes for the first time.

"#{ENV['HOME']}/.csv_to_gsheet_google_oauth2_token.yaml".freeze
SCOPE =
Google::Apis::SheetsV4::AUTH_SPREADSHEETS

Class Method Summary collapse

Class Method Details

.authorizeGoogle::Auth::UserRefreshCredentials

Ensure valid credentials, either by restoring from the saved credentials files or intitiating an OAuth2 authorization. If authorization is required, the user’s default browser will be launched to approve the request.

Returns:

  • (Google::Auth::UserRefreshCredentials)

    OAuth2 credentials



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/csv_to_gsheet.rb', line 144

def self.authorize
  client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(base_url: OOB_URI)
    puts 'Open the following URL in the browser and enter the ' \
         "resulting code after authorization:\n" + url
    code = gets.chomp
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI
    )
  end
  credentials
end

.check_token_filesObject



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/csv_to_gsheet.rb', line 125

def self.check_token_files
  if !File.exists? CREDENTIALS_PATH
    puts "No credentials.json equivalent file for your OAuth2 app exists at #{CREDENTIALS_PATH}"
    puts ""
    puts "Download your credentials.json file from https://developers.google.com/identity/sign-in/web/sign-in"
    puts ""
    puts "Move that credentials.json file to #{CREDENTIALS_PATH}"
    puts ""
    puts "Exiting now without connecting to Google's API"
    exit 1
  end
end