Class: Oauth2Rails::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/oauth2_rails/base.rb

Direct Known Subclasses

Auth, Client

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Returns a new instance of Base.



6
7
8
9
10
11
12
13
14
15
# File 'lib/oauth2_rails/base.rb', line 6

def initialize(options = {})
  @oauth_id       = options[:oauth_id]       || OAUTH2_RAILS_ID
  @oauth_secret   = options[:oauth_secret]   || OAUTH2_RAILS_SECRET
  @redirect_uri   = options[:redirect_uri]   || OAUTH2_RAILS_CALLBACK
  @authorize_site = options[:authorize_site] || 'https://www.fitbit.com'
  @authorize_path = options[:authorize_path] || '/oauth2/authorize'
  @api_site       = options[:api_site]       || 'https://api.fitbit.com'
  @token_path     = options[:token_path]     || '/oauth2/token'
  @scope          = options[:scope]          || 'heartrate'
end

Instance Method Details

#call(action, destination, options = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/oauth2_rails/base.rb', line 25

def call(action, destination, options = {})
  user = options[:user]
  site = options[:site] || @api_site

  if user
    auth_header = "Bearer #{user}"
  else
    encoded = Base64.strict_encode64("#{@oauth_id}:#{@oauth_secret}")
    auth_header = "Basic #{encoded}"
  end

  call = connection(site).send(action) do |req|
    req.url destination
    req.headers['Content-Type']   = 'application/x-www-form-urlencoded'
    req.headers['Authorization']  = auth_header
    req.body = options[:body]
  end

  response = Response.new(call)
  case response.status
    when 400 ; raise Oauth2Rails::Errors::BadRequest,      "400 #{response.error_message}"
    when 404 ; raise Oauth2Rails::Errors::NotFound,        "404 #{response.error_message}"
    when 409 ; raise Oauth2Rails::Errors::Conflict,        "409 #{response.error_message}"
    when 500 ; raise Oauth2Rails::Errors::InternalServer,  "500 #{response.error_message}"
    when 502 ; raise Oauth2Rails::Errors::BadGateway,      "502 #{response.error_message}"
    when 401 ; raise Oauth2Rails::Errors::Unauthorized,    "401 #{response.error_message}"
    else ; response
  end

end

#connection(url) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/oauth2_rails/base.rb', line 17

def connection(url)
  Faraday.new(url: url) do |faraday|
    faraday.request  :url_encoded
    faraday.response :logger
    faraday.adapter  Faraday.default_adapter
  end
end