module Github::Api::Auth

Constants

AUTH_FILE
AUTH_LOCAL_FILE
SCOPES
VERSION

Attributes

github[RW]
scopes[RW]

Public Class Methods

new(scopes: SCOPES) click to toggle source
# File lib/github/api/auth/auth.rb, line 14
def self.new(scopes: SCOPES)
  Github::Api::Auth::Klass.new(scopes: scopes)
end
new(scopes: []) click to toggle source
# File lib/github/api/auth/auth.rb, line 18
def initialize(scopes: [])
  @scopes = scopes
  authenticate
end

Private Instance Methods

authenticate() click to toggle source
# File lib/github/api/auth/auth.rb, line 25
def authenticate
  configure_from_file || basic_authentication
end
basic_authentication() click to toggle source
# File lib/github/api/auth/auth.rb, line 29
def basic_authentication
  login = ask('github username: ')
  password = ask('password: ') { |c| c.echo = false }
  self.github = Octokit::Client.new(login: login, password: password)
  token = create_access_token
  store_token(sanitize_token(token))
  configure_from_file
end
configure_from_file() click to toggle source
# File lib/github/api/auth/auth.rb, line 38
def configure_from_file
  path = File.exists?(AUTH_LOCAL_FILE) ? AUTH_LOCAL_FILE : AUTH_FILE
  config = YAML.load_file(path)
  self.github = Octokit::Client.new(access_token: config[:token])
  true
rescue
  false
end
create_access_token() click to toggle source
# File lib/github/api/auth/auth.rb, line 47
def create_access_token
  note = gen_token_note
  github.create_authorization(scopes: scopes, note: note)
rescue Octokit::OneTimePasswordRequired => e
  otp = ask('one time password required: ')
  github.create_authorization(scopes: scopes, note: note, headers: { 'X-GitHub-OTP' => otp })
end
gen_token_note() click to toggle source
# File lib/github/api/auth/auth.rb, line 63
def gen_token_note
  # TODO Make this use existing token instead of creating new one
  # NOTE We need this number if user want to authenticate multiple devices
  number = Time.now.to_i
  "github-api-auth authorization #{number}"
end
sanitize_token(token) click to toggle source
# File lib/github/api/auth/auth.rb, line 59
def sanitize_token(token)
  token.to_h.reject { |k, v| k == :app }
end
store_token(token) click to toggle source
# File lib/github/api/auth/auth.rb, line 55
def store_token(token)
  File.open(AUTH_LOCAL_FILE, 'w') { |f| f.write(token.to_yaml) }
end