Module: GithubPivotalFlow::GitHubAPI::OAuth

Included in:
GithubPivotalFlow::GitHubAPI
Defined in:
lib/github_pivotal_flow/github_api.rb

Instance Method Summary collapse

Instance Method Details

#apply_authentication(req, url) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
# File 'lib/github_pivotal_flow/github_api.rb', line 202

def apply_authentication req, url
  if req.path =~ %r{^(/api/v3)?/authorizations$}
    super
  else
    user = url.user ? CGI.unescape(url.user) : config.github_username(url.host)
    token = config.github_api_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



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/github_pivotal_flow/github_api.rb', line 214

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(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.ask_auth_code
      return obtain_oauth_token(host, user, two_factor_code)
    else
      res.error!
    end
  end

  if found = res.data.find {|auth| auth['app']['url'] == oauth_app_url }
    found['token']
  else
    # create a new authorization
    res = post auth_url,
               :scopes => %w[repo], :note => 'github-pivotal-flow', :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