facebook.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. from json import dumps
  2. try:
  3. from urlparse import parse_qsl
  4. except ImportError:
  5. from urllib.parse import parse_qsl
  6. from oauthlib.common import to_unicode
  7. def facebook_compliance_fix(session):
  8. def _compliance_fix(r):
  9. # if Facebook claims to be sending us json, let's trust them.
  10. if "application/json" in r.headers.get("content-type", {}):
  11. return r
  12. # Facebook returns a content-type of text/plain when sending their
  13. # x-www-form-urlencoded responses, along with a 200. If not, let's
  14. # assume we're getting JSON and bail on the fix.
  15. if "text/plain" in r.headers.get("content-type", {}) and r.status_code == 200:
  16. token = dict(parse_qsl(r.text, keep_blank_values=True))
  17. else:
  18. return r
  19. expires = token.get("expires")
  20. if expires is not None:
  21. token["expires_in"] = expires
  22. token["token_type"] = "Bearer"
  23. r._content = to_unicode(dumps(token)).encode("UTF-8")
  24. return r
  25. session.register_compliance_hook("access_token_response", _compliance_fix)
  26. return session