Class: Simpal::Middleware::Authorization

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/simpal/middleware/authorization.rb

Overview

Requests an OAuth2 access token for a ‘Simpal::Client`, adding the resulting access token into each request.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, client) ⇒ Authorization

Returns a new instance of Authorization.



20
21
22
23
# File 'lib/simpal/middleware/authorization.rb', line 20

def initialize(app, client)
  super(app)
  @client = client
end

Instance Attribute Details

#access_tokenString (readonly)

Returns The access token to include in each request.

Returns:

  • (String)

    The access token to include in each request.



14
15
16
# File 'lib/simpal/middleware/authorization.rb', line 14

def access_token
  @access_token
end

#access_token_expires_atTime (readonly)

Returns The time at which the access token expires.

Returns:

  • (Time)

    The time at which the access token expires.



18
19
20
# File 'lib/simpal/middleware/authorization.rb', line 18

def access_token_expires_at
  @access_token_expires_at
end

#clientSimpal::Client (readonly)

Returns The client which we’re handling the ‘Authorization’ header for.

Returns:

  • (Simpal::Client)

    The client which we’re handling the ‘Authorization’ header for.



10
11
12
# File 'lib/simpal/middleware/authorization.rb', line 10

def client
  @client
end

Instance Method Details

#call(request_env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/simpal/middleware/authorization.rb', line 25

def call(request_env)
  retryable = true
  refresh_access_token

  begin
    request_env[:request_headers].merge!('Authorization' => "Bearer #{access_token}")
    super(request_env)
  rescue Faraday::UnauthorizedError
    raise unless retryable

    retryable = false
    refresh_access_token!
    retry
  end
end