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

#obtain_oauth_token(host, user, two_factor_code = nil) ⇒ 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
# File 'lib/hub/github_api.rb', line 336

def obtain_oauth_token host, user, two_factor_code = nil
  auth_url = URI.parse("https://%s@%s/authorizations" % [CGI.escape(user), host])

  # dummy request to trigger a 2FA SMS since a HTTP GET won't do it
  post(auth_url) if !two_factor_code

  # first try to fetch existing authorization
  res = get_all(auth_url) do |req|
    req['X-GitHub-OTP'] = two_factor_code if two_factor_code
  end
  unless res.success?
    if !two_factor_code && res['X-GitHub-OTP'].to_s.include?('required')
      two_factor_code = config.prompt_auth_code
      return obtain_oauth_token(host, user, two_factor_code)
    else
      res.error!
    end
  end

  if found = res.data.find {|auth| auth['note'] == 'hub' || auth['note_url'] == oauth_app_url }
    found['token']
  else
    # create a new authorization
    res = post auth_url,
      :scopes => %w[repo], :note => 'hub', :note_url => oauth_app_url do |req|
        req['X-GitHub-OTP'] = two_factor_code if two_factor_code
      end
    res.error! unless res.success?
    res.data['token']
  end
end