oauth2_auth.py 1.5 KB

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