1 # -*- coding: utf-8 -*-
6 This module contains utility methods used by various parts of the OAuth 2 spec.
8 from __future__ import absolute_import, unicode_literals
13 from urllib import quote
15 from urllib.parse import quote
17 from urlparse import urlparse
19 from urllib.parse import urlparse
20 from oauthlib.common import unicode_type, urldecode
23 def list_to_scope(scope):
24 """Convert a list of scopes to a space separated string."""
25 if isinstance(scope, unicode_type) or scope is None:
27 elif isinstance(scope, (set, tuple, list)):
28 return " ".join([unicode_type(s) for s in scope])
30 raise ValueError("Invalid scope (%s), must be string, tuple, set, or list." % scope)
33 def scope_to_list(scope):
34 """Convert a space separated string to a list of scopes."""
35 if isinstance(scope, (tuple, list, set)):
36 return [unicode_type(s) for s in scope]
40 return scope.strip().split(" ")
43 def params_from_uri(uri):
44 params = dict(urldecode(urlparse(uri).query))
46 params['scope'] = scope_to_list(params['scope'])
50 def host_from_uri(uri):
51 """Extract hostname and port from URI.
53 Will use default port for HTTP and HTTPS if none is present in the URI.
60 sch, netloc, path, par, query, fra = urlparse(uri)
62 netloc, port = netloc.split(':', 1)
64 port = default_ports.get(sch.upper())
70 """Escape a string in an OAuth-compatible fashion.
72 TODO: verify whether this can in fact be used for OAuth 2
75 if not isinstance(u, unicode_type):
76 raise ValueError('Only unicode objects are escapable.')
77 return quote(u.encode('utf-8'), safe=b'~')
80 def generate_age(issue_time):
81 """Generate a age parameter for MAC authentication draft 00."""
82 td = datetime.datetime.now() - issue_time
83 age = (td.microseconds + (td.seconds + td.days * 24 * 3600)
85 return unicode_type(age)
88 def is_secure_transport(uri):
89 """Check if the uri is over ssl."""
90 if os.environ.get('OAUTHLIB_INSECURE_TRANSPORT'):
92 return uri.lower().startswith('https://')