Method: Gist#access_token_login!

Defined in:
lib/gist.rb

#access_token_login!(credentials = {}) ⇒ Object

Logs the user into gist.

This method asks the user for a username and password, and tries to obtain and OAuth2 access token, which is then stored in ~/.gist

Raises:

See Also:



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/gist.rb', line 400

def access_token_login!(credentials={})
  puts "Obtaining OAuth2 access_token from GitHub."
  loop do
    print "GitHub username: "
    username = credentials[:username] || $stdin.gets.strip
    print "GitHub password: "
    password = credentials[:password] || begin
      `stty -echo` rescue nil
      $stdin.gets.strip
    ensure
      `stty echo` rescue nil
    end
    puts ""

    request = Net::HTTP::Post.new("#{base_path}/authorizations")
    request.body = JSON.dump({
      :scopes => [:gist],
      :note => "The gist gem (#{Time.now})",
      :note_url => "https://github.com/ConradIrwin/gist"
    })
    request.content_type = 'application/json'
    request.basic_auth(username, password)

    response = http(api_url, request)

    if Net::HTTPUnauthorized === response && response['X-GitHub-OTP']
      print "2-factor auth code: "
      twofa_code = $stdin.gets.strip
      puts ""

      request['X-GitHub-OTP'] = twofa_code
      response = http(api_url, request)
    end

    if Net::HTTPCreated === response
      AuthTokenFile.write JSON.parse(response.body)['token']
      puts "Success! #{ENV[URL_ENV_NAME] || "https://github.com/"}settings/tokens"
      return
    elsif Net::HTTPUnauthorized === response
      puts "Error: #{JSON.parse(response.body)['message']}"
      next
    else
      raise "Got #{response.class} from gist: #{response.body}"
    end
  end
rescue => e
  raise e.extend Error
end