Skip to content

Commit

Permalink
Callable authorizers (lostisland#1345)
Browse files Browse the repository at this point in the history
  • Loading branch information
sled authored and jrochkind committed Dec 20, 2021
1 parent 8ca1f5e commit 7b03dda
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/faraday/request/authorization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ class Authorization < Faraday::Middleware

# @param app [#call]
# @param type [String, Symbol] Type of Authorization
# @param params [Array<String, Proc>] parameters to build the Authorization header.
# @param params [Array<String, Proc, #call>] parameters to build the Authorization header.
# If the type is `:basic`, then these can be a login and password pair.
# Otherwise, a single value is expected that will be appended after the type.
# This value can be a proc, in which case it will be invoked on each request.
# This value can be a proc or an object responding to `.call`, in which case
# it will be invoked on each request.
def initialize(app, type, *params)
@type = type
@params = params
Expand All @@ -37,7 +38,7 @@ def header_from(type, *params)
raise ArgumentError, "Unexpected params received (got #{params.size} instead of 1)"
else
value = params.first
value = value.call if value.is_a?(Proc)
value = value.call if value.is_a?(Proc) || value.respond_to?(:call)
"#{type} #{value}"
end
end
Expand Down
9 changes: 9 additions & 0 deletions spec/faraday/request/authorization_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@
include_examples 'does not interfere with existing authentication'
end

context 'when passed a callable' do
let(:callable) { double('Callable Authorizer', call: 'custom_from_callable') }
let(:auth_config) { [callable] }

it { expect(response.body).to eq('Bearer custom_from_callable') }

include_examples 'does not interfere with existing authentication'
end

context 'when passed too many arguments' do
let(:auth_config) { %w[baz foo] }

Expand Down

0 comments on commit 7b03dda

Please sign in to comment.