Class: WCC::Data::FaradayClientAppTokenAuth

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/wcc/data/faraday_client_app_token_auth.rb,
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.

Raises:

  • (NotSupportedError)


37
38
39
40
41
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 37

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.



35
36
37
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 35

def cache
  @cache
end

#token_factoryObject (readonly)

Returns the value of attribute token_factory.



35
36
37
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 35

def token_factory
  @token_factory
end

Instance Method Details

#call(env, retry_on_forbidden: true) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 47

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



43
44
45
# File 'lib/wcc/data/faraday_client_app_token_auth.rb', line 43

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