oauth2_auth.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
  2. from oauthlib.oauth2 import is_secure_transport
  3. from requests.auth import AuthBase
  4. class OAuth2(AuthBase):
  5. """Adds proof of authorization (OAuth2 token) to the request."""
  6. def __init__(self, client_id=None, client=None, token=None):
  7. """Construct a new OAuth 2 authorization object.
  8. :param client_id: Client id obtained during registration
  9. :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
  10. WebApplicationClient which is useful for any
  11. hosted application but not mobile or desktop.
  12. :param token: Token dictionary, must include access_token
  13. and token_type.
  14. """
  15. self._client = client or WebApplicationClient(client_id, token=token)
  16. if token:
  17. for k, v in token.items():
  18. setattr(self._client, k, v)
  19. def __call__(self, r):
  20. """Append an OAuth 2 token to the request.
  21. Note that currently HTTPS is required for all requests. There may be
  22. a token type that allows for plain HTTP in the future and then this
  23. should be updated to allow plain HTTP on a white list basis.
  24. """
  25. if not is_secure_transport(r.url):
  26. raise InsecureTransportError()
  27. r.url, r.headers, r.body = self._client.add_token(
  28. r.url, http_method=r.method, body=r.body, headers=r.headers
  29. )
  30. return r