Class: Restforce::Middleware::Authentication

Inherits:
Restforce::Middleware show all
Defined in:
lib/restforce/middleware/authentication.rb

Overview

Faraday middleware that allows for on the fly authentication of requests. When a request fails (ie. A status of 401 is returned). The middleware will attempt to either reauthenticate (username and password) or refresh the oauth access token (if a refresh token is present).

Direct Known Subclasses

Password, Token

Defined Under Namespace

Classes: Password, Token

Instance Method Summary collapse

Methods inherited from Restforce::Middleware

#client, #initialize

Constructor Details

This class inherits a constructor from Restforce::Middleware

Instance Method Details

#authenticate!Object



16
17
18
19
20
21
22
23
24
# File 'lib/restforce/middleware/authentication.rb', line 16

def authenticate!
  response = connection.post '/services/oauth2/token' do |req|
    req.body = URI.encode_www_form params
  end
  raise Restforce::AuthenticationError, error_message(response) if response.status != 200
  @options[:instance_url] = response.body['instance_url']
  @options[:oauth_token]  = response.body['access_token']
  response.body
end

#call(env) ⇒ Object



9
10
11
12
13
14
# File 'lib/restforce/middleware/authentication.rb', line 9

def call(env)
  @app.call(env)
rescue Restforce::UnauthorizedError
  authenticate!
  raise
end

#connectionObject



30
31
32
33
34
35
36
37
# File 'lib/restforce/middleware/authentication.rb', line 30

def connection
  @connection ||= Faraday.new(:url => "https://#{@options[:host]}") do |builder|
    builder.use Restforce::Middleware::Mashify, nil, @options
    builder.response :json
    builder.use Restforce::Middleware::Logger, Restforce.configuration.logger, @options if Restforce.log?
    builder.adapter Faraday.default_adapter
  end
end

#error_message(response) ⇒ Object



39
40
41
# File 'lib/restforce/middleware/authentication.rb', line 39

def error_message(response)
  "#{response.body['error']}: #{response.body['error_description']}"
end

#paramsObject



26
27
28
# File 'lib/restforce/middleware/authentication.rb', line 26

def params
  raise 'not implemented'
end