utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. oauthlib.utils
  3. ~~~~~~~~~~~~~~
  4. This module contains utility methods used by various parts of the OAuth 2 spec.
  5. """
  6. import datetime
  7. import os
  8. from urllib.parse import quote, urlparse
  9. from oauthlib.common import urldecode
  10. def list_to_scope(scope):
  11. """Convert a list of scopes to a space separated string."""
  12. if isinstance(scope, str) or scope is None:
  13. return scope
  14. elif isinstance(scope, (set, tuple, list)):
  15. return " ".join([str(s) for s in scope])
  16. else:
  17. raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope)
  18. def scope_to_list(scope):
  19. """Convert a space separated string to a list of scopes."""
  20. if isinstance(scope, (tuple, list, set)):
  21. return [str(s) for s in scope]
  22. elif scope is None:
  23. return None
  24. else:
  25. return scope.strip().split(" ")
  26. def params_from_uri(uri):
  27. params = dict(urldecode(urlparse(uri).query))
  28. if 'scope' in params:
  29. params['scope'] = scope_to_list(params['scope'])
  30. return params
  31. def host_from_uri(uri):
  32. """Extract hostname and port from URI.
  33. Will use default port for HTTP and HTTPS if none is present in the URI.
  34. """
  35. default_ports = {
  36. 'HTTP': '80',
  37. 'HTTPS': '443',
  38. }
  39. sch, netloc, path, par, query, fra = urlparse(uri)
  40. if ':' in netloc:
  41. netloc, port = netloc.split(':', 1)
  42. else:
  43. port = default_ports.get(sch.upper())
  44. return netloc, port
  45. def escape(u):
  46. """Escape a string in an OAuth-compatible fashion.
  47. TODO: verify whether this can in fact be used for OAuth 2
  48. """
  49. if not isinstance(u, str):
  50. raise ValueError('Only unicode objects are escapable.')
  51. return quote(u.encode('utf-8'), safe=b'~')
  52. def generate_age(issue_time):
  53. """Generate a age parameter for MAC authentication draft 00."""
  54. td = datetime.datetime.now() - issue_time
  55. age = (td.microseconds + (td.seconds + td.days * 24 * 3600)
  56. * 10 ** 6) / 10 ** 6
  57. return str(age)
  58. def is_secure_transport(uri):
  59. """Check if the uri is over ssl."""
  60. if os.environ.get('OAUTHLIB_INSECURE_TRANSPORT'):
  61. return True
  62. return uri.lower().startswith('https://')