Class: WCC::Data::FaradayClientAppTokenAuth

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/wcc/data/faraday_client_app_token_auth.rb

Defined Under Namespace

Classes: RedisCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, cache: default_cache, token_factory: method(:default_token_factory)) ⇒ FaradayClientAppTokenAuth

Returns a new instance of FaradayClientAppTokenAuth.



27
28
29
30
31
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 27

def initialize(app, cache: default_cache, token_factory: method(:default_token_factory))
  super(app)
  @cache = cache
  @token_factory = token_factory
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



25
26
27
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 25

def cache
  @cache
end

#token_factoryObject (readonly)

Returns the value of attribute token_factory.



25
26
27
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 25

def token_factory
  @token_factory
end

Instance Method Details

#call(env, retry_on_forbidden: true) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 37

def call(env, retry_on_forbidden: true)
  request_body = env[:body]
  host = env[:url].host
  env[:request_headers]["Authorization"] = "Bearer #{token_for(host)}"
  @app.call(env).on_complete do |response_env|
    response = Faraday::Response.new(response_env)
    cache[host] = nil unless response.success?
    if response.status == 403 && retry_on_forbidden
      env[:body] = request_body
      call(env, retry_on_forbidden: false)
    end
  end
end

#token_for(host) ⇒ Object



33
34
35
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 33

def token_for(host)
  @cache[host] ||= token_factory.(host)
end