1 # -*- coding: utf-8 -*-
6 This module contains utility methods used by various parts of the OAuth
9 from __future__ import absolute_import, unicode_literals
14 import urllib.request as urllib2
16 from oauthlib.common import quote, unquote, bytes_type, unicode_type
18 UNICODE_ASCII_CHARACTER_SET = ('abcdefghijklmnopqrstuvwxyz'
19 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
23 def filter_params(target):
24 """Decorator which filters params to remove non-oauth_* parameters
26 Assumes the decorated method takes a params dict or list of tuples as its
29 def wrapper(params, *args, **kwargs):
30 params = filter_oauth_params(params)
31 return target(params, *args, **kwargs)
33 wrapper.__doc__ = target.__doc__
37 def filter_oauth_params(params):
38 """Removes all non oauth parameters from a dict or a list of params."""
39 is_oauth = lambda kv: kv[0].startswith("oauth_")
40 if isinstance(params, dict):
41 return list(filter(is_oauth, list(params.items())))
43 return list(filter(is_oauth, params))
47 """Escape a unicode string in an OAuth-compatible fashion.
49 Per `section 3.6`_ of the spec.
51 .. _`section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6
54 if not isinstance(u, unicode_type):
55 raise ValueError('Only unicode objects are escapable. ' +
56 'Got %s of type %s.' % (u, type(u)))
57 # Letters, digits, and the characters '_.-' are already treated as safe
58 # by urllib.quote(). We need to add '~' to fully support rfc5849.
59 return quote(u, safe=b'~')
63 if not isinstance(u, unicode_type):
64 raise ValueError('Only unicode objects are unescapable.')
68 def parse_keqv_list(l):
69 """A unicode-safe version of urllib2.parse_keqv_list"""
70 # With Python 2.6, parse_http_list handles unicode fine
71 return urllib2.parse_keqv_list(l)
74 def parse_http_list(u):
75 """A unicode-safe version of urllib2.parse_http_list"""
76 # With Python 2.6, parse_http_list handles unicode fine
77 return urllib2.parse_http_list(u)
80 def parse_authorization_header(authorization_header):
81 """Parse an OAuth authorization header into a list of 2-tuples"""
82 auth_scheme = 'OAuth '.lower()
83 if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme):
84 items = parse_http_list(authorization_header[len(auth_scheme):])
86 return list(parse_keqv_list(items).items())
87 except (IndexError, ValueError):
89 raise ValueError('Malformed authorization header')