Skip to content

Instantly share code, notes, and snippets.

@wheeyls
Last active September 20, 2017 22:16
Show Gist options
  • Save wheeyls/143d153db3d7af6422372ea1b008d01f to your computer and use it in GitHub Desktop.
Save wheeyls/143d153db3d7af6422372ea1b008d01f to your computer and use it in GitHub Desktop.
require 'googleauth'
require 'googleauth/stores/file_token_store'
module SEO
class Auth
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
USER_ID_KEY = 'GOOGLE_SEARCH_CONSOLE_USER_ID'
attr_reader :token_file, :secret, :id
def initialize(id: ENV['GOOGLE_SEARCH_CONSOLE_CLIENT_ID'],
secret: ENV['GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET'],
token_file: 'tmp/tokens.yml')
@id = id
@secret = secret
@token_file = token_file
end
def headers
Hash[authorize.apply({}).map { |k, v| [k.to_s, v] }]
end
def authorize(user_id = ENV[USER_ID_KEY])
creds = authorizer.get_credentials(user_id)
if creds.nil?
launch_browser(user_id)
else
creds
end
end
def authorize!(user_id = ENV[USER_ID_KEY])
launch_browser(user_id)
end
private
def launch_browser(user_id)
url = authorizer.get_authorization_url(base_url: OOB_URI)
puts "Open #{url} in your browser and enter the resulting code:"
code = STDIN.gets
authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)
end
def scopes
%w(https://www.googleapis.com/auth/webmasters)
end
def authorizer
@authorized ||= Google::Auth::UserAuthorizer.new(client_id, scopes, token_store)
end
def client_id
Google::Auth::ClientId.new(id, secret)
end
def token_store
@token_store ||= Google::Auth::Stores::FileTokenStore.new(file: token_file)
end
end
end
@wheeyls
Copy link
Author

wheeyls commented Sep 20, 2017

Simple class to get access to Google APIs in a command line interface tools.

Set environment variables for user_id (probably your email), client_id and client_secret (found in google api console), then you can use the api:

authorize! forces a new login.
authorize tries to use existing login
headers returns a properly formatted header, can be dropped right into your request function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment