blob: 2c0786f8ec5ee16fbee9723930e647c802b07923 [file] [log] [blame]
ade@google.com85f1a022010-08-19 00:02:59 +01001# Copyright (C) 2010 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import httplib2
16import oauth2 as oauth
17import simplejson
18
19
20def oauth_wrap(consumer, token, http):
21 """
22 Args:
23 http - An instance of httplib2.Http
24 or something that acts like it.
25
26 Returns:
27 A modified instance of http that was passed in.
28
29 Example:
30
31 h = httplib2.Http()
32 h = oauth_wrap(h)
33
34 Grumble. You can't create a new OAuth
35 subclass of httplib2.Authenication because
36 it never gets passed the absolute URI, which is
37 needed for signing. So instead we have to overload
38 'request' with a closure that adds in the
39 Authorization header and then calls the original version
40 of 'request().
41 """
42 request_orig = http.request
43 signer = oauth.SignatureMethod_HMAC_SHA1()
44
45 def new_request(uri, method='GET', body=None, headers=None,
46 redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
47 """Modify the request headers to add the appropriate
48 Authorization header."""
49 req = oauth.Request.from_consumer_and_token(
50 consumer, token, http_method=method, http_url=uri)
51 req.sign_request(signer, consumer, token)
52 if headers == None:
53 headers = {}
54 headers.update(req.to_header())
55 headers['user-agent'] = 'jcgregorio-test-client'
56 return request_orig(uri, method, body, headers, redirections,
57 connection_type)
58
59 http.request = new_request
60 return http
61
62def get_authorised_http(oauth_params):
63 consumer = oauth.Consumer(oauth_params['consumer_key'],
64 oauth_params['consumer_secret'])
65 token = oauth.Token(oauth_params['oauth_token'],
66 oauth_params['oauth_token_secret'])
67
68 # Create a simple monkeypatch for httplib2.Http.request
69 # just adds in the oauth authorization header and then calls
70 # the original request().
71 http = httplib2.Http()
72 return oauth_wrap(consumer, token, http)
73
74def get_wrapped_http(filename='oauth_token.dat'):
75 f = open(filename, 'r')
76 oauth_params = simplejson.loads(f.read())
77
78 return get_authorised_http(oauth_params)