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



23
24
25
# File 'lib/restforce/middleware/authentication.rb', line 23

def authenticate!
  raise 'must subclass'
end

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/restforce/middleware/authentication.rb', line 9

def call(env)
  request_body = env[:body]
  request = env[:request]
  begin
    return authenticate! if force_authenticate?(env)
    @app.call(env)
  rescue Restforce::UnauthorizedError
    authenticate!
    env[:body] = request_body
    env[:request] = request
    @app.call(env)
  end
end

#connectionObject



27
28
29
30
31
32
33
# File 'lib/restforce/middleware/authentication.rb', line 27

def connection
  @connection ||= Faraday.new(:url => "https://#{@options[:host]}") do |builder|
    builder.response :json
    builder.use Restforce::Middleware::Logger, Restforce.configuration.logger 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

#force_authenticate?(env) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/restforce/middleware/authentication.rb', line 35

def force_authenticate?(env)
  env[:request_headers] && env[:request_headers]['X-ForceAuthenticate']
end