+ def oauth_2_login
+ require 'signet/oauth_2/client'
+ require 'launchy'
+ require 'yaml'
+ if !options[:client_credential_key] ||
+ !options[:client_credential_secret]
+ STDERR.puts('No client ID and secret supplied.')
+ exit(1)
+ end
+ if options[:access_token]
+ config = {
+ "mechanism" => "oauth_2",
+ "scope" => options[:scope],
+ "client_id" => options[:client_credential_key],
+ "client_secret" => options[:client_credential_secret],
+ "access_token" => options[:access_token],
+ "refresh_token" => options[:refresh_token]
+ }
+ config_file = File.expand_path('~/.google-api.yaml')
+ open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
+ exit(0)
+ else
+ $verifier = nil
+ # TODO(bobaman): Cross-platform?
+ logger = WEBrick::Log.new('/dev/null')
+ server = WEBrick::HTTPServer.new(
+ :Port => OAUTH_SERVER_PORT,
+ :Logger => logger,
+ :AccessLog => logger
+ )
+ trap("INT") { server.shutdown }
+
+ server.mount("/", OAuthVerifierServlet)
+
+ oauth_client = Signet::OAuth2::Client.new(
+ :authorization_uri =>
+ 'https://www.google.com/accounts/o8/oauth2/authorization',
+ :token_credential_uri =>
+ 'https://www.google.com/accounts/o8/oauth2/token',
+ :client_id => options[:client_credential_key],
+ :client_secret => options[:client_credential_secret],
+ :redirect_uri => "http://localhost:#{OAUTH_SERVER_PORT}/",
+ :scope => options[:scope]
+ )
+
+ # Launch browser
+ Launchy.open(oauth_client.authorization_uri.to_s)
+
+ server.start
+ oauth_client.code = $verifier
+ oauth_client.fetch_access_token!
+ config = {
+ "mechanism" => "oauth_2",
+ "scope" => options[:scope],
+ "client_id" => oauth_client.client_id,
+ "client_secret" => oauth_client.client_secret,
+ "access_token" => oauth_client.access_token,
+ "refresh_token" => oauth_client.refresh_token
+ }
+ config_file = File.expand_path('~/.google-api.yaml')
+ open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
+ exit(0)
+ end
+ end
+