@@ -104,10 +104,31 @@ def initialize
104104 add_warning_callback
105105 end
106106
107+ # token impersonation for the scope of the block
108+ # @param [String] username The username (email) of the user to impersonate
109+ # @yield The block to run while impersonating the user
110+ # @example
111+ # client.api_token_impersonate("[email protected] ") do 112+ # client.tickets.create(:subject => "Help!")
113+ # end
114+ #
115+ # # creates a ticket on behalf of otheruser
116+ # @return
117+ # yielded value
118+ def api_token_impersonate ( username )
119+ Thread . current [ :local_connection ] = build_connection ( username )
120+ yield
121+ ensure
122+ Thread . current [ :local_connection ] = nil
123+ end
124+
107125 # Creates a connection if there is none, otherwise returns the existing connection.
108126 #
109127 # @return [Faraday::Connection] Faraday connection for the client
110128 def connection
129+ if Thread . current [ :local_connection ]
130+ return Thread . current [ :local_connection ]
131+ end
111132 @connection ||= build_connection
112133 end
113134
@@ -142,7 +163,7 @@ def self.check_deprecated_namespace_usage(attributes, name)
142163 # Request logger if logger is not nil
143164 #
144165 # Retry middleware if retry is true
145- def build_connection
166+ def build_connection ( username = nil )
146167 Faraday . new ( config . options ) do |builder |
147168 # response
148169 builder . use ZendeskAPI ::Middleware ::Response ::RaiseError
@@ -158,7 +179,7 @@ def build_connection
158179 builder . use ZendeskAPI ::Middleware ::Response ::Deflate
159180 end
160181
161- set_authentication ( builder , config )
182+ set_authentication ( builder , config , username )
162183
163184 if config . cache
164185 builder . use ZendeskAPI ::Middleware ::Request ::EtagCache , :cache => config . cache
@@ -206,7 +227,6 @@ def set_raise_error_when_rated_limited
206227
207228 def set_token_auth
208229 return if config . password || config . token . nil?
209-
210230 if config . username . nil?
211231 raise ArgumentError , "you need to provide a username when using API token auth"
212232 else
@@ -234,13 +254,13 @@ def add_warning_callback
234254 end
235255
236256 # See https://lostisland.github.io/faraday/middleware/authentication
237- def set_authentication ( builder , config )
257+ def set_authentication ( builder , config , username = nil )
238258 if config . access_token && !config . url_based_access_token
239259 builder . request :authorization , "Bearer" , config . access_token
240260 elsif config . access_token
241261 builder . use ZendeskAPI ::Middleware ::Request ::UrlBasedAccessToken , config . access_token
242262 else
243- builder . request :authorization , :basic , config . username , config . password
263+ builder . request :authorization , :basic , username ? " #{ username } /token" : config . username , config . password
244264 end
245265 end
246266 end
0 commit comments