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, (tuple, list)):
28 return " ".join([unicode_type(s) for s in scope])
29 elif isinstance(scope, set):
30 return list_to_scope(list(scope))
32 raise ValueError("Invalid scope, must be string or list.")
35 def scope_to_list(scope):
36 """Convert a space separated string to a list of scopes."""
37 if isinstance(scope, list):
38 return [unicode_type(s) for s in scope]
39 if isinstance(scope, set):
40 scope_to_list(list(scope))
44 return scope.strip().split(" ")
47 def params_from_uri(uri):
48 params = dict(urldecode(urlparse(uri).query))
50 params['scope'] = scope_to_list(params['scope'])
54 def host_from_uri(uri):
55 """Extract hostname and port from URI.
57 Will use default port for HTTP and HTTPS if none is present in the URI.
64 sch, netloc, path, par, query, fra = urlparse(uri)
66 netloc, port = netloc.split(':', 1)
68 port = default_ports.get(sch.upper())
74 """Escape a string in an OAuth-compatible fashion.
76 TODO: verify whether this can in fact be used for OAuth 2
79 if not isinstance(u, unicode_type):
80 raise ValueError('Only unicode objects are escapable.')
81 return quote(u.encode('utf-8'), safe=b'~')
84 def generate_age(issue_time):
85 """Generate a age parameter for MAC authentication draft 00."""
86 td = datetime.datetime.now() - issue_time
87 age = (td.microseconds + (td.seconds + td.days * 24 * 3600)
89 return unicode_type(age)
92 def is_secure_transport(uri):
93 """Check if the uri is over ssl."""
94 if os.environ.get('OAUTHLIB_INSECURE_TRANSPORT'):
96 return uri.lower().startswith('https://')