Sha256: 25711102b70a443fa2439bc0b1282cde34cd5a35a4378e5b14cfe5e5f9f59a8e

Contents?: true

Size: 1.65 KB

Versions: 5

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

require "googleauth"
require "launchy"
require_relative "google-oauth-cli/version"
require_relative "google-oauth-cli/server"

class GoogleOAuthCli
  class Error < StandardError; end

  def initialize(client_id:, client_secret:, scope:, credentials_file: nil, port: 9876)
    @credentials = Google::Auth::UserRefreshCredentials.new(
      client_id: client_id,
      client_secret: client_secret,
      scope: scope,
      redirect_uri: "http://localhost:#{port}/authorize",
      additional_parameters: { access_type: "offline" }
    )
    if credentials_file
      @credentials_file = Pathname.new(File.expand_path(credentials_file))
      @credentials_file
    end
    @port = port
  end

  def login
    authorize_from_credentials || authorize_from_authorization_code_flow
  end

  private

  attr_reader :credentials, :credentials_file, :port

  def authorize_from_credentials
    return nil unless credentials_file&.exist?

    token = JSON.parse(credentials_file.read)["refresh_token"]
    return nil if token.nil?

    credentials.refresh_token = token
    fetch_and_save_token!

    credentials
  end

  def authorize_from_authorization_code_flow
    state = SecureRandom.base64(16)
    credentials.state = state

    uri = credentials.authorization_uri
    Launchy.open(uri) do |exception|
      raise(Error, "Attempted to open #{uri} and failed because #{exception}")
    end

    credentials.code = Server.new(port: port, state: state).start
    fetch_and_save_token!

    credentials
  end

  def fetch_and_save_token!
    credentials.fetch_access_token!
    credentials_file&.write({ refresh_token: credentials.refresh_token }.to_json)
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
google-oauth-cli-1.0.1 lib/google-oauth-cli.rb
google-oauth-cli-1.0.0 lib/google-oauth-cli.rb
google-oauth-cli-0.1.5 lib/google-oauth-cli.rb
google-oauth-cli-0 lib/google-oauth-cli.rb
google-oauth-cli-0.1.1 lib/google-oauth-cli.rb