Module: Hub::GitHubAPI::OAuth

Included in:
Hub::GitHubAPI
Defined in:
lib/hub/github_api.rb

Instance Method Summary collapse

Instance Method Details

#apply_authentication(req, url) ⇒ Object



324
325
326
327
328
329
330
331
332
333
334
# File 'lib/hub/github_api.rb', line 324

def apply_authentication req, url
  if req.path =~ %r{^(/api/v3)?/authorizations\b}
    super
  else
    user = url.user ? CGI.unescape(url.user) : config.username(url.host)
    token = config.oauth_token(url.host, user) {
      obtain_oauth_token url.host, user
    }
    req['Authorization'] = "token #{token}"
  end
end

#local_hostnameObject



376
377
378
379
# File 'lib/hub/github_api.rb', line 376

def local_hostname
  require 'socket'
  Socket.gethostname
end

#local_userObject



371
372
373
374
# File 'lib/hub/github_api.rb', line 371

def local_user
  require 'etc'
  Etc.getlogin
end

#obtain_oauth_token(host, user) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/hub/github_api.rb', line 336

def obtain_oauth_token host, user
  auth_url = URI.parse("https://%s@%s/authorizations" % [CGI.escape(user), host])
  auth_params = {
    :scopes => ['repo'],
    :note => "hub for #{local_user}@#{local_hostname}",
    :note_url => oauth_app_url
  }
  res = nil
  two_factor_code = nil

  loop do
    res = post(auth_url, auth_params) do |req|
      req['X-GitHub-OTP'] = two_factor_code if two_factor_code
    end

    if res.success?
      break
    elsif res.status == 401 && res['X-GitHub-OTP'].to_s.include?('required')
      $stderr.puts "warning: invalid two-factor code" if two_factor_code
      two_factor_code = config.prompt_auth_code
    elsif res.status == 422 && 'already_exists' == res.data['errors'][0]['code']
      if auth_params[:note] =~ / (\d+)$/
        res.error! if $1.to_i >= 9
        auth_params[:note].succ!
      else
        auth_params[:note] += ' 2'
      end
    else
      res.error!
    end
  end

  res.data['token']
end