Class: FlexmlsApi::Authentication::OAuth2Impl::Middleware

Inherits:
Faraday::Response::ParseJson
  • Object
show all
Defined in:
lib/flexmls_api/authentication/oauth2_impl/middleware.rb

Overview

OAuth2 Faraday response middleware

HTTP Response after filter to package oauth2 responses and bubble up basic api errors.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



32
33
34
# File 'lib/flexmls_api/authentication/oauth2_impl/middleware.rb', line 32

def initialize(app)
  super(app)
end

Instance Method Details

#on_complete(finished_env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/flexmls_api/authentication/oauth2_impl/middleware.rb', line 11

def on_complete(finished_env)
  body = parse(finished_env[:body])
  FlexmlsApi.logger.debug("[oauth2] Response Body: #{body.inspect}")
  unless body.is_a?(Hash)
    raise InvalidResponse, "The server response could not be understood"
  end
  case finished_env[:status]
  when 200..299
    FlexmlsApi.logger.debug("[oauth2] Success!")
    session = OAuthSession.new(body)
  else 
    # Handle the WWW-Authenticate Response Header Field if present. This can be returned by 
    # OAuth2 implementations and wouldn't hurt to log.
    auth_header_error = finished_env[:request_headers]["WWW-Authenticate"]
    FlexmlsApi.logger.warn("Authentication error #{auth_header_error}") unless auth_header_error.nil?
    raise ClientError, {:message => body["error"], :code =>0, :status => finished_env[:status]}
  end
  FlexmlsApi.logger.debug("[oauth2] Session=#{session.inspect}")
  finished_env[:body] = session
end