/gdata/auth.py

http://radioappz.googlecode.com/ · Python · 952 lines · 794 code · 29 blank · 129 comment · 58 complexity · 7650c25637770e4937a639a3e0618640 MD5 · raw file

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2007 - 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. import cgi
  17. import math
  18. import random
  19. import re
  20. import time
  21. import types
  22. import urllib
  23. import atom.http_interface
  24. import atom.token_store
  25. import atom.url
  26. import gdata.oauth as oauth
  27. import gdata.oauth.rsa as oauth_rsa
  28. import gdata.tlslite.utils.keyfactory as keyfactory
  29. import gdata.tlslite.utils.cryptomath as cryptomath
  30. import gdata.gauth
  31. __author__ = 'api.jscudder (Jeff Scudder)'
  32. PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth='
  33. AUTHSUB_AUTH_LABEL = 'AuthSub token='
  34. """This module provides functions and objects used with Google authentication.
  35. Details on Google authorization mechanisms used with the Google Data APIs can
  36. be found here:
  37. http://code.google.com/apis/gdata/auth.html
  38. http://code.google.com/apis/accounts/
  39. The essential functions are the following.
  40. Related to ClientLogin:
  41. generate_client_login_request_body: Constructs the body of an HTTP request to
  42. obtain a ClientLogin token for a specific
  43. service.
  44. extract_client_login_token: Creates a ClientLoginToken with the token from a
  45. success response to a ClientLogin request.
  46. get_captcha_challenge: If the server responded to the ClientLogin request
  47. with a CAPTCHA challenge, this method extracts the
  48. CAPTCHA URL and identifying CAPTCHA token.
  49. Related to AuthSub:
  50. generate_auth_sub_url: Constructs a full URL for a AuthSub request. The
  51. user's browser must be sent to this Google Accounts
  52. URL and redirected back to the app to obtain the
  53. AuthSub token.
  54. extract_auth_sub_token_from_url: Once the user's browser has been
  55. redirected back to the web app, use this
  56. function to create an AuthSubToken with
  57. the correct authorization token and scope.
  58. token_from_http_body: Extracts the AuthSubToken value string from the
  59. server's response to an AuthSub session token upgrade
  60. request.
  61. """
  62. def generate_client_login_request_body(email, password, service, source,
  63. account_type='HOSTED_OR_GOOGLE', captcha_token=None,
  64. captcha_response=None):
  65. """Creates the body of the autentication request
  66. See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request
  67. for more details.
  68. Args:
  69. email: str
  70. password: str
  71. service: str
  72. source: str
  73. account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid
  74. values are 'GOOGLE' and 'HOSTED'
  75. captcha_token: str (optional)
  76. captcha_response: str (optional)
  77. Returns:
  78. The HTTP body to send in a request for a client login token.
  79. """
  80. return gdata.gauth.generate_client_login_request_body(email, password,
  81. service, source, account_type, captcha_token, captcha_response)
  82. GenerateClientLoginRequestBody = generate_client_login_request_body
  83. def GenerateClientLoginAuthToken(http_body):
  84. """Returns the token value to use in Authorization headers.
  85. Reads the token from the server's response to a Client Login request and
  86. creates header value to use in requests.
  87. Args:
  88. http_body: str The body of the server's HTTP response to a Client Login
  89. request
  90. Returns:
  91. The value half of an Authorization header.
  92. """
  93. token = get_client_login_token(http_body)
  94. if token:
  95. return 'GoogleLogin auth=%s' % token
  96. return None
  97. def get_client_login_token(http_body):
  98. """Returns the token value for a ClientLoginToken.
  99. Reads the token from the server's response to a Client Login request and
  100. creates the token value string to use in requests.
  101. Args:
  102. http_body: str The body of the server's HTTP response to a Client Login
  103. request
  104. Returns:
  105. The token value string for a ClientLoginToken.
  106. """
  107. return gdata.gauth.get_client_login_token_string(http_body)
  108. def extract_client_login_token(http_body, scopes):
  109. """Parses the server's response and returns a ClientLoginToken.
  110. Args:
  111. http_body: str The body of the server's HTTP response to a Client Login
  112. request. It is assumed that the login request was successful.
  113. scopes: list containing atom.url.Urls or strs. The scopes list contains
  114. all of the partial URLs under which the client login token is
  115. valid. For example, if scopes contains ['http://example.com/foo']
  116. then the client login token would be valid for
  117. http://example.com/foo/bar/baz
  118. Returns:
  119. A ClientLoginToken which is valid for the specified scopes.
  120. """
  121. token_string = get_client_login_token(http_body)
  122. token = ClientLoginToken(scopes=scopes)
  123. token.set_token_string(token_string)
  124. return token
  125. def get_captcha_challenge(http_body,
  126. captcha_base_url='http://www.google.com/accounts/'):
  127. """Returns the URL and token for a CAPTCHA challenge issued by the server.
  128. Args:
  129. http_body: str The body of the HTTP response from the server which
  130. contains the CAPTCHA challenge.
  131. captcha_base_url: str This function returns a full URL for viewing the
  132. challenge image which is built from the server's response. This
  133. base_url is used as the beginning of the URL because the server
  134. only provides the end of the URL. For example the server provides
  135. 'Captcha?ctoken=Hi...N' and the URL for the image is
  136. 'http://www.google.com/accounts/Captcha?ctoken=Hi...N'
  137. Returns:
  138. A dictionary containing the information needed to repond to the CAPTCHA
  139. challenge, the image URL and the ID token of the challenge. The
  140. dictionary is in the form:
  141. {'token': string identifying the CAPTCHA image,
  142. 'url': string containing the URL of the image}
  143. Returns None if there was no CAPTCHA challenge in the response.
  144. """
  145. return gdata.gauth.get_captcha_challenge(http_body, captcha_base_url)
  146. GetCaptchaChallenge = get_captcha_challenge
  147. def GenerateOAuthRequestTokenUrl(
  148. oauth_input_params, scopes,
  149. request_token_url='https://www.google.com/accounts/OAuthGetRequestToken',
  150. extra_parameters=None):
  151. """Generate a URL at which a request for OAuth request token is to be sent.
  152. Args:
  153. oauth_input_params: OAuthInputParams OAuth input parameters.
  154. scopes: list of strings The URLs of the services to be accessed.
  155. request_token_url: string The beginning of the request token URL. This is
  156. normally 'https://www.google.com/accounts/OAuthGetRequestToken' or
  157. '/accounts/OAuthGetRequestToken'
  158. extra_parameters: dict (optional) key-value pairs as any additional
  159. parameters to be included in the URL and signature while making a
  160. request for fetching an OAuth request token. All the OAuth parameters
  161. are added by default. But if provided through this argument, any
  162. default parameters will be overwritten. For e.g. a default parameter
  163. oauth_version 1.0 can be overwritten if
  164. extra_parameters = {'oauth_version': '2.0'}
  165. Returns:
  166. atom.url.Url OAuth request token URL.
  167. """
  168. scopes_string = ' '.join([str(scope) for scope in scopes])
  169. parameters = {'scope': scopes_string}
  170. if extra_parameters:
  171. parameters.update(extra_parameters)
  172. oauth_request = oauth.OAuthRequest.from_consumer_and_token(
  173. oauth_input_params.GetConsumer(), http_url=request_token_url,
  174. parameters=parameters)
  175. oauth_request.sign_request(oauth_input_params.GetSignatureMethod(),
  176. oauth_input_params.GetConsumer(), None)
  177. return atom.url.parse_url(oauth_request.to_url())
  178. def GenerateOAuthAuthorizationUrl(
  179. request_token,
  180. authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken',
  181. callback_url=None, extra_params=None,
  182. include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'):
  183. """Generates URL at which user will login to authorize the request token.
  184. Args:
  185. request_token: gdata.auth.OAuthToken OAuth request token.
  186. authorization_url: string The beginning of the authorization URL. This is
  187. normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or
  188. '/accounts/OAuthAuthorizeToken'
  189. callback_url: string (optional) The URL user will be sent to after
  190. logging in and granting access.
  191. extra_params: dict (optional) Additional parameters to be sent.
  192. include_scopes_in_callback: Boolean (default=False) if set to True, and
  193. if 'callback_url' is present, the 'callback_url' will be modified to
  194. include the scope(s) from the request token as a URL parameter. The
  195. key for the 'callback' URL's scope parameter will be
  196. OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
  197. a parameter to the 'callback' URL, is that the page which receives
  198. the OAuth token will be able to tell which URLs the token grants
  199. access to.
  200. scopes_param_prefix: string (default='oauth_token_scope') The URL
  201. parameter key which maps to the list of valid scopes for the token.
  202. This URL parameter will be included in the callback URL along with
  203. the scopes of the token as value if include_scopes_in_callback=True.
  204. Returns:
  205. atom.url.Url OAuth authorization URL.
  206. """
  207. scopes = request_token.scopes
  208. if isinstance(scopes, list):
  209. scopes = ' '.join(scopes)
  210. if include_scopes_in_callback and callback_url:
  211. if callback_url.find('?') > -1:
  212. callback_url += '&'
  213. else:
  214. callback_url += '?'
  215. callback_url += urllib.urlencode({scopes_param_prefix:scopes})
  216. oauth_token = oauth.OAuthToken(request_token.key, request_token.secret)
  217. oauth_request = oauth.OAuthRequest.from_token_and_callback(
  218. token=oauth_token, callback=callback_url,
  219. http_url=authorization_url, parameters=extra_params)
  220. return atom.url.parse_url(oauth_request.to_url())
  221. def GenerateOAuthAccessTokenUrl(
  222. authorized_request_token,
  223. oauth_input_params,
  224. access_token_url='https://www.google.com/accounts/OAuthGetAccessToken',
  225. oauth_version='1.0',
  226. oauth_verifier=None):
  227. """Generates URL at which user will login to authorize the request token.
  228. Args:
  229. authorized_request_token: gdata.auth.OAuthToken OAuth authorized request
  230. token.
  231. oauth_input_params: OAuthInputParams OAuth input parameters.
  232. access_token_url: string The beginning of the authorization URL. This is
  233. normally 'https://www.google.com/accounts/OAuthGetAccessToken' or
  234. '/accounts/OAuthGetAccessToken'
  235. oauth_version: str (default='1.0') oauth_version parameter.
  236. oauth_verifier: str (optional) If present, it is assumed that the client
  237. will use the OAuth v1.0a protocol which includes passing the
  238. oauth_verifier (as returned by the SP) in the access token step.
  239. Returns:
  240. atom.url.Url OAuth access token URL.
  241. """
  242. oauth_token = oauth.OAuthToken(authorized_request_token.key,
  243. authorized_request_token.secret)
  244. parameters = {'oauth_version': oauth_version}
  245. if oauth_verifier is not None:
  246. parameters['oauth_verifier'] = oauth_verifier
  247. oauth_request = oauth.OAuthRequest.from_consumer_and_token(
  248. oauth_input_params.GetConsumer(), token=oauth_token,
  249. http_url=access_token_url, parameters=parameters)
  250. oauth_request.sign_request(oauth_input_params.GetSignatureMethod(),
  251. oauth_input_params.GetConsumer(), oauth_token)
  252. return atom.url.parse_url(oauth_request.to_url())
  253. def GenerateAuthSubUrl(next, scope, secure=False, session=True,
  254. request_url='https://www.google.com/accounts/AuthSubRequest',
  255. domain='default'):
  256. """Generate a URL at which the user will login and be redirected back.
  257. Users enter their credentials on a Google login page and a token is sent
  258. to the URL specified in next. See documentation for AuthSub login at:
  259. http://code.google.com/apis/accounts/AuthForWebApps.html
  260. Args:
  261. request_url: str The beginning of the request URL. This is normally
  262. 'http://www.google.com/accounts/AuthSubRequest' or
  263. '/accounts/AuthSubRequest'
  264. next: string The URL user will be sent to after logging in.
  265. scope: string The URL of the service to be accessed.
  266. secure: boolean (optional) Determines whether or not the issued token
  267. is a secure token.
  268. session: boolean (optional) Determines whether or not the issued token
  269. can be upgraded to a session token.
  270. domain: str (optional) The Google Apps domain for this account. If this
  271. is not a Google Apps account, use 'default' which is the default
  272. value.
  273. """
  274. # Translate True/False values for parameters into numeric values acceoted
  275. # by the AuthSub service.
  276. if secure:
  277. secure = 1
  278. else:
  279. secure = 0
  280. if session:
  281. session = 1
  282. else:
  283. session = 0
  284. request_params = urllib.urlencode({'next': next, 'scope': scope,
  285. 'secure': secure, 'session': session,
  286. 'hd': domain})
  287. if request_url.find('?') == -1:
  288. return '%s?%s' % (request_url, request_params)
  289. else:
  290. # The request URL already contained url parameters so we should add
  291. # the parameters using the & seperator
  292. return '%s&%s' % (request_url, request_params)
  293. def generate_auth_sub_url(next, scopes, secure=False, session=True,
  294. request_url='https://www.google.com/accounts/AuthSubRequest',
  295. domain='default', scopes_param_prefix='auth_sub_scopes'):
  296. """Constructs a URL string for requesting a multiscope AuthSub token.
  297. The generated token will contain a URL parameter to pass along the
  298. requested scopes to the next URL. When the Google Accounts page
  299. redirects the broswser to the 'next' URL, it appends the single use
  300. AuthSub token value to the URL as a URL parameter with the key 'token'.
  301. However, the information about which scopes were requested is not
  302. included by Google Accounts. This method adds the scopes to the next
  303. URL before making the request so that the redirect will be sent to
  304. a page, and both the token value and the list of scopes can be
  305. extracted from the request URL.
  306. Args:
  307. next: atom.url.URL or string The URL user will be sent to after
  308. authorizing this web application to access their data.
  309. scopes: list containint strings The URLs of the services to be accessed.
  310. secure: boolean (optional) Determines whether or not the issued token
  311. is a secure token.
  312. session: boolean (optional) Determines whether or not the issued token
  313. can be upgraded to a session token.
  314. request_url: atom.url.Url or str The beginning of the request URL. This
  315. is normally 'http://www.google.com/accounts/AuthSubRequest' or
  316. '/accounts/AuthSubRequest'
  317. domain: The domain which the account is part of. This is used for Google
  318. Apps accounts, the default value is 'default' which means that the
  319. requested account is a Google Account (@gmail.com for example)
  320. scopes_param_prefix: str (optional) The requested scopes are added as a
  321. URL parameter to the next URL so that the page at the 'next' URL can
  322. extract the token value and the valid scopes from the URL. The key
  323. for the URL parameter defaults to 'auth_sub_scopes'
  324. Returns:
  325. An atom.url.Url which the user's browser should be directed to in order
  326. to authorize this application to access their information.
  327. """
  328. if isinstance(next, (str, unicode)):
  329. next = atom.url.parse_url(next)
  330. scopes_string = ' '.join([str(scope) for scope in scopes])
  331. next.params[scopes_param_prefix] = scopes_string
  332. if isinstance(request_url, (str, unicode)):
  333. request_url = atom.url.parse_url(request_url)
  334. request_url.params['next'] = str(next)
  335. request_url.params['scope'] = scopes_string
  336. if session:
  337. request_url.params['session'] = 1
  338. else:
  339. request_url.params['session'] = 0
  340. if secure:
  341. request_url.params['secure'] = 1
  342. else:
  343. request_url.params['secure'] = 0
  344. request_url.params['hd'] = domain
  345. return request_url
  346. def AuthSubTokenFromUrl(url):
  347. """Extracts the AuthSub token from the URL.
  348. Used after the AuthSub redirect has sent the user to the 'next' page and
  349. appended the token to the URL. This function returns the value to be used
  350. in the Authorization header.
  351. Args:
  352. url: str The URL of the current page which contains the AuthSub token as
  353. a URL parameter.
  354. """
  355. token = TokenFromUrl(url)
  356. if token:
  357. return 'AuthSub token=%s' % token
  358. return None
  359. def TokenFromUrl(url):
  360. """Extracts the AuthSub token from the URL.
  361. Returns the raw token value.
  362. Args:
  363. url: str The URL or the query portion of the URL string (after the ?) of
  364. the current page which contains the AuthSub token as a URL parameter.
  365. """
  366. if url.find('?') > -1:
  367. query_params = url.split('?')[1]
  368. else:
  369. query_params = url
  370. for pair in query_params.split('&'):
  371. if pair.startswith('token='):
  372. return pair[6:]
  373. return None
  374. def extract_auth_sub_token_from_url(url,
  375. scopes_param_prefix='auth_sub_scopes', rsa_key=None):
  376. """Creates an AuthSubToken and sets the token value and scopes from the URL.
  377. After the Google Accounts AuthSub pages redirect the user's broswer back to
  378. the web application (using the 'next' URL from the request) the web app must
  379. extract the token from the current page's URL. The token is provided as a
  380. URL parameter named 'token' and if generate_auth_sub_url was used to create
  381. the request, the token's valid scopes are included in a URL parameter whose
  382. name is specified in scopes_param_prefix.
  383. Args:
  384. url: atom.url.Url or str representing the current URL. The token value
  385. and valid scopes should be included as URL parameters.
  386. scopes_param_prefix: str (optional) The URL parameter key which maps to
  387. the list of valid scopes for the token.
  388. Returns:
  389. An AuthSubToken with the token value from the URL and set to be valid for
  390. the scopes passed in on the URL. If no scopes were included in the URL,
  391. the AuthSubToken defaults to being valid for no scopes. If there was no
  392. 'token' parameter in the URL, this function returns None.
  393. """
  394. if isinstance(url, (str, unicode)):
  395. url = atom.url.parse_url(url)
  396. if 'token' not in url.params:
  397. return None
  398. scopes = []
  399. if scopes_param_prefix in url.params:
  400. scopes = url.params[scopes_param_prefix].split(' ')
  401. token_value = url.params['token']
  402. if rsa_key:
  403. token = SecureAuthSubToken(rsa_key, scopes=scopes)
  404. else:
  405. token = AuthSubToken(scopes=scopes)
  406. token.set_token_string(token_value)
  407. return token
  408. def AuthSubTokenFromHttpBody(http_body):
  409. """Extracts the AuthSub token from an HTTP body string.
  410. Used to find the new session token after making a request to upgrade a
  411. single use AuthSub token.
  412. Args:
  413. http_body: str The repsonse from the server which contains the AuthSub
  414. key. For example, this function would find the new session token
  415. from the server's response to an upgrade token request.
  416. Returns:
  417. The header value to use for Authorization which contains the AuthSub
  418. token.
  419. """
  420. token_value = token_from_http_body(http_body)
  421. if token_value:
  422. return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value)
  423. return None
  424. def token_from_http_body(http_body):
  425. """Extracts the AuthSub token from an HTTP body string.
  426. Used to find the new session token after making a request to upgrade a
  427. single use AuthSub token.
  428. Args:
  429. http_body: str The repsonse from the server which contains the AuthSub
  430. key. For example, this function would find the new session token
  431. from the server's response to an upgrade token request.
  432. Returns:
  433. The raw token value to use in an AuthSubToken object.
  434. """
  435. for response_line in http_body.splitlines():
  436. if response_line.startswith('Token='):
  437. # Strip off Token= and return the token value string.
  438. return response_line[6:]
  439. return None
  440. TokenFromHttpBody = token_from_http_body
  441. def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'):
  442. """Creates an OAuthToken and sets token key and scopes (if present) from URL.
  443. After the Google Accounts OAuth pages redirect the user's broswer back to
  444. the web application (using the 'callback' URL from the request) the web app
  445. can extract the token from the current page's URL. The token is same as the
  446. request token, but it is either authorized (if user grants access) or
  447. unauthorized (if user denies access). The token is provided as a
  448. URL parameter named 'oauth_token' and if it was chosen to use
  449. GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's
  450. valid scopes are included in a URL parameter whose name is specified in
  451. scopes_param_prefix.
  452. Args:
  453. url: atom.url.Url or str representing the current URL. The token value
  454. and valid scopes should be included as URL parameters.
  455. scopes_param_prefix: str (optional) The URL parameter key which maps to
  456. the list of valid scopes for the token.
  457. Returns:
  458. An OAuthToken with the token key from the URL and set to be valid for
  459. the scopes passed in on the URL. If no scopes were included in the URL,
  460. the OAuthToken defaults to being valid for no scopes. If there was no
  461. 'oauth_token' parameter in the URL, this function returns None.
  462. """
  463. if isinstance(url, (str, unicode)):
  464. url = atom.url.parse_url(url)
  465. if 'oauth_token' not in url.params:
  466. return None
  467. scopes = []
  468. if scopes_param_prefix in url.params:
  469. scopes = url.params[scopes_param_prefix].split(' ')
  470. token_key = url.params['oauth_token']
  471. token = OAuthToken(key=token_key, scopes=scopes)
  472. return token
  473. def OAuthTokenFromHttpBody(http_body):
  474. """Parses the HTTP response body and returns an OAuth token.
  475. The returned OAuth token will just have key and secret parameters set.
  476. It won't have any knowledge about the scopes or oauth_input_params. It is
  477. your responsibility to make it aware of the remaining parameters.
  478. Returns:
  479. OAuthToken OAuth token.
  480. """
  481. token = oauth.OAuthToken.from_string(http_body)
  482. oauth_token = OAuthToken(key=token.key, secret=token.secret)
  483. return oauth_token
  484. class OAuthSignatureMethod(object):
  485. """Holds valid OAuth signature methods.
  486. RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm.
  487. HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm.
  488. """
  489. HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1
  490. class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1):
  491. """Provides implementation for abstract methods to return RSA certs."""
  492. def __init__(self, private_key, public_cert):
  493. self.private_key = private_key
  494. self.public_cert = public_cert
  495. def _fetch_public_cert(self, unused_oauth_request):
  496. return self.public_cert
  497. def _fetch_private_cert(self, unused_oauth_request):
  498. return self.private_key
  499. class OAuthInputParams(object):
  500. """Stores OAuth input parameters.
  501. This class is a store for OAuth input parameters viz. consumer key and secret,
  502. signature method and RSA key.
  503. """
  504. def __init__(self, signature_method, consumer_key, consumer_secret=None,
  505. rsa_key=None, requestor_id=None):
  506. """Initializes object with parameters required for using OAuth mechanism.
  507. NOTE: Though consumer_secret and rsa_key are optional, either of the two
  508. is required depending on the value of the signature_method.
  509. Args:
  510. signature_method: class which provides implementation for strategy class
  511. oauth.oauth.OAuthSignatureMethod. Signature method to be used for
  512. signing each request. Valid implementations are provided as the
  513. constants defined by gdata.auth.OAuthSignatureMethod. Currently
  514. they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
  515. gdata.auth.OAuthSignatureMethod.HMAC_SHA1. Instead of passing in
  516. the strategy class, you may pass in a string for 'RSA_SHA1' or
  517. 'HMAC_SHA1'. If you plan to use OAuth on App Engine (or another
  518. WSGI environment) I recommend specifying signature method using a
  519. string (the only options are 'RSA_SHA1' and 'HMAC_SHA1'). In these
  520. environments there are sometimes issues with pickling an object in
  521. which a member references a class or function. Storing a string to
  522. refer to the signature method mitigates complications when
  523. pickling.
  524. consumer_key: string Domain identifying third_party web application.
  525. consumer_secret: string (optional) Secret generated during registration.
  526. Required only for HMAC_SHA1 signature method.
  527. rsa_key: string (optional) Private key required for RSA_SHA1 signature
  528. method.
  529. requestor_id: string (optional) User email adress to make requests on
  530. their behalf. This parameter should only be set when performing
  531. 2 legged OAuth requests.
  532. """
  533. if (signature_method == OAuthSignatureMethod.RSA_SHA1
  534. or signature_method == 'RSA_SHA1'):
  535. self.__signature_strategy = 'RSA_SHA1'
  536. elif (signature_method == OAuthSignatureMethod.HMAC_SHA1
  537. or signature_method == 'HMAC_SHA1'):
  538. self.__signature_strategy = 'HMAC_SHA1'
  539. else:
  540. self.__signature_strategy = signature_method
  541. self.rsa_key = rsa_key
  542. self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
  543. self.requestor_id = requestor_id
  544. def __get_signature_method(self):
  545. if self.__signature_strategy == 'RSA_SHA1':
  546. return OAuthSignatureMethod.RSA_SHA1(self.rsa_key, None)
  547. elif self.__signature_strategy == 'HMAC_SHA1':
  548. return OAuthSignatureMethod.HMAC_SHA1()
  549. else:
  550. return self.__signature_strategy()
  551. def __set_signature_method(self, signature_method):
  552. if (signature_method == OAuthSignatureMethod.RSA_SHA1
  553. or signature_method == 'RSA_SHA1'):
  554. self.__signature_strategy = 'RSA_SHA1'
  555. elif (signature_method == OAuthSignatureMethod.HMAC_SHA1
  556. or signature_method == 'HMAC_SHA1'):
  557. self.__signature_strategy = 'HMAC_SHA1'
  558. else:
  559. self.__signature_strategy = signature_method
  560. _signature_method = property(__get_signature_method, __set_signature_method,
  561. doc="""Returns object capable of signing the request using RSA of HMAC.
  562. Replaces the _signature_method member to avoid pickle errors.""")
  563. def GetSignatureMethod(self):
  564. """Gets the OAuth signature method.
  565. Returns:
  566. object of supertype <oauth.oauth.OAuthSignatureMethod>
  567. """
  568. return self._signature_method
  569. def GetConsumer(self):
  570. """Gets the OAuth consumer.
  571. Returns:
  572. object of type <oauth.oauth.Consumer>
  573. """
  574. return self._consumer
  575. class ClientLoginToken(atom.http_interface.GenericToken):
  576. """Stores the Authorization header in auth_header and adds to requests.
  577. This token will add it's Authorization header to an HTTP request
  578. as it is made. Ths token class is simple but
  579. some Token classes must calculate portions of the Authorization header
  580. based on the request being made, which is why the token is responsible
  581. for making requests via an http_client parameter.
  582. Args:
  583. auth_header: str The value for the Authorization header.
  584. scopes: list of str or atom.url.Url specifying the beginnings of URLs
  585. for which this token can be used. For example, if scopes contains
  586. 'http://example.com/foo', then this token can be used for a request to
  587. 'http://example.com/foo/bar' but it cannot be used for a request to
  588. 'http://example.com/baz'
  589. """
  590. def __init__(self, auth_header=None, scopes=None):
  591. self.auth_header = auth_header
  592. self.scopes = scopes or []
  593. def __str__(self):
  594. return self.auth_header
  595. def perform_request(self, http_client, operation, url, data=None,
  596. headers=None):
  597. """Sets the Authorization header and makes the HTTP request."""
  598. if headers is None:
  599. headers = {'Authorization':self.auth_header}
  600. else:
  601. headers['Authorization'] = self.auth_header
  602. return http_client.request(operation, url, data=data, headers=headers)
  603. def get_token_string(self):
  604. """Removes PROGRAMMATIC_AUTH_LABEL to give just the token value."""
  605. return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):]
  606. def set_token_string(self, token_string):
  607. self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string)
  608. def valid_for_scope(self, url):
  609. """Tells the caller if the token authorizes access to the desired URL.
  610. """
  611. if isinstance(url, (str, unicode)):
  612. url = atom.url.parse_url(url)
  613. for scope in self.scopes:
  614. if scope == atom.token_store.SCOPE_ALL:
  615. return True
  616. if isinstance(scope, (str, unicode)):
  617. scope = atom.url.parse_url(scope)
  618. if scope == url:
  619. return True
  620. # Check the host and the path, but ignore the port and protocol.
  621. elif scope.host == url.host and not scope.path:
  622. return True
  623. elif scope.host == url.host and scope.path and not url.path:
  624. continue
  625. elif scope.host == url.host and url.path.startswith(scope.path):
  626. return True
  627. return False
  628. class AuthSubToken(ClientLoginToken):
  629. def get_token_string(self):
  630. """Removes AUTHSUB_AUTH_LABEL to give just the token value."""
  631. return self.auth_header[len(AUTHSUB_AUTH_LABEL):]
  632. def set_token_string(self, token_string):
  633. self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string)
  634. class OAuthToken(atom.http_interface.GenericToken):
  635. """Stores the token key, token secret and scopes for which token is valid.
  636. This token adds the authorization header to each request made. It
  637. re-calculates authorization header for every request since the OAuth
  638. signature to be added to the authorization header is dependent on the
  639. request parameters.
  640. Attributes:
  641. key: str The value for the OAuth token i.e. token key.
  642. secret: str The value for the OAuth token secret.
  643. scopes: list of str or atom.url.Url specifying the beginnings of URLs
  644. for which this token can be used. For example, if scopes contains
  645. 'http://example.com/foo', then this token can be used for a request to
  646. 'http://example.com/foo/bar' but it cannot be used for a request to
  647. 'http://example.com/baz'
  648. oauth_input_params: OAuthInputParams OAuth input parameters.
  649. """
  650. def __init__(self, key=None, secret=None, scopes=None,
  651. oauth_input_params=None):
  652. self.key = key
  653. self.secret = secret
  654. self.scopes = scopes or []
  655. self.oauth_input_params = oauth_input_params
  656. def __str__(self):
  657. return self.get_token_string()
  658. def get_token_string(self):
  659. """Returns the token string.
  660. The token string returned is of format
  661. oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings.
  662. Returns:
  663. A token string of format oauth_token=[0]&oauth_token_secret=[1],
  664. where [0] and [1] are some strings. If self.secret is absent, it just
  665. returns oauth_token=[0]. If self.key is absent, it just returns
  666. oauth_token_secret=[1]. If both are absent, it returns None.
  667. """
  668. if self.key and self.secret:
  669. return urllib.urlencode({'oauth_token': self.key,
  670. 'oauth_token_secret': self.secret})
  671. elif self.key:
  672. return 'oauth_token=%s' % self.key
  673. elif self.secret:
  674. return 'oauth_token_secret=%s' % self.secret
  675. else:
  676. return None
  677. def set_token_string(self, token_string):
  678. """Sets the token key and secret from the token string.
  679. Args:
  680. token_string: str Token string of form
  681. oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present,
  682. self.key will be None. If oauth_token_secret is not present,
  683. self.secret will be None.
  684. """
  685. token_params = cgi.parse_qs(token_string, keep_blank_values=False)
  686. if 'oauth_token' in token_params:
  687. self.key = token_params['oauth_token'][0]
  688. if 'oauth_token_secret' in token_params:
  689. self.secret = token_params['oauth_token_secret'][0]
  690. def GetAuthHeader(self, http_method, http_url, realm=''):
  691. """Get the authentication header.
  692. Args:
  693. http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
  694. http_url: string or atom.url.Url HTTP URL to which request is made.
  695. realm: string (default='') realm parameter to be included in the
  696. authorization header.
  697. Returns:
  698. dict Header to be sent with every subsequent request after
  699. authentication.
  700. """
  701. if isinstance(http_url, types.StringTypes):
  702. http_url = atom.url.parse_url(http_url)
  703. header = None
  704. token = None
  705. if self.key or self.secret:
  706. token = oauth.OAuthToken(self.key, self.secret)
  707. oauth_request = oauth.OAuthRequest.from_consumer_and_token(
  708. self.oauth_input_params.GetConsumer(), token=token,
  709. http_url=str(http_url), http_method=http_method,
  710. parameters=http_url.params)
  711. oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(),
  712. self.oauth_input_params.GetConsumer(), token)
  713. header = oauth_request.to_header(realm=realm)
  714. header['Authorization'] = header['Authorization'].replace('+', '%2B')
  715. return header
  716. def perform_request(self, http_client, operation, url, data=None,
  717. headers=None):
  718. """Sets the Authorization header and makes the HTTP request."""
  719. if not headers:
  720. headers = {}
  721. if self.oauth_input_params.requestor_id:
  722. url.params['xoauth_requestor_id'] = self.oauth_input_params.requestor_id
  723. headers.update(self.GetAuthHeader(operation, url))
  724. return http_client.request(operation, url, data=data, headers=headers)
  725. def valid_for_scope(self, url):
  726. if isinstance(url, (str, unicode)):
  727. url = atom.url.parse_url(url)
  728. for scope in self.scopes:
  729. if scope == atom.token_store.SCOPE_ALL:
  730. return True
  731. if isinstance(scope, (str, unicode)):
  732. scope = atom.url.parse_url(scope)
  733. if scope == url:
  734. return True
  735. # Check the host and the path, but ignore the port and protocol.
  736. elif scope.host == url.host and not scope.path:
  737. return True
  738. elif scope.host == url.host and scope.path and not url.path:
  739. continue
  740. elif scope.host == url.host and url.path.startswith(scope.path):
  741. return True
  742. return False
  743. class SecureAuthSubToken(AuthSubToken):
  744. """Stores the rsa private key, token, and scopes for the secure AuthSub token.
  745. This token adds the authorization header to each request made. It
  746. re-calculates authorization header for every request since the secure AuthSub
  747. signature to be added to the authorization header is dependent on the
  748. request parameters.
  749. Attributes:
  750. rsa_key: string The RSA private key in PEM format that the token will
  751. use to sign requests
  752. token_string: string (optional) The value for the AuthSub token.
  753. scopes: list of str or atom.url.Url specifying the beginnings of URLs
  754. for which this token can be used. For example, if scopes contains
  755. 'http://example.com/foo', then this token can be used for a request to
  756. 'http://example.com/foo/bar' but it cannot be used for a request to
  757. 'http://example.com/baz'
  758. """
  759. def __init__(self, rsa_key, token_string=None, scopes=None):
  760. self.rsa_key = keyfactory.parsePEMKey(rsa_key)
  761. self.token_string = token_string or ''
  762. self.scopes = scopes or []
  763. def __str__(self):
  764. return self.get_token_string()
  765. def get_token_string(self):
  766. return str(self.token_string)
  767. def set_token_string(self, token_string):
  768. self.token_string = token_string
  769. def GetAuthHeader(self, http_method, http_url):
  770. """Generates the Authorization header.
  771. The form of the secure AuthSub Authorization header is
  772. Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig"
  773. and data represents a string in the form
  774. data = http_method http_url timestamp nonce
  775. Args:
  776. http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
  777. http_url: string or atom.url.Url HTTP URL to which request is made.
  778. Returns:
  779. dict Header to be sent with every subsequent request after authentication.
  780. """
  781. timestamp = int(math.floor(time.time()))
  782. nonce = '%lu' % random.randrange(1, 2**64)
  783. data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce)
  784. sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data))
  785. header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' %
  786. (AUTHSUB_AUTH_LABEL, self.token_string, data, sig)}
  787. return header
  788. def perform_request(self, http_client, operation, url, data=None,
  789. headers=None):
  790. """Sets the Authorization header and makes the HTTP request."""
  791. if not headers:
  792. headers = {}
  793. headers.update(self.GetAuthHeader(operation, url))
  794. return http_client.request(operation, url, data=data, headers=headers)