ignore the __pychache__ directory
[yelp-api-cdsw] / requests_oauthlib / oauth1_auth.py
1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
3 from oauthlib.common import extract_params
4 from oauthlib.oauth1 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
5
6 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
7 CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
8
9 import sys
10 if sys.version > "3":
11     unicode = str
12
13     def to_native_str(string):
14         return string.decode('utf-8')
15 else:
16     def to_native_str(string):
17         return string
18
19 # OBS!: Correct signing of requests are conditional on invoking OAuth1
20 # as the last step of preparing a request, or at least having the
21 # content-type set properly.
22 class OAuth1(object):
23     """Signs the request using OAuth 1 (RFC5849)"""
24     def __init__(self, client_key,
25             client_secret=None,
26             resource_owner_key=None,
27             resource_owner_secret=None,
28             callback_uri=None,
29             signature_method=SIGNATURE_HMAC,
30             signature_type=SIGNATURE_TYPE_AUTH_HEADER,
31             rsa_key=None, verifier=None,
32             decoding='utf-8'):
33
34         try:
35             signature_type = signature_type.upper()
36         except AttributeError:
37             pass
38
39         self.client = Client(client_key, client_secret, resource_owner_key,
40             resource_owner_secret, callback_uri, signature_method,
41             signature_type, rsa_key, verifier, decoding=decoding)
42
43     def __call__(self, r):
44         """Add OAuth parameters to the request.
45
46         Parameters may be included from the body if the content-type is
47         urlencoded, if no content type is set a guess is made.
48         """
49         # Overwriting url is safe here as request will not modify it past
50         # this point.
51
52         content_type = r.headers.get('Content-Type', '')
53         if not content_type and extract_params(r.body):
54             content_type = CONTENT_TYPE_FORM_URLENCODED
55         if not isinstance(content_type, unicode):
56             content_type = content_type.decode('utf-8')
57
58         is_form_encoded = (CONTENT_TYPE_FORM_URLENCODED in content_type)
59
60         if is_form_encoded:
61             r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED
62             r.url, headers, r.body = self.client.sign(
63                 unicode(r.url), unicode(r.method), r.body or '', r.headers)
64         else:
65             # Omit body data in the signing of non form-encoded requests
66             r.url, headers, _ = self.client.sign(
67                 unicode(r.url), unicode(r.method), None, r.headers)
68
69         r.prepare_headers(headers)
70         r.url = to_native_str(r.url)
71         return r

Benjamin Mako Hill || Want to submit a patch?