robins35
robins35

Reputation: 681

Ruby Gmail API with OAUTH2 responds with Invalid credentials (Failure) when logging in

I am trying to connect to the Gmail api using the Gmail for Ruby gem. I'm following this google oauth2 guide for installed applications.

I have set my app up in the Google Developer's Console, I am able to send a request with my client_id and client_secret to obtain an authorization code. I am then able to send a request with my authorization code to obtain an access token and a refresh token. I am able to successfully send a request to refresh my access token, and it returns a new access token.

The problem arises when I try to connect to Gmail. First I set an instance variable @gmail = Gmail.connect(:xoauth2, @email, @client.access_token). Then, I attempt to login with @gmail.login(true). However, when I try that, I get the following error:

Couldn't login to given Gmail account: [email protected] (Invalid credentials (Failure)) (Gmail::Client::AuthorizationError)

I am at a loss here, everything suggests I'm executing the oauth2 flow correctly, except the fact that when it comes time to login, I get invalid credentials. When generating my authorization code, I specifically click my email and allow my app to have access. The API is also enabled in my developers console. Here is the full code:

class GmailClient
  def initialize
    load_client_info
    @email = "[email protected]"
    load_and_set_oauth2_tokens

    sign_in_gmail
    binding.pry
  end

  private

  def sign_in_gmail
    binding.pry
    @gmail = Gmail.connect(:xoauth2, @email, @client.access_token)
    ######################
    # RIGHT HERE IS WHERE IT FAIL
    ######################
    @gmail.login true
    binding.pry
  end

  def load_client_info
    gmail_credentials = YAML.load_file('config/gmail.yml')
    @client_id = gmail_credentials["client_id"]
    @client_secret = gmail_credentials["client_secret"]
    @redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
  end

  def load_and_set_oauth2_tokens use_cached_tokens = true
    if use_cached_tokens && File.exist?("config/tokens.yml")
      token_hash = YAML.load_file('config/tokens.yml')
      @authorization_code = { code: token_hash["authorization_code"],
                              is_cached: true }
      @client = signet_client(token_hash)
      @token_hash = @client.refresh!
    else
      if !(instance_variable_defined?("@authorization_code") && @authorization_code[:is_cached] == false)
        retrieve_and_set_authorization_code
      end
      @token_hash = set_client_and_retrieve_oauth2_tokens
    end
    write_tokens_to_file
  end

  def retrieve_and_set_authorization_code
      puts "Go to the following url to enable the gmail cli app:"
      puts "https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=#{@client_id}"
      print "Paste your authorization code here: "
      @authorization_code = { code: gets.chomp,
                              is_cached: false }
  end

  def set_client_and_retrieve_oauth2_tokens
    @client = signet_client
    @client.fetch_access_token!
  end

  def signet_client token_hash = nil
    client = Signet::OAuth2::Client.new(
      client_id: @client_id,
      client_secret: @client_secret,
      redirect_uri: @redirect_uri,
      scope: 'email',
      token_credential_uri: 'https://www.googleapis.com/oauth2/v4/token'
    )
    if token_hash.present?
      client.refresh_token = token_hash["refresh_token"]
    else
      client.authorization_uri = 'https://accounts.google.com/o/oauth2/auth'
      client.code = @authorization_code[:code]
    end
    client
  end

  def write_tokens_to_file
    if File.exist?("config/tokens.yml")
      data = YAML.load_file "config/tokens.yml"
      @token_hash.each { |k, v| data[k] = v }
      File.open('config/tokens.yml', 'w') do |file|
        YAML.dump(data, file)
      end
    else
      File.open('config/tokens.yml', 'w') do |file|
        @token_hash.each { |k, v| file.write("#{k}: #{v}\n") }
        file.write("authorization_code: #{@authorization_code[:code]}\n")
      end
    end
  end
end

If my question is lacking any info, please just ask, I am eager to solve this.

Upvotes: 1

Views: 571

Answers (1)

Mikhail Chuprynski
Mikhail Chuprynski

Reputation: 2493

Scopes matter. Here are right ones:

scope: ['https://mail.google.com/', 'https://www.googleapis.com/auth/userinfo.email' #,'https://www.googleapis.com/auth/gmail.send' - if you'd like to send emails as well]

Upvotes: 1

Related Questions