Class: Airwallex::Middleware::AuthRefresh

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/airwallex/middleware/auth_refresh.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, client) ⇒ AuthRefresh

Returns a new instance of AuthRefresh.



6
7
8
9
# File 'lib/airwallex/middleware/auth_refresh.rb', line 6

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

Instance Method Details

#call(env) ⇒ Object



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

def call(env)
  # Skip authentication refresh for login endpoint
  return @app.call(env) if env[:url].path.include?("/authentication/login")

  # Ensure token is valid before making request
  @client.ensure_authenticated! unless env[:url].path.include?("/authentication/")

  response = @app.call(env)

  # If we get a 401, try refreshing the token and retrying once
  if response.status == 401 && !env[:request].fetch(:auth_retry, false)
    @client.authenticate!
    env[:request][:auth_retry] = true
    env[:request_headers]["Authorization"] = "Bearer #{@client.access_token}"
    response = @app.call(env)
  end

  response
end