/gdata/gauth.py

http://radioappz.googlecode.com/ · Python · 1306 lines · 1144 code · 41 blank · 121 comment · 54 complexity · 2ad17ed286a07f9fc81ff8a3fad7f979 MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2009 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # This module is used for version 2 of the Google Data APIs.
  17. """Provides auth related token classes and functions for Google Data APIs.
  18. Token classes represent a user's authorization of this app to access their
  19. data. Usually these are not created directly but by a GDClient object.
  20. ClientLoginToken
  21. AuthSubToken
  22. SecureAuthSubToken
  23. OAuthHmacToken
  24. OAuthRsaToken
  25. TwoLeggedOAuthHmacToken
  26. TwoLeggedOAuthRsaToken
  27. Functions which are often used in application code (as opposed to just within
  28. the gdata-python-client library) are the following:
  29. generate_auth_sub_url
  30. authorize_request_token
  31. The following are helper functions which are used to save and load auth token
  32. objects in the App Engine datastore. These should only be used if you are using
  33. this library within App Engine:
  34. ae_load
  35. ae_save
  36. """
  37. import time
  38. import random
  39. import urllib
  40. import atom.http_core
  41. __author__ = 'j.s@google.com (Jeff Scudder)'
  42. PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth='
  43. AUTHSUB_AUTH_LABEL = 'AuthSub token='
  44. # This dict provides the AuthSub and OAuth scopes for all services by service
  45. # name. The service name (key) is used in ClientLogin requests.
  46. AUTH_SCOPES = {
  47. 'cl': ( # Google Calendar API
  48. 'https://www.google.com/calendar/feeds/',
  49. 'http://www.google.com/calendar/feeds/'),
  50. 'gbase': ( # Google Base API
  51. 'http://base.google.com/base/feeds/',
  52. 'http://www.google.com/base/feeds/'),
  53. 'blogger': ( # Blogger API
  54. 'http://www.blogger.com/feeds/',),
  55. 'codesearch': ( # Google Code Search API
  56. 'http://www.google.com/codesearch/feeds/',),
  57. 'cp': ( # Contacts API
  58. 'https://www.google.com/m8/feeds/',
  59. 'http://www.google.com/m8/feeds/'),
  60. 'finance': ( # Google Finance API
  61. 'http://finance.google.com/finance/feeds/',),
  62. 'health': ( # Google Health API
  63. 'https://www.google.com/health/feeds/',),
  64. 'writely': ( # Documents List API
  65. 'https://docs.google.com/feeds/',
  66. 'http://docs.google.com/feeds/'),
  67. 'lh2': ( # Picasa Web Albums API
  68. 'http://picasaweb.google.com/data/',),
  69. 'apps': ( # Google Apps Provisioning API
  70. 'http://www.google.com/a/feeds/',
  71. 'https://www.google.com/a/feeds/',
  72. 'http://apps-apis.google.com/a/feeds/',
  73. 'https://apps-apis.google.com/a/feeds/'),
  74. 'weaver': ( # Health H9 Sandbox
  75. 'https://www.google.com/h9/feeds/',),
  76. 'wise': ( # Spreadsheets Data API
  77. 'https://spreadsheets.google.com/feeds/',
  78. 'http://spreadsheets.google.com/feeds/'),
  79. 'sitemaps': ( # Google Webmaster Tools API
  80. 'https://www.google.com/webmasters/tools/feeds/',),
  81. 'youtube': ( # YouTube API
  82. 'http://gdata.youtube.com/feeds/api/',
  83. 'http://uploads.gdata.youtube.com/feeds/api',
  84. 'http://gdata.youtube.com/action/GetUploadToken'),
  85. 'books': ( # Google Books API
  86. 'http://www.google.com/books/feeds/',),
  87. 'analytics': ( # Google Analytics API
  88. 'https://www.google.com/analytics/feeds/',),
  89. 'jotspot': ( # Google Sites API
  90. 'http://sites.google.com/feeds/',
  91. 'https://sites.google.com/feeds/'),
  92. 'local': ( # Google Maps Data API
  93. 'http://maps.google.com/maps/feeds/',),
  94. 'code': ( # Project Hosting Data API
  95. 'http://code.google.com/feeds/issues',)}
  96. class Error(Exception):
  97. pass
  98. class UnsupportedTokenType(Error):
  99. """Raised when token to or from blob is unable to convert the token."""
  100. pass
  101. # ClientLogin functions and classes.
  102. def generate_client_login_request_body(email, password, service, source,
  103. account_type='HOSTED_OR_GOOGLE', captcha_token=None,
  104. captcha_response=None):
  105. """Creates the body of the autentication request
  106. See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request
  107. for more details.
  108. Args:
  109. email: str
  110. password: str
  111. service: str
  112. source: str
  113. account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid
  114. values are 'GOOGLE' and 'HOSTED'
  115. captcha_token: str (optional)
  116. captcha_response: str (optional)
  117. Returns:
  118. The HTTP body to send in a request for a client login token.
  119. """
  120. # Create a POST body containing the user's credentials.
  121. request_fields = {'Email': email,
  122. 'Passwd': password,
  123. 'accountType': account_type,
  124. 'service': service,
  125. 'source': source}
  126. if captcha_token and captcha_response:
  127. # Send the captcha token and response as part of the POST body if the
  128. # user is responding to a captch challenge.
  129. request_fields['logintoken'] = captcha_token
  130. request_fields['logincaptcha'] = captcha_response
  131. return urllib.urlencode(request_fields)
  132. GenerateClientLoginRequestBody = generate_client_login_request_body
  133. def get_client_login_token_string(http_body):
  134. """Returns the token value for a ClientLoginToken.
  135. Reads the token from the server's response to a Client Login request and
  136. creates the token value string to use in requests.
  137. Args:
  138. http_body: str The body of the server's HTTP response to a Client Login
  139. request
  140. Returns:
  141. The token value string for a ClientLoginToken.
  142. """
  143. for response_line in http_body.splitlines():
  144. if response_line.startswith('Auth='):
  145. # Strip off the leading Auth= and return the Authorization value.
  146. return response_line[5:]
  147. return None
  148. GetClientLoginTokenString = get_client_login_token_string
  149. def get_captcha_challenge(http_body,
  150. captcha_base_url='http://www.google.com/accounts/'):
  151. """Returns the URL and token for a CAPTCHA challenge issued by the server.
  152. Args:
  153. http_body: str The body of the HTTP response from the server which
  154. contains the CAPTCHA challenge.
  155. captcha_base_url: str This function returns a full URL for viewing the
  156. challenge image which is built from the server's response. This
  157. base_url is used as the beginning of the URL because the server
  158. only provides the end of the URL. For example the server provides
  159. 'Captcha?ctoken=Hi...N' and the URL for the image is
  160. 'http://www.google.com/accounts/Captcha?ctoken=Hi...N'
  161. Returns:
  162. A dictionary containing the information needed to repond to the CAPTCHA
  163. challenge, the image URL and the ID token of the challenge. The
  164. dictionary is in the form:
  165. {'token': string identifying the CAPTCHA image,
  166. 'url': string containing the URL of the image}
  167. Returns None if there was no CAPTCHA challenge in the response.
  168. """
  169. contains_captcha_challenge = False
  170. captcha_parameters = {}
  171. for response_line in http_body.splitlines():
  172. if response_line.startswith('Error=CaptchaRequired'):
  173. contains_captcha_challenge = True
  174. elif response_line.startswith('CaptchaToken='):
  175. # Strip off the leading CaptchaToken=
  176. captcha_parameters['token'] = response_line[13:]
  177. elif response_line.startswith('CaptchaUrl='):
  178. captcha_parameters['url'] = '%s%s' % (captcha_base_url,
  179. response_line[11:])
  180. if contains_captcha_challenge:
  181. return captcha_parameters
  182. else:
  183. return None
  184. GetCaptchaChallenge = get_captcha_challenge
  185. class ClientLoginToken(object):
  186. def __init__(self, token_string):
  187. self.token_string = token_string
  188. def modify_request(self, http_request):
  189. http_request.headers['Authorization'] = '%s%s' % (PROGRAMMATIC_AUTH_LABEL,
  190. self.token_string)
  191. ModifyRequest = modify_request
  192. # AuthSub functions and classes.
  193. def _to_uri(str_or_uri):
  194. if isinstance(str_or_uri, (str, unicode)):
  195. return atom.http_core.Uri.parse_uri(str_or_uri)
  196. return str_or_uri
  197. def generate_auth_sub_url(next, scopes, secure=False, session=True,
  198. request_url=atom.http_core.parse_uri(
  199. 'https://www.google.com/accounts/AuthSubRequest'),
  200. domain='default', scopes_param_prefix='auth_sub_scopes'):
  201. """Constructs a URI for requesting a multiscope AuthSub token.
  202. The generated token will contain a URL parameter to pass along the
  203. requested scopes to the next URL. When the Google Accounts page
  204. redirects the broswser to the 'next' URL, it appends the single use
  205. AuthSub token value to the URL as a URL parameter with the key 'token'.
  206. However, the information about which scopes were requested is not
  207. included by Google Accounts. This method adds the scopes to the next
  208. URL before making the request so that the redirect will be sent to
  209. a page, and both the token value and the list of scopes for which the token
  210. was requested.
  211. Args:
  212. next: atom.http_core.Uri or string The URL user will be sent to after
  213. authorizing this web application to access their data.
  214. scopes: list containint strings or atom.http_core.Uri objects. The URLs
  215. of the services to be accessed. Could also be a single string
  216. or single atom.http_core.Uri for requesting just one scope.
  217. secure: boolean (optional) Determines whether or not the issued token
  218. is a secure token.
  219. session: boolean (optional) Determines whether or not the issued token
  220. can be upgraded to a session token.
  221. request_url: atom.http_core.Uri or str The beginning of the request URL.
  222. This is normally
  223. 'http://www.google.com/accounts/AuthSubRequest' or
  224. '/accounts/AuthSubRequest'
  225. domain: The domain which the account is part of. This is used for Google
  226. Apps accounts, the default value is 'default' which means that
  227. the requested account is a Google Account (@gmail.com for
  228. example)
  229. scopes_param_prefix: str (optional) The requested scopes are added as a
  230. URL parameter to the next URL so that the page at
  231. the 'next' URL can extract the token value and the
  232. valid scopes from the URL. The key for the URL
  233. parameter defaults to 'auth_sub_scopes'
  234. Returns:
  235. An atom.http_core.Uri which the user's browser should be directed to in
  236. order to authorize this application to access their information.
  237. """
  238. if isinstance(next, (str, unicode)):
  239. next = atom.http_core.Uri.parse_uri(next)
  240. # If the user passed in a string instead of a list for scopes, convert to
  241. # a single item tuple.
  242. if isinstance(scopes, (str, unicode, atom.http_core.Uri)):
  243. scopes = (scopes,)
  244. scopes_string = ' '.join([str(scope) for scope in scopes])
  245. next.query[scopes_param_prefix] = scopes_string
  246. if isinstance(request_url, (str, unicode)):
  247. request_url = atom.http_core.Uri.parse_uri(request_url)
  248. request_url.query['next'] = str(next)
  249. request_url.query['scope'] = scopes_string
  250. if session:
  251. request_url.query['session'] = '1'
  252. else:
  253. request_url.query['session'] = '0'
  254. if secure:
  255. request_url.query['secure'] = '1'
  256. else:
  257. request_url.query['secure'] = '0'
  258. request_url.query['hd'] = domain
  259. return request_url
  260. def auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'):
  261. """Finds the token string (and scopes) after the browser is redirected.
  262. After the Google Accounts AuthSub pages redirect the user's broswer back to
  263. the web application (using the 'next' URL from the request) the web app must
  264. extract the token from the current page's URL. The token is provided as a
  265. URL parameter named 'token' and if generate_auth_sub_url was used to create
  266. the request, the token's valid scopes are included in a URL parameter whose
  267. name is specified in scopes_param_prefix.
  268. Args:
  269. url: atom.url.Url or str representing the current URL. The token value
  270. and valid scopes should be included as URL parameters.
  271. scopes_param_prefix: str (optional) The URL parameter key which maps to
  272. the list of valid scopes for the token.
  273. Returns:
  274. A tuple containing the token value as a string, and a tuple of scopes
  275. (as atom.http_core.Uri objects) which are URL prefixes under which this
  276. token grants permission to read and write user data.
  277. (token_string, (scope_uri, scope_uri, scope_uri, ...))
  278. If no scopes were included in the URL, the second value in the tuple is
  279. None. If there was no token param in the url, the tuple returned is
  280. (None, None)
  281. """
  282. if isinstance(url, (str, unicode)):
  283. url = atom.http_core.Uri.parse_uri(url)
  284. if 'token' not in url.query:
  285. return (None, None)
  286. token = url.query['token']
  287. # TODO: decide whether no scopes should be None or ().
  288. scopes = None # Default to None for no scopes.
  289. if scopes_param_prefix in url.query:
  290. scopes = tuple(url.query[scopes_param_prefix].split(' '))
  291. return (token, scopes)
  292. AuthSubStringFromUrl = auth_sub_string_from_url
  293. def auth_sub_string_from_body(http_body):
  294. """Extracts the AuthSub token from an HTTP body string.
  295. Used to find the new session token after making a request to upgrade a
  296. single use AuthSub token.
  297. Args:
  298. http_body: str The repsonse from the server which contains the AuthSub
  299. key. For example, this function would find the new session token
  300. from the server's response to an upgrade token request.
  301. Returns:
  302. The raw token value string to use in an AuthSubToken object.
  303. """
  304. for response_line in http_body.splitlines():
  305. if response_line.startswith('Token='):
  306. # Strip off Token= and return the token value string.
  307. return response_line[6:]
  308. return None
  309. class AuthSubToken(object):
  310. def __init__(self, token_string, scopes=None):
  311. self.token_string = token_string
  312. self.scopes = scopes or []
  313. def modify_request(self, http_request):
  314. """Sets Authorization header, allows app to act on the user's behalf."""
  315. http_request.headers['Authorization'] = '%s%s' % (AUTHSUB_AUTH_LABEL,
  316. self.token_string)
  317. ModifyRequest = modify_request
  318. def from_url(str_or_uri):
  319. """Creates a new AuthSubToken using information in the URL.
  320. Uses auth_sub_string_from_url.
  321. Args:
  322. str_or_uri: The current page's URL (as a str or atom.http_core.Uri)
  323. which should contain a token query parameter since the
  324. Google auth server redirected the user's browser to this
  325. URL.
  326. """
  327. token_and_scopes = auth_sub_string_from_url(str_or_uri)
  328. return AuthSubToken(token_and_scopes[0], token_and_scopes[1])
  329. from_url = staticmethod(from_url)
  330. FromUrl = from_url
  331. def _upgrade_token(self, http_body):
  332. """Replaces the token value with a session token from the auth server.
  333. Uses the response of a token upgrade request to modify this token. Uses
  334. auth_sub_string_from_body.
  335. """
  336. self.token_string = auth_sub_string_from_body(http_body)
  337. # Functions and classes for Secure-mode AuthSub
  338. def build_auth_sub_data(http_request, timestamp, nonce):
  339. """Creates the data string which must be RSA-signed in secure requests.
  340. For more details see the documenation on secure AuthSub requests:
  341. http://code.google.com/apis/accounts/docs/AuthSub.html#signingrequests
  342. Args:
  343. http_request: The request being made to the server. The Request's URL
  344. must be complete before this signature is calculated as any changes
  345. to the URL will invalidate the signature.
  346. nonce: str Random 64-bit, unsigned number encoded as an ASCII string in
  347. decimal format. The nonce/timestamp pair should always be unique to
  348. prevent replay attacks.
  349. timestamp: Integer representing the time the request is sent. The
  350. timestamp should be expressed in number of seconds after January 1,
  351. 1970 00:00:00 GMT.
  352. """
  353. return '%s %s %s %s' % (http_request.method, str(http_request.uri),
  354. str(timestamp), nonce)
  355. def generate_signature(data, rsa_key):
  356. """Signs the data string for a secure AuthSub request."""
  357. import base64
  358. try:
  359. from tlslite.utils import keyfactory
  360. except ImportError:
  361. from gdata.tlslite.utils import keyfactory
  362. private_key = keyfactory.parsePrivateKey(rsa_key)
  363. signed = private_key.hashAndSign(data)
  364. # Python2.3 and lower does not have the base64.b64encode function.
  365. if hasattr(base64, 'b64encode'):
  366. return base64.b64encode(signed)
  367. else:
  368. return base64.encodestring(signed).replace('\n', '')
  369. class SecureAuthSubToken(AuthSubToken):
  370. def __init__(self, token_string, rsa_private_key, scopes=None):
  371. self.token_string = token_string
  372. self.scopes = scopes or []
  373. self.rsa_private_key = rsa_private_key
  374. def from_url(str_or_uri, rsa_private_key):
  375. """Creates a new SecureAuthSubToken using information in the URL.
  376. Uses auth_sub_string_from_url.
  377. Args:
  378. str_or_uri: The current page's URL (as a str or atom.http_core.Uri)
  379. which should contain a token query parameter since the Google auth
  380. server redirected the user's browser to this URL.
  381. rsa_private_key: str the private RSA key cert used to sign all requests
  382. made with this token.
  383. """
  384. token_and_scopes = auth_sub_string_from_url(str_or_uri)
  385. return SecureAuthSubToken(token_and_scopes[0], rsa_private_key,
  386. token_and_scopes[1])
  387. from_url = staticmethod(from_url)
  388. FromUrl = from_url
  389. def modify_request(self, http_request):
  390. """Sets the Authorization header and includes a digital signature.
  391. Calculates a digital signature using the private RSA key, a timestamp
  392. (uses now at the time this method is called) and a random nonce.
  393. Args:
  394. http_request: The atom.http_core.HttpRequest which contains all of the
  395. information needed to send a request to the remote server. The
  396. URL and the method of the request must be already set and cannot be
  397. changed after this token signs the request, or the signature will
  398. not be valid.
  399. """
  400. timestamp = str(int(time.time()))
  401. nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)])
  402. data = build_auth_sub_data(http_request, timestamp, nonce)
  403. signature = generate_signature(data, self.rsa_private_key)
  404. http_request.headers['Authorization'] = (
  405. '%s%s sigalg="rsa-sha1" data="%s" sig="%s"' % (AUTHSUB_AUTH_LABEL,
  406. self.token_string, data, signature))
  407. ModifyRequest = modify_request
  408. # OAuth functions and classes.
  409. RSA_SHA1 = 'RSA-SHA1'
  410. HMAC_SHA1 = 'HMAC-SHA1'
  411. def build_oauth_base_string(http_request, consumer_key, nonce, signaure_type,
  412. timestamp, version, next='oob', token=None,
  413. verifier=None):
  414. """Generates the base string to be signed in the OAuth request.
  415. Args:
  416. http_request: The request being made to the server. The Request's URL
  417. must be complete before this signature is calculated as any changes
  418. to the URL will invalidate the signature.
  419. consumer_key: Domain identifying the third-party web application. This is
  420. the domain used when registering the application with Google. It
  421. identifies who is making the request on behalf of the user.
  422. nonce: Random 64-bit, unsigned number encoded as an ASCII string in decimal
  423. format. The nonce/timestamp pair should always be unique to prevent
  424. replay attacks.
  425. signaure_type: either RSA_SHA1 or HMAC_SHA1
  426. timestamp: Integer representing the time the request is sent. The
  427. timestamp should be expressed in number of seconds after January 1,
  428. 1970 00:00:00 GMT.
  429. version: The OAuth version used by the requesting web application. This
  430. value must be '1.0' or '1.0a'. If not provided, Google assumes version
  431. 1.0 is in use.
  432. next: The URL the user should be redirected to after granting access
  433. to a Google service(s). It can include url-encoded query parameters.
  434. The default value is 'oob'. (This is the oauth_callback.)
  435. token: The string for the OAuth request token or OAuth access token.
  436. verifier: str Sent as the oauth_verifier and required when upgrading a
  437. request token to an access token.
  438. """
  439. # First we must build the canonical base string for the request.
  440. params = http_request.uri.query.copy()
  441. params['oauth_consumer_key'] = consumer_key
  442. params['oauth_nonce'] = nonce
  443. params['oauth_signature_method'] = signaure_type
  444. params['oauth_timestamp'] = str(timestamp)
  445. if next is not None:
  446. params['oauth_callback'] = str(next)
  447. if token is not None:
  448. params['oauth_token'] = token
  449. if version is not None:
  450. params['oauth_version'] = version
  451. if verifier is not None:
  452. params['oauth_verifier'] = verifier
  453. # We need to get the key value pairs in lexigraphically sorted order.
  454. sorted_keys = None
  455. try:
  456. sorted_keys = sorted(params.keys())
  457. # The sorted function is not available in Python2.3 and lower
  458. except NameError:
  459. sorted_keys = params.keys()
  460. sorted_keys.sort()
  461. pairs = []
  462. for key in sorted_keys:
  463. pairs.append('%s=%s' % (urllib.quote(key, safe='~'),
  464. urllib.quote(params[key], safe='~')))
  465. # We want to escape /'s too, so use safe='~'
  466. all_parameters = urllib.quote('&'.join(pairs), safe='~')
  467. normailzed_host = http_request.uri.host.lower()
  468. normalized_scheme = (http_request.uri.scheme or 'http').lower()
  469. non_default_port = None
  470. if (http_request.uri.port is not None
  471. and ((normalized_scheme == 'https' and http_request.uri.port != 443)
  472. or (normalized_scheme == 'http' and http_request.uri.port != 80))):
  473. non_default_port = http_request.uri.port
  474. path = http_request.uri.path or '/'
  475. request_path = None
  476. if not path.startswith('/'):
  477. path = '/%s' % path
  478. if non_default_port is not None:
  479. # Set the only safe char in url encoding to ~ since we want to escape /
  480. # as well.
  481. request_path = urllib.quote('%s://%s:%s%s' % (
  482. normalized_scheme, normailzed_host, non_default_port, path), safe='~')
  483. else:
  484. # Set the only safe char in url encoding to ~ since we want to escape /
  485. # as well.
  486. request_path = urllib.quote('%s://%s%s' % (
  487. normalized_scheme, normailzed_host, path), safe='~')
  488. # TODO: ensure that token escaping logic is correct, not sure if the token
  489. # value should be double escaped instead of single.
  490. base_string = '&'.join((http_request.method.upper(), request_path,
  491. all_parameters))
  492. # Now we have the base string, we can calculate the oauth_signature.
  493. return base_string
  494. def generate_hmac_signature(http_request, consumer_key, consumer_secret,
  495. timestamp, nonce, version, next='oob',
  496. token=None, token_secret=None, verifier=None):
  497. import hmac
  498. import base64
  499. base_string = build_oauth_base_string(
  500. http_request, consumer_key, nonce, HMAC_SHA1, timestamp, version,
  501. next, token, verifier=verifier)
  502. hash_key = None
  503. hashed = None
  504. if token_secret is not None:
  505. hash_key = '%s&%s' % (urllib.quote(consumer_secret, safe='~'),
  506. urllib.quote(token_secret, safe='~'))
  507. else:
  508. hash_key = '%s&' % urllib.quote(consumer_secret, safe='~')
  509. try:
  510. import hashlib
  511. hashed = hmac.new(hash_key, base_string, hashlib.sha1)
  512. except ImportError:
  513. import sha
  514. hashed = hmac.new(hash_key, base_string, sha)
  515. # Python2.3 does not have base64.b64encode.
  516. if hasattr(base64, 'b64encode'):
  517. return base64.b64encode(hashed.digest())
  518. else:
  519. return base64.encodestring(hashed.digest()).replace('\n', '')
  520. def generate_rsa_signature(http_request, consumer_key, rsa_key,
  521. timestamp, nonce, version, next='oob',
  522. token=None, token_secret=None, verifier=None):
  523. import base64
  524. try:
  525. from tlslite.utils import keyfactory
  526. except ImportError:
  527. from gdata.tlslite.utils import keyfactory
  528. base_string = build_oauth_base_string(
  529. http_request, consumer_key, nonce, RSA_SHA1, timestamp, version,
  530. next, token, verifier=verifier)
  531. private_key = keyfactory.parsePrivateKey(rsa_key)
  532. # Sign using the key
  533. signed = private_key.hashAndSign(base_string)
  534. # Python2.3 does not have base64.b64encode.
  535. if hasattr(base64, 'b64encode'):
  536. return base64.b64encode(signed)
  537. else:
  538. return base64.encodestring(signed).replace('\n', '')
  539. def generate_auth_header(consumer_key, timestamp, nonce, signature_type,
  540. signature, version='1.0', next=None, token=None,
  541. verifier=None):
  542. """Builds the Authorization header to be sent in the request.
  543. Args:
  544. consumer_key: Identifies the application making the request (str).
  545. timestamp:
  546. nonce:
  547. signature_type: One of either HMAC_SHA1 or RSA_SHA1
  548. signature: The HMAC or RSA signature for the request as a base64
  549. encoded string.
  550. version: The version of the OAuth protocol that this request is using.
  551. Default is '1.0'
  552. next: The URL of the page that the user's browser should be sent to
  553. after they authorize the token. (Optional)
  554. token: str The OAuth token value to be used in the oauth_token parameter
  555. of the header.
  556. verifier: str The OAuth verifier which must be included when you are
  557. upgrading a request token to an access token.
  558. """
  559. params = {
  560. 'oauth_consumer_key': consumer_key,
  561. 'oauth_version': version,
  562. 'oauth_nonce': nonce,
  563. 'oauth_timestamp': str(timestamp),
  564. 'oauth_signature_method': signature_type,
  565. 'oauth_signature': signature}
  566. if next is not None:
  567. params['oauth_callback'] = str(next)
  568. if token is not None:
  569. params['oauth_token'] = token
  570. if verifier is not None:
  571. params['oauth_verifier'] = verifier
  572. pairs = [
  573. '%s="%s"' % (
  574. k, urllib.quote(v, safe='~')) for k, v in params.iteritems()]
  575. return 'OAuth %s' % (', '.join(pairs))
  576. REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken'
  577. ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken'
  578. def generate_request_for_request_token(
  579. consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None,
  580. auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'):
  581. """Creates request to be sent to auth server to get an OAuth request token.
  582. Args:
  583. consumer_key:
  584. signature_type: either RSA_SHA1 or HMAC_SHA1. The rsa_key must be
  585. provided if the signature type is RSA but if the signature method
  586. is HMAC, the consumer_secret must be used.
  587. scopes: List of URL prefixes for the data which we want to access. For
  588. example, to request access to the user's Blogger and Google Calendar
  589. data, we would request
  590. ['http://www.blogger.com/feeds/',
  591. 'https://www.google.com/calendar/feeds/',
  592. 'http://www.google.com/calendar/feeds/']
  593. rsa_key: Only used if the signature method is RSA_SHA1.
  594. consumer_secret: Only used if the signature method is HMAC_SHA1.
  595. auth_server_url: The URL to which the token request should be directed.
  596. Defaults to 'https://www.google.com/accounts/OAuthGetRequestToken'.
  597. next: The URL of the page that the user's browser should be sent to
  598. after they authorize the token. (Optional)
  599. version: The OAuth version used by the requesting web application.
  600. Defaults to '1.0a'
  601. Returns:
  602. An atom.http_core.HttpRequest object with the URL, Authorization header
  603. and body filled in.
  604. """
  605. request = atom.http_core.HttpRequest(auth_server_url, 'POST')
  606. # Add the requested auth scopes to the Auth request URL.
  607. if scopes:
  608. request.uri.query['scope'] = ' '.join(scopes)
  609. timestamp = str(int(time.time()))
  610. nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)])
  611. signature = None
  612. if signature_type == HMAC_SHA1:
  613. signature = generate_hmac_signature(
  614. request, consumer_key, consumer_secret, timestamp, nonce, version,
  615. next=next)
  616. elif signature_type == RSA_SHA1:
  617. signature = generate_rsa_signature(
  618. request, consumer_key, rsa_key, timestamp, nonce, version, next=next)
  619. else:
  620. return None
  621. request.headers['Authorization'] = generate_auth_header(
  622. consumer_key, timestamp, nonce, signature_type, signature, version,
  623. next)
  624. request.headers['Content-Length'] = '0'
  625. return request
  626. def generate_request_for_access_token(
  627. request_token, auth_server_url=ACCESS_TOKEN_URL):
  628. """Creates a request to ask the OAuth server for an access token.
  629. Requires a request token which the user has authorized. See the
  630. documentation on OAuth with Google Data for more details:
  631. http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken
  632. Args:
  633. request_token: An OAuthHmacToken or OAuthRsaToken which the user has
  634. approved using their browser.
  635. auth_server_url: (optional) The URL at which the OAuth access token is
  636. requested. Defaults to
  637. https://www.google.com/accounts/OAuthGetAccessToken
  638. Returns:
  639. A new HttpRequest object which can be sent to the OAuth server to
  640. request an OAuth Access Token.
  641. """
  642. http_request = atom.http_core.HttpRequest(auth_server_url, 'POST')
  643. http_request.headers['Content-Length'] = '0'
  644. return request_token.modify_request(http_request)
  645. def oauth_token_info_from_body(http_body):
  646. """Exracts an OAuth request token from the server's response.
  647. Returns:
  648. A tuple of strings containing the OAuth token and token secret. If
  649. neither of these are present in the body, returns (None, None)
  650. """
  651. token = None
  652. token_secret = None
  653. for pair in http_body.split('&'):
  654. if pair.startswith('oauth_token='):
  655. token = urllib.unquote(pair[len('oauth_token='):])
  656. if pair.startswith('oauth_token_secret='):
  657. token_secret = urllib.unquote(pair[len('oauth_token_secret='):])
  658. return (token, token_secret)
  659. def hmac_token_from_body(http_body, consumer_key, consumer_secret,
  660. auth_state):
  661. token_value, token_secret = oauth_token_info_from_body(http_body)
  662. token = OAuthHmacToken(consumer_key, consumer_secret, token_value,
  663. token_secret, auth_state)
  664. return token
  665. def rsa_token_from_body(http_body, consumer_key, rsa_private_key,
  666. auth_state):
  667. token_value, token_secret = oauth_token_info_from_body(http_body)
  668. token = OAuthRsaToken(consumer_key, rsa_private_key, token_value,
  669. token_secret, auth_state)
  670. return token
  671. DEFAULT_DOMAIN = 'default'
  672. OAUTH_AUTHORIZE_URL = 'https://www.google.com/accounts/OAuthAuthorizeToken'
  673. def generate_oauth_authorization_url(
  674. token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None,
  675. auth_server=OAUTH_AUTHORIZE_URL):
  676. """Creates a URL for the page where the request token can be authorized.
  677. Args:
  678. token: str The request token from the OAuth server.
  679. next: str (optional) URL the user should be redirected to after granting
  680. access to a Google service(s). It can include url-encoded query
  681. parameters.
  682. hd: str (optional) Identifies a particular hosted domain account to be
  683. accessed (for example, 'mycollege.edu'). Uses 'default' to specify a
  684. regular Google account ('username@gmail.com').
  685. hl: str (optional) An ISO 639 country code identifying what language the
  686. approval page should be translated in (for example, 'hl=en' for
  687. English). The default is the user's selected language.
  688. btmpl: str (optional) Forces a mobile version of the approval page. The
  689. only accepted value is 'mobile'.
  690. auth_server: str (optional) The start of the token authorization web
  691. page. Defaults to
  692. 'https://www.google.com/accounts/OAuthAuthorizeToken'
  693. Returns:
  694. An atom.http_core.Uri pointing to the token authorization page where the
  695. user may allow or deny this app to access their Google data.
  696. """
  697. uri = atom.http_core.Uri.parse_uri(auth_server)
  698. uri.query['oauth_token'] = token
  699. uri.query['hd'] = hd
  700. if next is not None:
  701. uri.query['oauth_callback'] = str(next)
  702. if hl is not None:
  703. uri.query['hl'] = hl
  704. if btmpl is not None:
  705. uri.query['btmpl'] = btmpl
  706. return uri
  707. def oauth_token_info_from_url(url):
  708. """Exracts an OAuth access token from the redirected page's URL.
  709. Returns:
  710. A tuple of strings containing the OAuth token and the OAuth verifier which
  711. need to sent when upgrading a request token to an access token.
  712. """
  713. if isinstance(url, (str, unicode)):
  714. url = atom.http_core.Uri.parse_uri(url)
  715. token = None
  716. verifier = None
  717. if 'oauth_token' in url.query:
  718. token = urllib.unquote(url.query['oauth_token'])
  719. if 'oauth_verifier' in url.query:
  720. verifier = urllib.unquote(url.query['oauth_verifier'])
  721. return (token, verifier)
  722. def authorize_request_token(request_token, url):
  723. """Adds information to request token to allow it to become an access token.
  724. Modifies the request_token object passed in by setting and unsetting the
  725. necessary fields to allow this token to form a valid upgrade request.
  726. Args:
  727. request_token: The OAuth request token which has been authorized by the
  728. user. In order for this token to be upgraded to an access token,
  729. certain fields must be extracted from the URL and added to the token
  730. so that they can be passed in an upgrade-token request.
  731. url: The URL of the current page which the user's browser was redirected
  732. to after they authorized access for the app. This function extracts
  733. information from the URL which is needed to upgraded the token from
  734. a request token to an access token.
  735. Returns:
  736. The same token object which was passed in.
  737. """
  738. token, verifier = oauth_token_info_from_url(url)
  739. request_token.token = token
  740. request_token.verifier = verifier
  741. request_token.auth_state = AUTHORIZED_REQUEST_TOKEN
  742. return request_token
  743. AuthorizeRequestToken = authorize_request_token
  744. def upgrade_to_access_token(request_token, server_response_body):
  745. """Extracts access token information from response to an upgrade request.
  746. Once the server has responded with the new token info for the OAuth
  747. access token, this method modifies the request_token to set and unset
  748. necessary fields to create valid OAuth authorization headers for requests.
  749. Args:
  750. request_token: An OAuth token which this function modifies to allow it
  751. to be used as an access token.
  752. server_response_body: str The server's response to an OAuthAuthorizeToken
  753. request. This should contain the new token and token_secret which
  754. are used to generate the signature and parameters of the Authorization
  755. header in subsequent requests to Google Data APIs.
  756. Returns:
  757. The same token object which was passed in.
  758. """
  759. token, token_secret = oauth_token_info_from_body(server_response_body)
  760. request_token.token = token
  761. request_token.token_secret = token_secret
  762. request_token.auth_state = ACCESS_TOKEN
  763. request_token.next = None
  764. request_token.verifier = None
  765. return request_token
  766. UpgradeToAccessToken = upgrade_to_access_token
  767. REQUEST_TOKEN = 1
  768. AUTHORIZED_REQUEST_TOKEN = 2
  769. ACCESS_TOKEN = 3
  770. class OAuthHmacToken(object):
  771. SIGNATURE_METHOD = HMAC_SHA1
  772. def __init__(self, consumer_key, consumer_secret, token, token_secret,
  773. auth_state, next=None, verifier=None):
  774. self.consumer_key = consumer_key
  775. self.consumer_secret = consumer_secret
  776. self.token = token
  777. self.token_secret = token_secret
  778. self.auth_state = auth_state
  779. self.next = next
  780. self.verifier = verifier # Used to convert request token to access token.
  781. def generate_authorization_url(
  782. self, google_apps_domain=DEFAULT_DOMAIN, language=None, btmpl=None,
  783. auth_server=OAUTH_AUTHORIZE_URL):
  784. """Creates the URL at which the user can authorize this app to access.
  785. Args:
  786. google_apps_domain: str (optional) If the user should be signing in
  787. using an account under a known Google Apps domain, provide the
  788. domain name ('example.com') here. If not provided, 'default'
  789. will be used, and the user will be prompted to select an account
  790. if they are signed in with a Google Account and Google Apps
  791. accounts.
  792. language: str (optional) An ISO 639 country code identifying what
  793. language the approval page should be translated in (for example,
  794. 'en' for English). The default is the user's selected language.
  795. btmpl: str (optional) Forces a mobile version of the approval page. The
  796. only accepted value is 'mobile'.
  797. auth_server: str (optional) The start of the token authorization web
  798. page. Defaults to
  799. 'https://www.google.com/accounts/OAuthAuthorizeToken'
  800. """
  801. return generate_oauth_authorization_url(
  802. self.token, hd=google_apps_domain, hl=language, btmpl=btmpl,
  803. auth_server=auth_server)
  804. GenerateAuthorizationUrl = generate_authorization_url
  805. def modify_request(self, http_request):
  806. """Sets the Authorization header in the HTTP request using the token.
  807. Calculates an HMAC signature using the information in the token to
  808. indicate that the request came from this application and that this
  809. application has permission to access a particular user's data.
  810. Returns:
  811. The same HTTP request object which was passed in.
  812. """
  813. timestamp = str(int(time.time()))
  814. nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)])
  815. signature = generate_hmac_signature(
  816. http_request, self.consumer_key, self.consumer_secret, timestamp,
  817. nonce, version='1.0', next=self.next, token=self.token,
  818. token_secret=self.token_secret, verifier=self.verifier)
  819. http_request.headers['Authorization'] = generate_auth_header(
  820. self.consumer_key, timestamp, nonce, HMAC_SHA1, signature,
  821. version='1.0', next=self.next, token=self.token,
  822. verifier=self.verifier)
  823. return http_request
  824. ModifyRequest = modify_request
  825. class OAuthRsaToken(OAuthHmacToken):
  826. SIGNATURE_METHOD = RSA_SHA1
  827. def __init__(self, consumer_key, rsa_private_key, token, token_secret,
  828. auth_state, next=None, verifier=None):
  829. self.consumer_key = consumer_key
  830. self.rsa_private_key = rsa_private_key
  831. self.token = token
  832. self.token_secret = token_secret
  833. self.auth_state = auth_state
  834. self.next = next
  835. self.verifier = verifier # Used to convert request token to access token.
  836. def modify_request(self, http_request):
  837. """Sets the Authorization header in the HTTP request using the token.
  838. Calculates an RSA signature using the information in the token to
  839. indicate that the request came from this application and that this
  840. application has permission to access a particular user's data.
  841. Returns:
  842. The same HTTP request object which was passed in.
  843. """
  844. timestamp = str(int(time.time()))
  845. nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)])
  846. signature = generate_rsa_signature(
  847. http_request, self.consumer_key, self.rsa_private_key, timestamp,
  848. nonce, version='1.0', next=self.next, token=self.token,
  849. token_secret=self.token_secret, verifier=self.verifier)
  850. http_request.headers['Authorization'] = generate_auth_header(
  851. self.consumer_key, timestamp, nonce, RSA_SHA1, signature,
  852. version='1.0', next=self.next, token=self.token,
  853. verifier=self.verifier)
  854. return http_request
  855. ModifyRequest = modify_request
  856. class TwoLeggedOAuthHmacToken(OAuthHmacToken):
  857. def __init__(self, consumer_key, consumer_secret, requestor_id):
  858. self.requestor_id = requestor_id
  859. OAuthHmacToken.__init__(
  860. self, consumer_key, consumer_secret, None, None, ACCESS_TOKEN,
  861. next=None, verifier=None)
  862. def modify_request(self, http_request):
  863. """Sets the Authorization header in the HTTP request using the token.
  864. Calculates an HMAC signature using the information in the token to
  865. indicate that the request came from this application and that this
  866. application has permission to access a particular user's data using 2LO.
  867. Returns:
  868. The same HTTP request object which was passed in.
  869. """
  870. http_request.uri.query['xoauth_requestor_id'] = self.requestor_id
  871. return OAuthHmacToken.modify_request(self, http_request)
  872. ModifyRequest = modify_request
  873. class TwoLeggedOAuthRsaToken(OAuthRsaToken):
  874. def __init__(self, consumer_key, rsa_private_key, requestor_id):
  875. self.requestor_id = requestor_id
  876. OAuthRsaToken.__init__(
  877. self, consumer_key, rsa_private_key, None, None, ACCESS_TOKEN,
  878. next=None, verifier=None)
  879. def modify_request(self, http_request):
  880. """Sets the Authorization header in the HTTP request using the token.
  881. Calculates an RSA signature using the information in the token to
  882. indicate that the request came from this application and that this
  883. application has permission to access a particular user's data using 2LO.
  884. Returns:
  885. The same HTTP request object which was passed in.
  886. """
  887. http_request.uri.query['xoauth_requestor_id'] = self.requestor_id
  888. return OAuthRsaToken.modify_request(self, http_request)
  889. ModifyRequest = modify_request
  890. def _join_token_parts(*args):
  891. """"Escapes and combines all strings passed in.
  892. Used to convert a token object's members into a string instead of
  893. using pickle.
  894. Note: A None value will be converted to an empty string.
  895. Returns:
  896. A string in the form 1x|member1|member2|member3...
  897. """
  898. return '|'.join([urllib.quote_plus(a or '') for a in args])
  899. def _split_token_parts(blob):
  900. """Extracts and unescapes fields from the provided binary string.
  901. Reverses the packing performed by _join_token_parts. Used to extract
  902. the members of a token object.
  903. Note: An empty string from the blob will be interpreted as None.
  904. Args:
  905. blob: str A string of the form 1x|member1|member2|member3 as created
  906. by _join_token_parts
  907. Returns:
  908. A list of unescaped strings.
  909. """
  910. return [urllib.unquote_plus(part) or None for part in blob.split('|')]
  911. def token_to_blob(token):
  912. """Serializes the token data as a string for storage in a datastore.
  913. Supported token classes: ClientLoginToken, AuthSubToken, SecureAuthSubToken,
  914. OAuthRsaToken, and OAuthHmacToken, TwoLeggedOAuthRsaToken,
  915. TwoLeggedOAuthHmacToken.
  916. Args:
  917. token: A token object which must be of one of the supported token classes.
  918. Raises:
  919. UnsupportedTokenType if the token is not one of the supported token
  920. classes listed above.
  921. Returns:
  922. A string represenging this token. The string can be converted back into
  923. an equivalent token object using token_from_blob. Note that any members
  924. which are set to '' will be set to None when the token is deserialized
  925. by token_from_blob.
  926. """
  927. if isinstance(token, ClientLoginToken):
  928. return _join_token_parts('1c', token.token_string)
  929. # Check for secure auth sub type first since it is a subclass of
  930. # AuthSubToken.
  931. elif isinstance(token, SecureAuthSubToken):
  932. return _join_token_parts('1s', token.token_string, token.rsa_private_key,
  933. *token.scopes)
  934. elif isinstance(token, AuthSubToken):
  935. return _join_token_parts('1a', token.token_string, *token.scopes)
  936. elif isinstance(token, TwoLeggedOAuthRsaToken):
  937. return _join_token_parts(
  938. '1rtl', token.consumer_key, token.rsa_private_key, token.requestor_id)
  939. elif isinstance(token, TwoLeggedOAuthHmacToken):
  940. return _join_token_parts(
  941. '1htl', token.consumer_key, token.consumer_secret, token.requestor_id)
  942. # Check RSA OAuth token first since the OAuthRsaToken is a subclass of
  943. # OAuthHmacToken.
  944. elif isinstance(token, OAuthRsaToken):
  945. return _join_token_parts(
  946. '1r', token.consumer_key, token.rsa_private_key, token.token,
  947. token.token_secret, str(token.auth_state), token.next,
  948. token.verifier)
  949. elif isinstance(token, OAuthHmacToken):
  950. return _join_token_parts(
  951. '1h', token.consumer_key, token.consumer_secret, token.token,
  952. token.token_secret, str(token.auth_state), token.next,
  953. token.verifier)
  954. else:
  955. raise UnsupportedTokenType(
  956. 'Unable to serialize token of type %s' % type(token))
  957. TokenToBlob = token_to_blob
  958. def token_from_blob(blob):
  959. """Deserializes a token string from the datastore back into a token object.
  960. Supported token classes: ClientLoginToken, AuthSubToken, SecureAuthSubToken,
  961. OAuthRsaToken, and OAuthHmacToken, TwoLeggedOAuthRsaToken,
  962. TwoLeggedOAuthHmacToken.
  963. Args:
  964. blob: string created by token_to_blob.
  965. Raises:
  966. UnsupportedTokenType if the token is not one of the supported token
  967. classes listed above.
  968. Returns:
  969. A new token object with members set to the values serialized in the
  970. blob string. Note that any members which were set to '' in the original
  971. token will now be None.
  972. """
  973. parts = _split_token_parts(blob)
  974. if parts[0] == '1c':
  975. return ClientLoginToken(parts[1])
  976. elif parts[0] == '1a':
  977. return AuthSubToken(parts[1], parts[2:])
  978. elif parts[0] == '1s':
  979. return SecureAuthSubToken(parts[1], parts[2], parts[3:])
  980. elif parts[0] == '1rtl':
  981. return TwoLeggedOAuthRsaToken(parts[1], parts[2], parts[3])
  982. elif parts[0] == '1htl':
  983. return TwoLeggedOAuthHmacToken(parts[1], parts[2], parts[3])
  984. elif parts[0] == '1r':
  985. auth_state = int(parts[5])
  986. return OAuthRsaToken(parts[1], parts[2], parts[3], parts[4], auth_state,
  987. parts[6], parts[7])
  988. elif parts[0] == '1h':
  989. auth_state = int(parts[5])
  990. return OAuthHmacToken(parts[1], parts[2], parts[3], parts[4], auth_state,
  991. parts[6], parts[7])
  992. else:
  993. raise UnsupportedTokenType(
  994. 'Unable to deserialize token with type marker of %s' % parts[0])
  995. TokenFromBlob = token_from_blob
  996. def dump_tokens(tokens):
  997. return ','.join([token_to_blob(t) for t in tokens])
  998. def load_tokens(blob):
  999. return [token_from_blob(s) for s in blob.split(',')]
  1000. def find_scopes_for_services(service_names=None):
  1001. """Creates a combined list of scope URLs for the desired services.
  1002. This method searches the AUTH_SCOPES dictionary.
  1003. Args:
  1004. service_names: list of strings (optional) Each name must be a key in the
  1005. AUTH_SCOPES dictionary. If no list is provided (None) then
  1006. the resulting list will contain all scope URLs in the
  1007. AUTH_SCOPES dict.
  1008. Returns:
  1009. A list of URL strings which are the scopes needed to access these services
  1010. when requesting a token using AuthSub or OAuth.
  1011. """
  1012. result_scopes = []
  1013. if service_names is None:
  1014. for service_name, scopes in AUTH_SCOPES.iteritems():
  1015. result_scopes.extend(scopes)
  1016. else:
  1017. for service_name in service_names:
  1018. result_scopes.extend(AUTH_SCOPES[service_name])
  1019. return result_scopes
  1020. FindScopesForServices = find_scopes_for_services
  1021. def ae_save(token, token_key):
  1022. """Stores an auth token in the App Engine datastore.
  1023. This is a convenience method for using the library with App Engine.
  1024. Recommended usage is to associate the auth token with the current_user.
  1025. If a user is signed in to the app using the App Engine users API, you
  1026. can use
  1027. gdata.gauth.ae_save(some_token, users.get_current_user().user_id())
  1028. If you are not using the Users API you are free to choose whatever
  1029. string you would like for a token_string.
  1030. Args:
  1031. token: an auth token object. Must be one of ClientLoginToken,
  1032. AuthSubToken, SecureAuthSubToken, OAuthRsaToken, or OAuthHmacToken
  1033. (see token_to_blob).
  1034. token_key: str A unique identified to be used when you want to retrieve
  1035. the token. If the user is signed in to App Engine using the
  1036. users API, I recommend using the user ID for the token_key:
  1037. users.get_current_user().user_id()
  1038. """
  1039. import gdata.alt.app_engine
  1040. key_name = ''.join(('gd_auth_token', token_key))
  1041. return gdata.alt.app_engine.set_token(key_name, token_to_blob(token))
  1042. AeSave = ae_save
  1043. def ae_load(token_key):
  1044. """Retrieves a token object from the App Engine datastore.
  1045. This is a convenience method for using the library with App Engine.
  1046. See also ae_save.
  1047. Args:
  1048. token_key: str The unique key associated with the desired token when it
  1049. was saved using ae_save.
  1050. Returns:
  1051. A token object if there was a token associated with the token_key or None
  1052. if the key could not be found.
  1053. """
  1054. import gdata.alt.app_engine
  1055. key_name = ''.join(('gd_auth_token', token_key))
  1056. token_string = gdata.alt.app_engine.get_token(key_name)
  1057. if token_string is not None:
  1058. return token_from_blob(token_string)
  1059. else:
  1060. return None
  1061. AeLoad = ae_load
  1062. def ae_delete(token_key):
  1063. """Removes the token object from the App Engine datastore."""
  1064. import gdata.alt.app_engine
  1065. key_name = ''.join(('gd_auth_token', token_key))
  1066. gdata.alt.app_engine.delete_token(key_name)
  1067. AeDelete = ae_delete