Skip to content

Commit

Permalink
feat: add support for different types of credentials to REST
Browse files Browse the repository at this point in the history
  • Loading branch information
viacheslav-rostovtsev committed Nov 8, 2022
1 parent d69e6b8 commit a6c5574
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions gapic-common/lib/gapic/rest/faraday_middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,43 @@ module Rest
# Registers the middleware with Faraday
module FaradayMiddleware
##
# @private
# Request middleware that constructs the Authorization HTTP header
# using ::Google::Auth::Credentials
#
class GoogleAuthorization < Faraday::Middleware
##
# @private
# @param app [#call]
# @param credentials [::Google::Auth::Credentials]
# @param credentials [Google::Auth::Credentials, Signet::OAuth2::Client, Symbol, Proc]
# Provides the means for authenticating requests made by
# the client. This parameter can be many types:
# * A `Google::Auth::Credentials` uses a the properties of its represented keyfile for authenticating requests
# made by this client.
# * A `Signet::OAuth2::Client` object used to apply the OAuth credentials.
# * A `Proc` will be used as an updater_proc for the auth token.
# * A `Symbol` is treated as a signal that authentication is not required.
#
def initialize app, credentials
@credentials = credentials
@updater_proc = case credentials
when Symbol
credentials
else
updater_proc = credentials.updater_proc if credentials.respond_to? :updater_proc
updater_proc ||= credentials if credentials.is_a? Proc
raise ArgumentError, "invalid credentials (#{credentials.class})" if updater_proc.nil?
updater_proc
end
super app
end

# @private
# @param env [Faraday::Env]
def call env
auth_hash = @credentials.client.apply({})
env.request_headers["Authorization"] = auth_hash[:authorization]
unless @updater_proc.is_a? Symbol
auth_hash = @updater_proc.call({})
env.request_headers["Authorization"] = auth_hash[:authorization]
end

@app.call env
end
Expand Down

0 comments on commit a6c5574

Please sign in to comment.