Allan Klaus
Allan Klaus

Reputation: 43

Authorize Google Oauth2

I have an application ruby on rails and I'm trying to authorize my app in google, but I always get uninitialized constant

I tried to use Google::Auth::Stores::TokenStore and Google::APIClient::InstalledAppFlow

I followed theses samples https://github.com/google/google-auth-library-ruby#example-command-line and https://developers.google.com/youtube/v3/code_samples/ruby?hl=pt-br#upload_a_video

One use googleauth and other google-api-client.

In my Gemfile

gem 'google-api-client', '0.8.2', require: 'google/api_client' gem 'googleauth'

In my code

Using first example

def authorization
    client_id = Google::Auth::ClientId.from_file './client_secrets.json'
    scope = ['SCOPE']
    token_store = Google::Auth::Stores::FileTokenStore.new(file: './tokens.yaml')
    authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)
    credentials = authorizer.get_credentials(user_id)
    if credentials.nil?
        url = authorizer.get_authorization_url(base_url: OOB_URI )
        puts "Open #{url} in your browser and enter the resulting code:"
        code = gets
        credentials = authorizer.get_and_store_credentials_from_code(
        user_id: user_id, code: code, base_url: OOB_URI)
    end
end

Using second example

def authorization
    file_storage = Google::APIClient::FileStore.new(oauth2)
    if file_storage.authorization.nil?
        client_secrets = Google::APIClient::ClientSecrets.load
        flow = Google::APIClient::InstalledAppFlow.new(
        client_id: client_secrets.client_id,
        client_secret: client_secrets.client_secret,
        scope: [YOUTUBE_UPLOAD_SCOPE]
        )
        client.authorization = flow.authorize(file_storage)
    else
        client.authorization = file_storage.authorization
    end
end

Upvotes: 0

Views: 657

Answers (1)

Allan Klaus
Allan Klaus

Reputation: 43

I found the solution using the second case. When I added the gem gem 'google-api-client', '>0.7', require: 'google/api_client' in Gemfile I thought that all was done, but Google::APIClient::FileStorage and Google::APIClient::InstalledAppFlow need to require more files, so in the file you will use theses guys add these lines

require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'

Upvotes: 1

Related Questions