import oauthlib (a dependency of the project)
[yelp-api-cdsw] / oauthlib / oauth2 / rfc6749 / utils.py
1 # -*- coding: utf-8 -*-
2 """
3 oauthlib.utils
4 ~~~~~~~~~~~~~~
5
6 This module contains utility methods used by various parts of the OAuth 2 spec.
7 """
8 from __future__ import absolute_import, unicode_literals
9
10 import os
11 import datetime
12 try:
13     from urllib import quote
14 except ImportError:
15     from urllib.parse import quote
16 try:
17     from urlparse import urlparse
18 except ImportError:
19     from urllib.parse import urlparse
20 from oauthlib.common import unicode_type, urldecode
21
22
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:
26         return scope
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))
31     else:
32         raise ValueError("Invalid scope, must be string or list.")
33
34
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))
41     elif scope is None:
42         return None
43     else:
44         return scope.strip().split(" ")
45
46
47 def params_from_uri(uri):
48     params = dict(urldecode(urlparse(uri).query))
49     if 'scope' in params:
50         params['scope'] = scope_to_list(params['scope'])
51     return params
52
53
54 def host_from_uri(uri):
55     """Extract hostname and port from URI.
56
57     Will use default port for HTTP and HTTPS if none is present in the URI.
58     """
59     default_ports = {
60         'HTTP': '80',
61         'HTTPS': '443',
62     }
63
64     sch, netloc, path, par, query, fra = urlparse(uri)
65     if ':' in netloc:
66         netloc, port = netloc.split(':', 1)
67     else:
68         port = default_ports.get(sch.upper())
69
70     return netloc, port
71
72
73 def escape(u):
74     """Escape a string in an OAuth-compatible fashion.
75
76     TODO: verify whether this can in fact be used for OAuth 2
77
78     """
79     if not isinstance(u, unicode_type):
80         raise ValueError('Only unicode objects are escapable.')
81     return quote(u.encode('utf-8'), safe=b'~')
82
83
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)
88            * 10 ** 6) / 10 ** 6
89     return unicode_type(age)
90
91
92 def is_secure_transport(uri):
93     """Check if the uri is over ssl."""
94     if os.environ.get('OAUTHLIB_INSECURE_TRANSPORT'):
95         return True
96     return uri.lower().startswith('https://')

Benjamin Mako Hill || Want to submit a patch?