Joe Gregorio | 20a5aa9 | 2011-04-01 17:44:25 -0400 | [diff] [blame] | 1 | # 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. |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 14 | |
| 15 | """Utilities for OAuth. |
| 16 | |
| 17 | Utilities for making it easier to work with OAuth. |
| 18 | """ |
| 19 | |
| 20 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 21 | |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 22 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 23 | import copy |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 24 | import httplib2 |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 25 | import logging |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 26 | import oauth2 as oauth |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 27 | import urllib |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 28 | import urlparse |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 29 | from anyjson import simplejson |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 30 | |
| 31 | try: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 32 | from urlparse import parse_qsl |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 33 | except ImportError: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 34 | from cgi import parse_qsl |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 35 | |
| 36 | |
Tom Miller | 05cd4f5 | 2010-10-06 11:09:12 -0700 | [diff] [blame] | 37 | class Error(Exception): |
| 38 | """Base error for this module.""" |
| 39 | pass |
| 40 | |
| 41 | |
| 42 | class RequestError(Error): |
| 43 | """Error occurred during request.""" |
| 44 | pass |
| 45 | |
| 46 | |
| 47 | class MissingParameter(Error): |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 48 | pass |
| 49 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 50 | |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 51 | class CredentialsInvalidError(Error): |
| 52 | pass |
| 53 | |
| 54 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 55 | def _abstract(): |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 56 | raise NotImplementedError('You need to override this function') |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 57 | |
| 58 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 59 | def _oauth_uri(name, discovery, params): |
ade@google.com | a9907a2 | 2010-12-11 02:44:37 +0000 | [diff] [blame] | 60 | """Look up the OAuth URI from the discovery |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 61 | document and add query parameters based on |
| 62 | params. |
| 63 | |
| 64 | name - The name of the OAuth URI to lookup, one |
| 65 | of 'request', 'access', or 'authorize'. |
| 66 | discovery - Portion of discovery document the describes |
| 67 | the OAuth endpoints. |
| 68 | params - Dictionary that is used to form the query parameters |
| 69 | for the specified URI. |
| 70 | """ |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 71 | if name not in ['request', 'access', 'authorize']: |
| 72 | raise KeyError(name) |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 73 | keys = discovery[name]['parameters'].keys() |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 74 | query = {} |
| 75 | for key in keys: |
| 76 | if key in params: |
| 77 | query[key] = params[key] |
| 78 | return discovery[name]['url'] + '?' + urllib.urlencode(query) |
| 79 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 80 | |
| 81 | class Credentials(object): |
| 82 | """Base class for all Credentials objects. |
| 83 | |
| 84 | Subclasses must define an authorize() method |
| 85 | that applies the credentials to an HTTP transport. |
| 86 | """ |
| 87 | |
| 88 | def authorize(self, http): |
| 89 | """Take an httplib2.Http instance (or equivalent) and |
| 90 | authorizes it for the set of credentials, usually by |
| 91 | replacing http.request() with a method that adds in |
| 92 | the appropriate headers and then delegates to the original |
| 93 | Http.request() method. |
| 94 | """ |
| 95 | _abstract() |
| 96 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 97 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 98 | class Flow(object): |
| 99 | """Base class for all Flow objects.""" |
| 100 | pass |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 101 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 102 | |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 103 | class Storage(object): |
| 104 | """Base class for all Storage objects. |
| 105 | |
| 106 | Store and retrieve a single credential. |
| 107 | """ |
| 108 | |
| 109 | def get(self): |
| 110 | """Retrieve credential. |
| 111 | |
| 112 | Returns: |
| 113 | apiclient.oauth.Credentials |
| 114 | """ |
| 115 | _abstract() |
| 116 | |
| 117 | def put(self, credentials): |
| 118 | """Write a credential. |
| 119 | |
| 120 | Args: |
| 121 | credentials: Credentials, the credentials to store. |
| 122 | """ |
| 123 | _abstract() |
| 124 | |
| 125 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 126 | class OAuthCredentials(Credentials): |
| 127 | """Credentials object for OAuth 1.0a |
| 128 | """ |
| 129 | |
| 130 | def __init__(self, consumer, token, user_agent): |
| 131 | """ |
| 132 | consumer - An instance of oauth.Consumer. |
| 133 | token - An instance of oauth.Token constructed with |
| 134 | the access token and secret. |
| 135 | user_agent - The HTTP User-Agent to provide for this application. |
| 136 | """ |
| 137 | self.consumer = consumer |
| 138 | self.token = token |
| 139 | self.user_agent = user_agent |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 140 | self.store = None |
| 141 | |
| 142 | # True if the credentials have been revoked |
| 143 | self._invalid = False |
| 144 | |
| 145 | @property |
| 146 | def invalid(self): |
| 147 | """True if the credentials are invalid, such as being revoked.""" |
| 148 | return getattr(self, "_invalid", False) |
| 149 | |
| 150 | def set_store(self, store): |
| 151 | """Set the storage for the credential. |
| 152 | |
| 153 | Args: |
| 154 | store: callable, a callable that when passed a Credential |
| 155 | will store the credential back to where it came from. |
| 156 | This is needed to store the latest access_token if it |
| 157 | has been revoked. |
| 158 | """ |
| 159 | self.store = store |
| 160 | |
| 161 | def __getstate__(self): |
Joe Gregorio | 825d78d | 2011-02-18 15:07:17 -0500 | [diff] [blame] | 162 | """Trim the state down to something that can be pickled.""" |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 163 | d = copy.copy(self.__dict__) |
| 164 | del d['store'] |
| 165 | return d |
| 166 | |
| 167 | def __setstate__(self, state): |
Joe Gregorio | 825d78d | 2011-02-18 15:07:17 -0500 | [diff] [blame] | 168 | """Reconstitute the state of the object from being pickled.""" |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 169 | self.__dict__.update(state) |
| 170 | self.store = None |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 171 | |
| 172 | def authorize(self, http): |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 173 | """Authorize an httplib2.Http instance with these Credentials |
| 174 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 175 | Args: |
| 176 | http - An instance of httplib2.Http |
| 177 | or something that acts like it. |
| 178 | |
| 179 | Returns: |
| 180 | A modified instance of http that was passed in. |
| 181 | |
| 182 | Example: |
| 183 | |
| 184 | h = httplib2.Http() |
| 185 | h = credentials.authorize(h) |
| 186 | |
| 187 | You can't create a new OAuth |
| 188 | subclass of httplib2.Authenication because |
| 189 | it never gets passed the absolute URI, which is |
| 190 | needed for signing. So instead we have to overload |
| 191 | 'request' with a closure that adds in the |
| 192 | Authorization header and then calls the original version |
| 193 | of 'request()'. |
| 194 | """ |
| 195 | request_orig = http.request |
| 196 | signer = oauth.SignatureMethod_HMAC_SHA1() |
| 197 | |
| 198 | # The closure that will replace 'httplib2.Http.request'. |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 199 | def new_request(uri, method='GET', body=None, headers=None, |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 200 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 201 | connection_type=None): |
| 202 | """Modify the request headers to add the appropriate |
| 203 | Authorization header.""" |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 204 | response_code = 302 |
| 205 | http.follow_redirects = False |
| 206 | while response_code in [301, 302]: |
| 207 | req = oauth.Request.from_consumer_and_token( |
| 208 | self.consumer, self.token, http_method=method, http_url=uri) |
| 209 | req.sign_request(signer, self.consumer, self.token) |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 210 | if headers is None: |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 211 | headers = {} |
| 212 | headers.update(req.to_header()) |
| 213 | if 'user-agent' in headers: |
| 214 | headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] |
| 215 | else: |
| 216 | headers['user-agent'] = self.user_agent |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 217 | |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 218 | resp, content = request_orig(uri, method, body, headers, |
| 219 | redirections, connection_type) |
| 220 | response_code = resp.status |
| 221 | if response_code in [301, 302]: |
| 222 | uri = resp['location'] |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 223 | |
| 224 | # Update the stored credential if it becomes invalid. |
| 225 | if response_code == 401: |
| 226 | logging.info('Access token no longer valid: %s' % content) |
| 227 | self._invalid = True |
| 228 | if self.store is not None: |
| 229 | self.store(self) |
| 230 | raise CredentialsInvalidError("Credentials are no longer valid.") |
| 231 | |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 232 | return resp, content |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 233 | |
| 234 | http.request = new_request |
| 235 | return http |
| 236 | |
| 237 | |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 238 | class TwoLeggedOAuthCredentials(Credentials): |
| 239 | """Two Legged Credentials object for OAuth 1.0a. |
| 240 | |
| 241 | The Two Legged object is created directly, not from a flow. Once you |
| 242 | authorize and httplib2.Http instance you can change the requestor and that |
| 243 | change will propogate to the authorized httplib2.Http instance. For example: |
| 244 | |
| 245 | http = httplib2.Http() |
| 246 | http = credentials.authorize(http) |
| 247 | |
| 248 | credentials.requestor = 'foo@example.info' |
| 249 | http.request(...) |
| 250 | credentials.requestor = 'bar@example.info' |
| 251 | http.request(...) |
| 252 | """ |
| 253 | |
| 254 | def __init__(self, consumer_key, consumer_secret, user_agent): |
| 255 | """ |
| 256 | Args: |
| 257 | consumer_key: string, An OAuth 1.0 consumer key |
| 258 | consumer_secret: string, An OAuth 1.0 consumer secret |
| 259 | user_agent: string, The HTTP User-Agent to provide for this application. |
| 260 | """ |
| 261 | self.consumer = oauth.Consumer(consumer_key, consumer_secret) |
| 262 | self.user_agent = user_agent |
| 263 | self.store = None |
| 264 | |
| 265 | # email address of the user to act on the behalf of. |
| 266 | self._requestor = None |
| 267 | |
| 268 | @property |
| 269 | def invalid(self): |
| 270 | """True if the credentials are invalid, such as being revoked. |
| 271 | |
| 272 | Always returns False for Two Legged Credentials. |
| 273 | """ |
| 274 | return False |
| 275 | |
| 276 | def getrequestor(self): |
| 277 | return self._requestor |
| 278 | |
| 279 | def setrequestor(self, email): |
| 280 | self._requestor = email |
| 281 | |
| 282 | requestor = property(getrequestor, setrequestor, None, |
| 283 | 'The email address of the user to act on behalf of') |
| 284 | |
| 285 | def set_store(self, store): |
| 286 | """Set the storage for the credential. |
| 287 | |
| 288 | Args: |
| 289 | store: callable, a callable that when passed a Credential |
| 290 | will store the credential back to where it came from. |
| 291 | This is needed to store the latest access_token if it |
| 292 | has been revoked. |
| 293 | """ |
| 294 | self.store = store |
| 295 | |
| 296 | def __getstate__(self): |
| 297 | """Trim the state down to something that can be pickled.""" |
| 298 | d = copy.copy(self.__dict__) |
| 299 | del d['store'] |
| 300 | return d |
| 301 | |
| 302 | def __setstate__(self, state): |
| 303 | """Reconstitute the state of the object from being pickled.""" |
| 304 | self.__dict__.update(state) |
| 305 | self.store = None |
| 306 | |
| 307 | def authorize(self, http): |
| 308 | """Authorize an httplib2.Http instance with these Credentials |
| 309 | |
| 310 | Args: |
| 311 | http - An instance of httplib2.Http |
| 312 | or something that acts like it. |
| 313 | |
| 314 | Returns: |
| 315 | A modified instance of http that was passed in. |
| 316 | |
| 317 | Example: |
| 318 | |
| 319 | h = httplib2.Http() |
| 320 | h = credentials.authorize(h) |
| 321 | |
| 322 | You can't create a new OAuth |
| 323 | subclass of httplib2.Authenication because |
| 324 | it never gets passed the absolute URI, which is |
| 325 | needed for signing. So instead we have to overload |
| 326 | 'request' with a closure that adds in the |
| 327 | Authorization header and then calls the original version |
| 328 | of 'request()'. |
| 329 | """ |
| 330 | request_orig = http.request |
| 331 | signer = oauth.SignatureMethod_HMAC_SHA1() |
| 332 | |
| 333 | # The closure that will replace 'httplib2.Http.request'. |
| 334 | def new_request(uri, method='GET', body=None, headers=None, |
| 335 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 336 | connection_type=None): |
| 337 | """Modify the request headers to add the appropriate |
| 338 | Authorization header.""" |
| 339 | response_code = 302 |
| 340 | http.follow_redirects = False |
| 341 | while response_code in [301, 302]: |
| 342 | # add in xoauth_requestor_id=self._requestor to the uri |
| 343 | if self._requestor is None: |
| 344 | raise MissingParameter( |
| 345 | 'Requestor must be set before using TwoLeggedOAuthCredentials') |
| 346 | parsed = list(urlparse.urlparse(uri)) |
| 347 | q = parse_qsl(parsed[4]) |
| 348 | q.append(('xoauth_requestor_id', self._requestor)) |
| 349 | parsed[4] = urllib.urlencode(q) |
| 350 | uri = urlparse.urlunparse(parsed) |
| 351 | |
| 352 | req = oauth.Request.from_consumer_and_token( |
| 353 | self.consumer, None, http_method=method, http_url=uri) |
| 354 | req.sign_request(signer, self.consumer, None) |
| 355 | if headers is None: |
| 356 | headers = {} |
| 357 | headers.update(req.to_header()) |
| 358 | if 'user-agent' in headers: |
| 359 | headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] |
| 360 | else: |
| 361 | headers['user-agent'] = self.user_agent |
| 362 | resp, content = request_orig(uri, method, body, headers, |
| 363 | redirections, connection_type) |
| 364 | response_code = resp.status |
| 365 | if response_code in [301, 302]: |
| 366 | uri = resp['location'] |
| 367 | |
| 368 | if response_code == 401: |
| 369 | logging.info('Access token no longer valid: %s' % content) |
| 370 | # Do not store the invalid state of the Credentials because |
| 371 | # being 2LO they could be reinstated in the future. |
| 372 | raise CredentialsInvalidError("Credentials are invalid.") |
| 373 | |
| 374 | return resp, content |
| 375 | |
| 376 | http.request = new_request |
| 377 | return http |
| 378 | |
| 379 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 380 | class FlowThreeLegged(Flow): |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 381 | """Does the Three Legged Dance for OAuth 1.0a. |
| 382 | """ |
| 383 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 384 | def __init__(self, discovery, consumer_key, consumer_secret, user_agent, |
| 385 | **kwargs): |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 386 | """ |
| 387 | discovery - Section of the API discovery document that describes |
| 388 | the OAuth endpoints. |
| 389 | consumer_key - OAuth consumer key |
| 390 | consumer_secret - OAuth consumer secret |
| 391 | user_agent - The HTTP User-Agent that identifies the application. |
| 392 | **kwargs - The keyword arguments are all optional and required |
| 393 | parameters for the OAuth calls. |
| 394 | """ |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 395 | self.discovery = discovery |
| 396 | self.consumer_key = consumer_key |
| 397 | self.consumer_secret = consumer_secret |
| 398 | self.user_agent = user_agent |
| 399 | self.params = kwargs |
| 400 | self.request_token = {} |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 401 | required = {} |
| 402 | for uriinfo in discovery.itervalues(): |
| 403 | for name, value in uriinfo['parameters'].iteritems(): |
| 404 | if value['required'] and not name.startswith('oauth_'): |
| 405 | required[name] = 1 |
| 406 | for key in required.iterkeys(): |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 407 | if key not in self.params: |
| 408 | raise MissingParameter('Required parameter %s not supplied' % key) |
| 409 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 410 | def step1_get_authorize_url(self, oauth_callback='oob'): |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 411 | """Returns a URI to redirect to the provider. |
| 412 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 413 | oauth_callback - Either the string 'oob' for a non-web-based application, |
| 414 | or a URI that handles the callback from the authorization |
| 415 | server. |
| 416 | |
| 417 | If oauth_callback is 'oob' then pass in the |
| 418 | generated verification code to step2_exchange, |
| 419 | otherwise pass in the query parameters received |
| 420 | at the callback uri to step2_exchange. |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 421 | """ |
| 422 | consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) |
| 423 | client = oauth.Client(consumer) |
| 424 | |
| 425 | headers = { |
| 426 | 'user-agent': self.user_agent, |
| 427 | 'content-type': 'application/x-www-form-urlencoded' |
| 428 | } |
| 429 | body = urllib.urlencode({'oauth_callback': oauth_callback}) |
| 430 | uri = _oauth_uri('request', self.discovery, self.params) |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 431 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 432 | resp, content = client.request(uri, 'POST', headers=headers, |
| 433 | body=body) |
| 434 | if resp['status'] != '200': |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 435 | logging.error('Failed to retrieve temporary authorization: %s', content) |
Tom Miller | 05cd4f5 | 2010-10-06 11:09:12 -0700 | [diff] [blame] | 436 | raise RequestError('Invalid response %s.' % resp['status']) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 437 | |
| 438 | self.request_token = dict(parse_qsl(content)) |
| 439 | |
| 440 | auth_params = copy.copy(self.params) |
| 441 | auth_params['oauth_token'] = self.request_token['oauth_token'] |
| 442 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 443 | return _oauth_uri('authorize', self.discovery, auth_params) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 444 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 445 | def step2_exchange(self, verifier): |
| 446 | """Exhanges an authorized request token |
| 447 | for OAuthCredentials. |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 448 | |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 449 | Args: |
| 450 | verifier: string, dict - either the verifier token, or a dictionary |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 451 | of the query parameters to the callback, which contains |
| 452 | the oauth_verifier. |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 453 | Returns: |
| 454 | The Credentials object. |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 455 | """ |
| 456 | |
| 457 | if not (isinstance(verifier, str) or isinstance(verifier, unicode)): |
| 458 | verifier = verifier['oauth_verifier'] |
| 459 | |
| 460 | token = oauth.Token( |
| 461 | self.request_token['oauth_token'], |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 462 | self.request_token['oauth_token_secret']) |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 463 | token.set_verifier(verifier) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 464 | consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) |
| 465 | client = oauth.Client(consumer, token) |
| 466 | |
| 467 | headers = { |
| 468 | 'user-agent': self.user_agent, |
| 469 | 'content-type': 'application/x-www-form-urlencoded' |
| 470 | } |
| 471 | |
| 472 | uri = _oauth_uri('access', self.discovery, self.params) |
| 473 | resp, content = client.request(uri, 'POST', headers=headers) |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 474 | if resp['status'] != '200': |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 475 | logging.error('Failed to retrieve access token: %s', content) |
Tom Miller | 05cd4f5 | 2010-10-06 11:09:12 -0700 | [diff] [blame] | 476 | raise RequestError('Invalid response %s.' % resp['status']) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 477 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 478 | oauth_params = dict(parse_qsl(content)) |
| 479 | token = oauth.Token( |
| 480 | oauth_params['oauth_token'], |
| 481 | oauth_params['oauth_token_secret']) |
| 482 | |
| 483 | return OAuthCredentials(consumer, token, self.user_agent) |