utils.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. oauthlib.utils
  3. ~~~~~~~~~~~~~~
  4. This module contains utility methods used by various parts of the OAuth
  5. spec.
  6. """
  7. import urllib.request as urllib2
  8. from oauthlib.common import quote, unquote
  9. UNICODE_ASCII_CHARACTER_SET = ('abcdefghijklmnopqrstuvwxyz'
  10. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  11. '0123456789')
  12. def filter_params(target):
  13. """Decorator which filters params to remove non-oauth_* parameters
  14. Assumes the decorated method takes a params dict or list of tuples as its
  15. first argument.
  16. """
  17. def wrapper(params, *args, **kwargs):
  18. params = filter_oauth_params(params)
  19. return target(params, *args, **kwargs)
  20. wrapper.__doc__ = target.__doc__
  21. return wrapper
  22. def filter_oauth_params(params):
  23. """Removes all non oauth parameters from a dict or a list of params."""
  24. is_oauth = lambda kv: kv[0].startswith("oauth_")
  25. if isinstance(params, dict):
  26. return list(filter(is_oauth, list(params.items())))
  27. else:
  28. return list(filter(is_oauth, params))
  29. def escape(u):
  30. """Escape a unicode string in an OAuth-compatible fashion.
  31. Per `section 3.6`_ of the spec.
  32. .. _`section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  33. """
  34. if not isinstance(u, str):
  35. raise ValueError('Only unicode objects are escapable. ' +
  36. 'Got {!r} of type {}.'.format(u, type(u)))
  37. # Letters, digits, and the characters '_.-' are already treated as safe
  38. # by urllib.quote(). We need to add '~' to fully support rfc5849.
  39. return quote(u, safe=b'~')
  40. def unescape(u):
  41. if not isinstance(u, str):
  42. raise ValueError('Only unicode objects are unescapable.')
  43. return unquote(u)
  44. def parse_keqv_list(l):
  45. """A unicode-safe version of urllib2.parse_keqv_list"""
  46. # With Python 2.6, parse_http_list handles unicode fine
  47. return urllib2.parse_keqv_list(l)
  48. def parse_http_list(u):
  49. """A unicode-safe version of urllib2.parse_http_list"""
  50. # With Python 2.6, parse_http_list handles unicode fine
  51. return urllib2.parse_http_list(u)
  52. def parse_authorization_header(authorization_header):
  53. """Parse an OAuth authorization header into a list of 2-tuples"""
  54. auth_scheme = 'OAuth '.lower()
  55. if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme):
  56. items = parse_http_list(authorization_header[len(auth_scheme):])
  57. try:
  58. return list(parse_keqv_list(items).items())
  59. except (IndexError, ValueError):
  60. pass
  61. raise ValueError('Malformed authorization header')