Class: HighLevel::Middleware::RefreshOn401

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/high_level/middleware/refresh_on_401.rb

Overview

Faraday middleware. On a 401 (raised by ErrorHandler as UnauthorizedError), asks TokenRefresher for a new access token, rewrites the Authorization header, and retries the request once. The retry is marked via env.request.context so a second 401 cannot loop.

Constant Summary collapse

RETRY_FLAG =

Request-options context key marking that a refresh+retry has already been attempted, so a second 401 cannot loop.

:high_level_refresh_attempted

Instance Method Summary collapse

Constructor Details

#initialize(app, refresher:, resolver:) ⇒ RefreshOn401

Returns a new instance of RefreshOn401.

Parameters:



19
20
21
22
23
# File 'lib/high_level/middleware/refresh_on_401.rb', line 19

def initialize(app, refresher:, resolver:)
  super(app)
  @refresher = refresher
  @resolver = resolver
end

Instance Method Details

#call(env) ⇒ Object

Invokes the downstream stack; on a 401 attempts one refresh+retry.



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

def call(env)
  @app.call(env)
rescue HighLevel::UnauthorizedError => e
  raise e if already_retried?(env)

  resource_id = resolve_resource_id(env)
  raise e if resource_id.nil?

  new_token = @refresher.refresh_for(resource_id: resource_id)
  raise e if new_token.nil?

  mark_retried(env)
  env.request_headers["Authorization"] = "Bearer #{new_token}"
  @app.call(env)
end