Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 1 | # Copyright 2010 Google Inc. All Rights Reserved. |
| 2 | |
| 3 | """Utilities for OAuth. |
| 4 | |
| 5 | Utilities for making it easier to work with OAuth. |
| 6 | """ |
| 7 | |
| 8 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 9 | |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 10 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 11 | import copy |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 12 | import httplib2 |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 13 | import logging |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 14 | import oauth2 as oauth |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 15 | import urllib |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 16 | import urlparse |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 17 | from anyjson import simplejson |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 18 | |
| 19 | try: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 20 | from urlparse import parse_qsl |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 21 | except ImportError: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 22 | from cgi import parse_qsl |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 23 | |
| 24 | |
Tom Miller | 05cd4f5 | 2010-10-06 11:09:12 -0700 | [diff] [blame] | 25 | class Error(Exception): |
| 26 | """Base error for this module.""" |
| 27 | pass |
| 28 | |
| 29 | |
| 30 | class RequestError(Error): |
| 31 | """Error occurred during request.""" |
| 32 | pass |
| 33 | |
| 34 | |
| 35 | class MissingParameter(Error): |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 36 | pass |
| 37 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 38 | |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 39 | class CredentialsInvalidError(Error): |
| 40 | pass |
| 41 | |
| 42 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 43 | def _abstract(): |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 44 | raise NotImplementedError('You need to override this function') |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 45 | |
| 46 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 47 | def _oauth_uri(name, discovery, params): |
ade@google.com | a9907a2 | 2010-12-11 02:44:37 +0000 | [diff] [blame] | 48 | """Look up the OAuth URI from the discovery |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 49 | document and add query parameters based on |
| 50 | params. |
| 51 | |
| 52 | name - The name of the OAuth URI to lookup, one |
| 53 | of 'request', 'access', or 'authorize'. |
| 54 | discovery - Portion of discovery document the describes |
| 55 | the OAuth endpoints. |
| 56 | params - Dictionary that is used to form the query parameters |
| 57 | for the specified URI. |
| 58 | """ |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 59 | if name not in ['request', 'access', 'authorize']: |
| 60 | raise KeyError(name) |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 61 | keys = discovery[name]['parameters'].keys() |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 62 | query = {} |
| 63 | for key in keys: |
| 64 | if key in params: |
| 65 | query[key] = params[key] |
| 66 | return discovery[name]['url'] + '?' + urllib.urlencode(query) |
| 67 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 68 | |
| 69 | class Credentials(object): |
| 70 | """Base class for all Credentials objects. |
| 71 | |
| 72 | Subclasses must define an authorize() method |
| 73 | that applies the credentials to an HTTP transport. |
| 74 | """ |
| 75 | |
| 76 | def authorize(self, http): |
| 77 | """Take an httplib2.Http instance (or equivalent) and |
| 78 | authorizes it for the set of credentials, usually by |
| 79 | replacing http.request() with a method that adds in |
| 80 | the appropriate headers and then delegates to the original |
| 81 | Http.request() method. |
| 82 | """ |
| 83 | _abstract() |
| 84 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 85 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 86 | class Flow(object): |
| 87 | """Base class for all Flow objects.""" |
| 88 | pass |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 89 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 90 | |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 91 | class Storage(object): |
| 92 | """Base class for all Storage objects. |
| 93 | |
| 94 | Store and retrieve a single credential. |
| 95 | """ |
| 96 | |
| 97 | def get(self): |
| 98 | """Retrieve credential. |
| 99 | |
| 100 | Returns: |
| 101 | apiclient.oauth.Credentials |
| 102 | """ |
| 103 | _abstract() |
| 104 | |
| 105 | def put(self, credentials): |
| 106 | """Write a credential. |
| 107 | |
| 108 | Args: |
| 109 | credentials: Credentials, the credentials to store. |
| 110 | """ |
| 111 | _abstract() |
| 112 | |
| 113 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 114 | class OAuthCredentials(Credentials): |
| 115 | """Credentials object for OAuth 1.0a |
| 116 | """ |
| 117 | |
| 118 | def __init__(self, consumer, token, user_agent): |
| 119 | """ |
| 120 | consumer - An instance of oauth.Consumer. |
| 121 | token - An instance of oauth.Token constructed with |
| 122 | the access token and secret. |
| 123 | user_agent - The HTTP User-Agent to provide for this application. |
| 124 | """ |
| 125 | self.consumer = consumer |
| 126 | self.token = token |
| 127 | self.user_agent = user_agent |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 128 | self.store = None |
| 129 | |
| 130 | # True if the credentials have been revoked |
| 131 | self._invalid = False |
| 132 | |
| 133 | @property |
| 134 | def invalid(self): |
| 135 | """True if the credentials are invalid, such as being revoked.""" |
| 136 | return getattr(self, "_invalid", False) |
| 137 | |
| 138 | def set_store(self, store): |
| 139 | """Set the storage for the credential. |
| 140 | |
| 141 | Args: |
| 142 | store: callable, a callable that when passed a Credential |
| 143 | will store the credential back to where it came from. |
| 144 | This is needed to store the latest access_token if it |
| 145 | has been revoked. |
| 146 | """ |
| 147 | self.store = store |
| 148 | |
| 149 | def __getstate__(self): |
Joe Gregorio | 825d78d | 2011-02-18 15:07:17 -0500 | [diff] [blame] | 150 | """Trim the state down to something that can be pickled.""" |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 151 | d = copy.copy(self.__dict__) |
| 152 | del d['store'] |
| 153 | return d |
| 154 | |
| 155 | def __setstate__(self, state): |
Joe Gregorio | 825d78d | 2011-02-18 15:07:17 -0500 | [diff] [blame] | 156 | """Reconstitute the state of the object from being pickled.""" |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 157 | self.__dict__.update(state) |
| 158 | self.store = None |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 159 | |
| 160 | def authorize(self, http): |
| 161 | """ |
| 162 | Args: |
| 163 | http - An instance of httplib2.Http |
| 164 | or something that acts like it. |
| 165 | |
| 166 | Returns: |
| 167 | A modified instance of http that was passed in. |
| 168 | |
| 169 | Example: |
| 170 | |
| 171 | h = httplib2.Http() |
| 172 | h = credentials.authorize(h) |
| 173 | |
| 174 | You can't create a new OAuth |
| 175 | subclass of httplib2.Authenication because |
| 176 | it never gets passed the absolute URI, which is |
| 177 | needed for signing. So instead we have to overload |
| 178 | 'request' with a closure that adds in the |
| 179 | Authorization header and then calls the original version |
| 180 | of 'request()'. |
| 181 | """ |
| 182 | request_orig = http.request |
| 183 | signer = oauth.SignatureMethod_HMAC_SHA1() |
| 184 | |
| 185 | # The closure that will replace 'httplib2.Http.request'. |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 186 | def new_request(uri, method='GET', body=None, headers=None, |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 187 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 188 | connection_type=None): |
| 189 | """Modify the request headers to add the appropriate |
| 190 | Authorization header.""" |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 191 | response_code = 302 |
| 192 | http.follow_redirects = False |
| 193 | while response_code in [301, 302]: |
| 194 | req = oauth.Request.from_consumer_and_token( |
| 195 | self.consumer, self.token, http_method=method, http_url=uri) |
| 196 | req.sign_request(signer, self.consumer, self.token) |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 197 | if headers is None: |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 198 | headers = {} |
| 199 | headers.update(req.to_header()) |
| 200 | if 'user-agent' in headers: |
| 201 | headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] |
| 202 | else: |
| 203 | headers['user-agent'] = self.user_agent |
| 204 | resp, content = request_orig(uri, method, body, headers, |
| 205 | redirections, connection_type) |
| 206 | response_code = resp.status |
| 207 | if response_code in [301, 302]: |
| 208 | uri = resp['location'] |
Joe Gregorio | a0a52e4 | 2011-02-17 17:13:26 -0500 | [diff] [blame] | 209 | |
| 210 | # Update the stored credential if it becomes invalid. |
| 211 | if response_code == 401: |
| 212 | logging.info('Access token no longer valid: %s' % content) |
| 213 | self._invalid = True |
| 214 | if self.store is not None: |
| 215 | self.store(self) |
| 216 | raise CredentialsInvalidError("Credentials are no longer valid.") |
| 217 | |
Joe Gregorio | 48c1caa | 2011-01-05 11:22:47 -0500 | [diff] [blame] | 218 | return resp, content |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 219 | |
| 220 | http.request = new_request |
| 221 | return http |
| 222 | |
| 223 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 224 | class FlowThreeLegged(Flow): |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 225 | """Does the Three Legged Dance for OAuth 1.0a. |
| 226 | """ |
| 227 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 228 | def __init__(self, discovery, consumer_key, consumer_secret, user_agent, |
| 229 | **kwargs): |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 230 | """ |
| 231 | discovery - Section of the API discovery document that describes |
| 232 | the OAuth endpoints. |
| 233 | consumer_key - OAuth consumer key |
| 234 | consumer_secret - OAuth consumer secret |
| 235 | user_agent - The HTTP User-Agent that identifies the application. |
| 236 | **kwargs - The keyword arguments are all optional and required |
| 237 | parameters for the OAuth calls. |
| 238 | """ |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 239 | self.discovery = discovery |
| 240 | self.consumer_key = consumer_key |
| 241 | self.consumer_secret = consumer_secret |
| 242 | self.user_agent = user_agent |
| 243 | self.params = kwargs |
| 244 | self.request_token = {} |
Joe Gregorio | 7943c5d | 2010-09-08 16:11:43 -0400 | [diff] [blame] | 245 | required = {} |
| 246 | for uriinfo in discovery.itervalues(): |
| 247 | for name, value in uriinfo['parameters'].iteritems(): |
| 248 | if value['required'] and not name.startswith('oauth_'): |
| 249 | required[name] = 1 |
| 250 | for key in required.iterkeys(): |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 251 | if key not in self.params: |
| 252 | raise MissingParameter('Required parameter %s not supplied' % key) |
| 253 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 254 | def step1_get_authorize_url(self, oauth_callback='oob'): |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 255 | """Returns a URI to redirect to the provider. |
| 256 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 257 | oauth_callback - Either the string 'oob' for a non-web-based application, |
| 258 | or a URI that handles the callback from the authorization |
| 259 | server. |
| 260 | |
| 261 | If oauth_callback is 'oob' then pass in the |
| 262 | generated verification code to step2_exchange, |
| 263 | otherwise pass in the query parameters received |
| 264 | at the callback uri to step2_exchange. |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 265 | """ |
| 266 | consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) |
| 267 | client = oauth.Client(consumer) |
| 268 | |
| 269 | headers = { |
| 270 | 'user-agent': self.user_agent, |
| 271 | 'content-type': 'application/x-www-form-urlencoded' |
| 272 | } |
| 273 | body = urllib.urlencode({'oauth_callback': oauth_callback}) |
| 274 | uri = _oauth_uri('request', self.discovery, self.params) |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 275 | |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 276 | resp, content = client.request(uri, 'POST', headers=headers, |
| 277 | body=body) |
| 278 | if resp['status'] != '200': |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 279 | logging.error('Failed to retrieve temporary authorization: %s', content) |
Tom Miller | 05cd4f5 | 2010-10-06 11:09:12 -0700 | [diff] [blame] | 280 | raise RequestError('Invalid response %s.' % resp['status']) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 281 | |
| 282 | self.request_token = dict(parse_qsl(content)) |
| 283 | |
| 284 | auth_params = copy.copy(self.params) |
| 285 | auth_params['oauth_token'] = self.request_token['oauth_token'] |
| 286 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 287 | return _oauth_uri('authorize', self.discovery, auth_params) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 288 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 289 | def step2_exchange(self, verifier): |
| 290 | """Exhanges an authorized request token |
| 291 | for OAuthCredentials. |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 292 | |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 293 | Args: |
| 294 | verifier: string, dict - either the verifier token, or a dictionary |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 295 | of the query parameters to the callback, which contains |
| 296 | the oauth_verifier. |
Joe Gregorio | 9e5fe4d | 2011-03-10 09:33:47 -0500 | [diff] [blame] | 297 | Returns: |
| 298 | The Credentials object. |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 299 | """ |
| 300 | |
| 301 | if not (isinstance(verifier, str) or isinstance(verifier, unicode)): |
| 302 | verifier = verifier['oauth_verifier'] |
| 303 | |
| 304 | token = oauth.Token( |
| 305 | self.request_token['oauth_token'], |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 306 | self.request_token['oauth_token_secret']) |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 307 | token.set_verifier(verifier) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 308 | consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) |
| 309 | client = oauth.Client(consumer, token) |
| 310 | |
| 311 | headers = { |
| 312 | 'user-agent': self.user_agent, |
| 313 | 'content-type': 'application/x-www-form-urlencoded' |
| 314 | } |
| 315 | |
| 316 | uri = _oauth_uri('access', self.discovery, self.params) |
| 317 | resp, content = client.request(uri, 'POST', headers=headers) |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 318 | if resp['status'] != '200': |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 319 | logging.error('Failed to retrieve access token: %s', content) |
Tom Miller | 05cd4f5 | 2010-10-06 11:09:12 -0700 | [diff] [blame] | 320 | raise RequestError('Invalid response %s.' % resp['status']) |
Joe Gregorio | 67d7777 | 2010-09-01 16:45:45 -0400 | [diff] [blame] | 321 | |
Joe Gregorio | 845a545 | 2010-09-08 13:50:34 -0400 | [diff] [blame] | 322 | oauth_params = dict(parse_qsl(content)) |
| 323 | token = oauth.Token( |
| 324 | oauth_params['oauth_token'], |
| 325 | oauth_params['oauth_token_secret']) |
| 326 | |
| 327 | return OAuthCredentials(consumer, token, self.user_agent) |