utils.py 2.4 KB

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