Skip to content

Commit

Permalink
Add user agent header wrapper to requests handled by AuthorizedHttp (G…
Browse files Browse the repository at this point in the history
…AM-team#721)

* Revert patched google_auth_httplib2 and replace functionality by wrapping original library calls

* Wrap calls to google_auth_httplib2.Request__call__ to include a user-agent header.

* Fix bad dict key assignment syntax

* Add user agent header wrapper to requests handled by AuthorizedHttp
  • Loading branch information
ejochman authored and jay0lee committed Apr 17, 2018
1 parent bbb486f commit f8c24bf
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions src/gam.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,25 +80,32 @@
{address}
"""

# Override and wrap google_auth_httplib2.Request.__call__ so that the GAM
# Override and wrap google_auth_httplib2 request methods so that the GAM
# user-agent string is inserted into HTTP request headers.
google_auth_httplib2_request_call = google_auth_httplib2.Request.__call__
def _request_with_user_agent(self, *args, **kwargs):
"""Inserts the GAM user-agent header in all google_auth_httplib2 requests."""
def _request_with_user_agent(request_method):
"""Inserts the GAM user-agent header kwargs sent to a method."""
GAM_USER_AGENT = GAM_INFO

if kwargs.get('headers') is not None:
if kwargs['headers'].get('user-agent'):
# Save the existing user-agent header and tack on the GAM user-agent.
kwargs['headers']['user-agent'] = '%s %s' % (
GAM_USER_AGENT, kwargs.headers['user-agent'])
def wrapped_request_method(self, *args, **kwargs):
if kwargs.get('headers') is not None:
if kwargs['headers'].get('user-agent'):
if GAM_USER_AGENT not in kwargs['headers']['user-agent']:
# Save the existing user-agent header and tack on the GAM user-agent.
kwargs['headers']['user-agent'] = '%s %s' % (
GAM_USER_AGENT, kwargs['headers']['user-agent'])
else:
kwargs['headers']['user-agent'] = GAM_USER_AGENT
else:
kwargs['headers']['user-agent'] = GAM_USER_AGENT
else:
kwargs['headers'] = {'user-agent': GAM_USER_AGENT}
return google_auth_httplib2_request_call(self, *args, **kwargs)
kwargs['headers'] = {'user-agent': GAM_USER_AGENT}

return request_method(self, *args, **kwargs)

return wrapped_request_method

google_auth_httplib2.Request.__call__ = _request_with_user_agent
google_auth_httplib2.Request.__call__ = _request_with_user_agent(
google_auth_httplib2.Request.__call__)
google_auth_httplib2.AuthorizedHttp.request = _request_with_user_agent(
google_auth_httplib2.AuthorizedHttp.request)

def showUsage():
doGAMVersion(checkForArgs=False)
Expand Down

0 comments on commit f8c24bf

Please sign in to comment.