__init__.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. """
  2. The MIT License
  3. Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. """
  20. import base64
  21. import urllib
  22. import time
  23. import random
  24. import urlparse
  25. import hmac
  26. import binascii
  27. import httplib2
  28. try:
  29. from urlparse import parse_qs
  30. parse_qs # placate pyflakes
  31. except ImportError:
  32. # fall back for Python 2.5
  33. from cgi import parse_qs
  34. try:
  35. from hashlib import sha1
  36. sha = sha1
  37. except ImportError:
  38. # hashlib was added in Python 2.5
  39. import sha
  40. import _version
  41. __version__ = _version.__version__
  42. OAUTH_VERSION = '1.0' # Hi Blaine!
  43. HTTP_METHOD = 'GET'
  44. SIGNATURE_METHOD = 'PLAINTEXT'
  45. class Error(RuntimeError):
  46. """Generic exception class."""
  47. def __init__(self, message='OAuth error occurred.'):
  48. self._message = message
  49. @property
  50. def message(self):
  51. """A hack to get around the deprecation errors in 2.6."""
  52. return self._message
  53. def __str__(self):
  54. return self._message
  55. class MissingSignature(Error):
  56. pass
  57. def build_authenticate_header(realm=''):
  58. """Optional WWW-Authenticate header (401 error)"""
  59. return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
  60. def build_xoauth_string(url, consumer, token=None):
  61. """Build an XOAUTH string for use in SMTP/IMPA authentication."""
  62. request = Request.from_consumer_and_token(consumer, token,
  63. "GET", url)
  64. signing_method = SignatureMethod_HMAC_SHA1()
  65. request.sign_request(signing_method, consumer, token)
  66. params = []
  67. for k, v in sorted(request.iteritems()):
  68. if v is not None:
  69. params.append('%s="%s"' % (k, escape(v)))
  70. return "%s %s %s" % ("GET", url, ','.join(params))
  71. def to_unicode(s):
  72. """ Convert to unicode, raise exception with instructive error
  73. message if s is not unicode, ascii, or utf-8. """
  74. if not isinstance(s, unicode):
  75. if not isinstance(s, str):
  76. raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s))
  77. try:
  78. s = s.decode('utf-8')
  79. except UnicodeDecodeError, le:
  80. raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,))
  81. return s
  82. def to_utf8(s):
  83. return to_unicode(s).encode('utf-8')
  84. def to_unicode_if_string(s):
  85. if isinstance(s, basestring):
  86. return to_unicode(s)
  87. else:
  88. return s
  89. def to_utf8_if_string(s):
  90. if isinstance(s, basestring):
  91. return to_utf8(s)
  92. else:
  93. return s
  94. def to_unicode_optional_iterator(x):
  95. """
  96. Raise TypeError if x is a str containing non-utf8 bytes or if x is
  97. an iterable which contains such a str.
  98. """
  99. if isinstance(x, basestring):
  100. return to_unicode(x)
  101. try:
  102. l = list(x)
  103. except TypeError, e:
  104. assert 'is not iterable' in str(e)
  105. return x
  106. else:
  107. return [ to_unicode(e) for e in l ]
  108. def to_utf8_optional_iterator(x):
  109. """
  110. Raise TypeError if x is a str or if x is an iterable which
  111. contains a str.
  112. """
  113. if isinstance(x, basestring):
  114. return to_utf8(x)
  115. try:
  116. l = list(x)
  117. except TypeError, e:
  118. assert 'is not iterable' in str(e)
  119. return x
  120. else:
  121. return [ to_utf8_if_string(e) for e in l ]
  122. def escape(s):
  123. """Escape a URL including any /."""
  124. return urllib.quote(s.encode('utf-8'), safe='~')
  125. def generate_timestamp():
  126. """Get seconds since epoch (UTC)."""
  127. return int(time.time())
  128. def generate_nonce(length=8):
  129. """Generate pseudorandom number."""
  130. return ''.join([str(random.randint(0, 9)) for i in range(length)])
  131. def generate_verifier(length=8):
  132. """Generate pseudorandom number."""
  133. return ''.join([str(random.randint(0, 9)) for i in range(length)])
  134. class Consumer(object):
  135. """A consumer of OAuth-protected services.
  136. The OAuth consumer is a "third-party" service that wants to access
  137. protected resources from an OAuth service provider on behalf of an end
  138. user. It's kind of the OAuth client.
  139. Usually a consumer must be registered with the service provider by the
  140. developer of the consumer software. As part of that process, the service
  141. provider gives the consumer a *key* and a *secret* with which the consumer
  142. software can identify itself to the service. The consumer will include its
  143. key in each request to identify itself, but will use its secret only when
  144. signing requests, to prove that the request is from that particular
  145. registered consumer.
  146. Once registered, the consumer can then use its consumer credentials to ask
  147. the service provider for a request token, kicking off the OAuth
  148. authorization process.
  149. """
  150. key = None
  151. secret = None
  152. def __init__(self, key, secret):
  153. self.key = key
  154. self.secret = secret
  155. if self.key is None or self.secret is None:
  156. raise ValueError("Key and secret must be set.")
  157. def __str__(self):
  158. data = {'oauth_consumer_key': self.key,
  159. 'oauth_consumer_secret': self.secret}
  160. return urllib.urlencode(data)
  161. class Token(object):
  162. """An OAuth credential used to request authorization or a protected
  163. resource.
  164. Tokens in OAuth comprise a *key* and a *secret*. The key is included in
  165. requests to identify the token being used, but the secret is used only in
  166. the signature, to prove that the requester is who the server gave the
  167. token to.
  168. When first negotiating the authorization, the consumer asks for a *request
  169. token* that the live user authorizes with the service provider. The
  170. consumer then exchanges the request token for an *access token* that can
  171. be used to access protected resources.
  172. """
  173. key = None
  174. secret = None
  175. callback = None
  176. callback_confirmed = None
  177. verifier = None
  178. def __init__(self, key, secret):
  179. self.key = key
  180. self.secret = secret
  181. if self.key is None or self.secret is None:
  182. raise ValueError("Key and secret must be set.")
  183. def set_callback(self, callback):
  184. self.callback = callback
  185. self.callback_confirmed = 'true'
  186. def set_verifier(self, verifier=None):
  187. if verifier is not None:
  188. self.verifier = verifier
  189. else:
  190. self.verifier = generate_verifier()
  191. def get_callback_url(self):
  192. if self.callback and self.verifier:
  193. # Append the oauth_verifier.
  194. parts = urlparse.urlparse(self.callback)
  195. scheme, netloc, path, params, query, fragment = parts[:6]
  196. if query:
  197. query = '%s&oauth_verifier=%s' % (query, self.verifier)
  198. else:
  199. query = 'oauth_verifier=%s' % self.verifier
  200. return urlparse.urlunparse((scheme, netloc, path, params,
  201. query, fragment))
  202. return self.callback
  203. def to_string(self):
  204. """Returns this token as a plain string, suitable for storage.
  205. The resulting string includes the token's secret, so you should never
  206. send or store this string where a third party can read it.
  207. """
  208. data = {
  209. 'oauth_token': self.key,
  210. 'oauth_token_secret': self.secret,
  211. }
  212. if self.callback_confirmed is not None:
  213. data['oauth_callback_confirmed'] = self.callback_confirmed
  214. return urllib.urlencode(data)
  215. @staticmethod
  216. def from_string(s):
  217. """Deserializes a token from a string like one returned by
  218. `to_string()`."""
  219. if not len(s):
  220. raise ValueError("Invalid parameter string.")
  221. params = parse_qs(s, keep_blank_values=False)
  222. if not len(params):
  223. raise ValueError("Invalid parameter string.")
  224. try:
  225. key = params['oauth_token'][0]
  226. except Exception:
  227. raise ValueError("'oauth_token' not found in OAuth request.")
  228. try:
  229. secret = params['oauth_token_secret'][0]
  230. except Exception:
  231. raise ValueError("'oauth_token_secret' not found in "
  232. "OAuth request.")
  233. token = Token(key, secret)
  234. try:
  235. token.callback_confirmed = params['oauth_callback_confirmed'][0]
  236. except KeyError:
  237. pass # 1.0, no callback confirmed.
  238. return token
  239. def __str__(self):
  240. return self.to_string()
  241. def setter(attr):
  242. name = attr.__name__
  243. def getter(self):
  244. try:
  245. return self.__dict__[name]
  246. except KeyError:
  247. raise AttributeError(name)
  248. def deleter(self):
  249. del self.__dict__[name]
  250. return property(getter, attr, deleter)
  251. class Request(dict):
  252. """The parameters and information for an HTTP request, suitable for
  253. authorizing with OAuth credentials.
  254. When a consumer wants to access a service's protected resources, it does
  255. so using a signed HTTP request identifying itself (the consumer) with its
  256. key, and providing an access token authorized by the end user to access
  257. those resources.
  258. """
  259. version = OAUTH_VERSION
  260. def __init__(self, method=HTTP_METHOD, url=None, parameters=None,
  261. body='', is_form_encoded=False):
  262. if url is not None:
  263. self.url = to_unicode(url)
  264. self.method = method
  265. if parameters is not None:
  266. for k, v in parameters.iteritems():
  267. k = to_unicode(k)
  268. v = to_unicode_optional_iterator(v)
  269. self[k] = v
  270. self.body = body
  271. self.is_form_encoded = is_form_encoded
  272. @setter
  273. def url(self, value):
  274. self.__dict__['url'] = value
  275. if value is not None:
  276. scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
  277. # Exclude default port numbers.
  278. if scheme == 'http' and netloc[-3:] == ':80':
  279. netloc = netloc[:-3]
  280. elif scheme == 'https' and netloc[-4:] == ':443':
  281. netloc = netloc[:-4]
  282. if scheme not in ('http', 'https'):
  283. raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
  284. # Normalized URL excludes params, query, and fragment.
  285. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
  286. else:
  287. self.normalized_url = None
  288. self.__dict__['url'] = None
  289. @setter
  290. def method(self, value):
  291. self.__dict__['method'] = value.upper()
  292. def _get_timestamp_nonce(self):
  293. return self['oauth_timestamp'], self['oauth_nonce']
  294. def get_nonoauth_parameters(self):
  295. """Get any non-OAuth parameters."""
  296. return dict([(k, v) for k, v in self.iteritems()
  297. if not k.startswith('oauth_')])
  298. def to_header(self, realm=''):
  299. """Serialize as a header for an HTTPAuth request."""
  300. oauth_params = ((k, v) for k, v in self.items()
  301. if k.startswith('oauth_'))
  302. stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
  303. header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
  304. params_header = ', '.join(header_params)
  305. auth_header = 'OAuth realm="%s"' % realm
  306. if params_header:
  307. auth_header = "%s, %s" % (auth_header, params_header)
  308. return {'Authorization': auth_header}
  309. def to_postdata(self):
  310. """Serialize as post data for a POST request."""
  311. d = {}
  312. for k, v in self.iteritems():
  313. d[k.encode('utf-8')] = to_utf8_optional_iterator(v)
  314. # tell urlencode to deal with sequence values and map them correctly
  315. # to resulting querystring. for example self["k"] = ["v1", "v2"] will
  316. # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
  317. return urllib.urlencode(d, True).replace('+', '%20')
  318. def to_url(self):
  319. """Serialize as a URL for a GET request."""
  320. base_url = urlparse.urlparse(self.url)
  321. try:
  322. query = base_url.query
  323. except AttributeError:
  324. # must be python <2.5
  325. query = base_url[4]
  326. query = parse_qs(query)
  327. for k, v in self.items():
  328. query.setdefault(k, []).append(v)
  329. try:
  330. scheme = base_url.scheme
  331. netloc = base_url.netloc
  332. path = base_url.path
  333. params = base_url.params
  334. fragment = base_url.fragment
  335. except AttributeError:
  336. # must be python <2.5
  337. scheme = base_url[0]
  338. netloc = base_url[1]
  339. path = base_url[2]
  340. params = base_url[3]
  341. fragment = base_url[5]
  342. url = (scheme, netloc, path, params,
  343. urllib.urlencode(query, True), fragment)
  344. return urlparse.urlunparse(url)
  345. def get_parameter(self, parameter):
  346. ret = self.get(parameter)
  347. if ret is None:
  348. raise Error('Parameter not found: %s' % parameter)
  349. return ret
  350. def get_normalized_parameters(self):
  351. """Return a string that contains the parameters that must be signed."""
  352. items = []
  353. for key, value in self.iteritems():
  354. if key == 'oauth_signature':
  355. continue
  356. # 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
  357. # so we unpack sequence values into multiple items for sorting.
  358. if isinstance(value, basestring):
  359. items.append((to_utf8_if_string(key), to_utf8(value)))
  360. else:
  361. try:
  362. value = list(value)
  363. except TypeError, e:
  364. assert 'is not iterable' in str(e)
  365. items.append((to_utf8_if_string(key), to_utf8_if_string(value)))
  366. else:
  367. items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value)
  368. # Include any query string parameters from the provided URL
  369. query = urlparse.urlparse(self.url)[4]
  370. url_items = self._split_url_string(query).items()
  371. url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ]
  372. items.extend(url_items)
  373. items.sort()
  374. encoded_str = urllib.urlencode(items)
  375. # Encode signature parameters per Oauth Core 1.0 protocol
  376. # spec draft 7, section 3.6
  377. # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
  378. # Spaces must be encoded with "%20" instead of "+"
  379. return encoded_str.replace('+', '%20').replace('%7E', '~')
  380. def sign_request(self, signature_method, consumer, token):
  381. """Set the signature parameter to the result of sign."""
  382. if not self.is_form_encoded:
  383. # according to
  384. # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
  385. # section 4.1.1 "OAuth Consumers MUST NOT include an
  386. # oauth_body_hash parameter on requests with form-encoded
  387. # request bodies."
  388. self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest())
  389. if 'oauth_consumer_key' not in self:
  390. self['oauth_consumer_key'] = consumer.key
  391. if token and 'oauth_token' not in self:
  392. self['oauth_token'] = token.key
  393. self['oauth_signature_method'] = signature_method.name
  394. self['oauth_signature'] = signature_method.sign(self, consumer, token)
  395. @classmethod
  396. def make_timestamp(cls):
  397. """Get seconds since epoch (UTC)."""
  398. return str(int(time.time()))
  399. @classmethod
  400. def make_nonce(cls):
  401. """Generate pseudorandom number."""
  402. return str(random.randint(0, 100000000))
  403. @classmethod
  404. def from_request(cls, http_method, http_url, headers=None, parameters=None,
  405. query_string=None):
  406. """Combines multiple parameter sources."""
  407. if parameters is None:
  408. parameters = {}
  409. # Headers
  410. if headers and 'Authorization' in headers:
  411. auth_header = headers['Authorization']
  412. # Check that the authorization header is OAuth.
  413. if auth_header[:6] == 'OAuth ':
  414. auth_header = auth_header[6:]
  415. try:
  416. # Get the parameters from the header.
  417. header_params = cls._split_header(auth_header)
  418. parameters.update(header_params)
  419. except:
  420. raise Error('Unable to parse OAuth parameters from '
  421. 'Authorization header.')
  422. # GET or POST query string.
  423. if query_string:
  424. query_params = cls._split_url_string(query_string)
  425. parameters.update(query_params)
  426. # URL parameters.
  427. param_str = urlparse.urlparse(http_url)[4] # query
  428. url_params = cls._split_url_string(param_str)
  429. parameters.update(url_params)
  430. if parameters:
  431. return cls(http_method, http_url, parameters)
  432. return None
  433. @classmethod
  434. def from_consumer_and_token(cls, consumer, token=None,
  435. http_method=HTTP_METHOD, http_url=None, parameters=None,
  436. body='', is_form_encoded=False):
  437. if not parameters:
  438. parameters = {}
  439. defaults = {
  440. 'oauth_consumer_key': consumer.key,
  441. 'oauth_timestamp': cls.make_timestamp(),
  442. 'oauth_nonce': cls.make_nonce(),
  443. 'oauth_version': cls.version,
  444. }
  445. defaults.update(parameters)
  446. parameters = defaults
  447. if token:
  448. parameters['oauth_token'] = token.key
  449. if token.verifier:
  450. parameters['oauth_verifier'] = token.verifier
  451. return Request(http_method, http_url, parameters, body=body,
  452. is_form_encoded=is_form_encoded)
  453. @classmethod
  454. def from_token_and_callback(cls, token, callback=None,
  455. http_method=HTTP_METHOD, http_url=None, parameters=None):
  456. if not parameters:
  457. parameters = {}
  458. parameters['oauth_token'] = token.key
  459. if callback:
  460. parameters['oauth_callback'] = callback
  461. return cls(http_method, http_url, parameters)
  462. @staticmethod
  463. def _split_header(header):
  464. """Turn Authorization: header into parameters."""
  465. params = {}
  466. parts = header.split(',')
  467. for param in parts:
  468. # Ignore realm parameter.
  469. if param.find('realm') > -1:
  470. continue
  471. # Remove whitespace.
  472. param = param.strip()
  473. # Split key-value.
  474. param_parts = param.split('=', 1)
  475. # Remove quotes and unescape the value.
  476. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
  477. return params
  478. @staticmethod
  479. def _split_url_string(param_str):
  480. """Turn URL string into parameters."""
  481. parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True)
  482. for k, v in parameters.iteritems():
  483. parameters[k] = urllib.unquote(v[0])
  484. return parameters
  485. class Client(httplib2.Http):
  486. """OAuthClient is a worker to attempt to execute a request."""
  487. def __init__(self, consumer, token=None, cache=None, timeout=None,
  488. proxy_info=None):
  489. if consumer is not None and not isinstance(consumer, Consumer):
  490. raise ValueError("Invalid consumer.")
  491. if token is not None and not isinstance(token, Token):
  492. raise ValueError("Invalid token.")
  493. self.consumer = consumer
  494. self.token = token
  495. self.method = SignatureMethod_HMAC_SHA1()
  496. httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
  497. def set_signature_method(self, method):
  498. if not isinstance(method, SignatureMethod):
  499. raise ValueError("Invalid signature method.")
  500. self.method = method
  501. def request(self, uri, method="GET", body='', headers=None,
  502. redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
  503. DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
  504. if not isinstance(headers, dict):
  505. headers = {}
  506. if method == "POST":
  507. headers['Content-Type'] = headers.get('Content-Type',
  508. DEFAULT_POST_CONTENT_TYPE)
  509. is_form_encoded = \
  510. headers.get('Content-Type') == 'application/x-www-form-urlencoded'
  511. if is_form_encoded and body:
  512. parameters = parse_qs(body)
  513. else:
  514. parameters = None
  515. req = Request.from_consumer_and_token(self.consumer,
  516. token=self.token, http_method=method, http_url=uri,
  517. parameters=parameters, body=body, is_form_encoded=is_form_encoded)
  518. req.sign_request(self.method, self.consumer, self.token)
  519. schema, rest = urllib.splittype(uri)
  520. if rest.startswith('//'):
  521. hierpart = '//'
  522. else:
  523. hierpart = ''
  524. host, rest = urllib.splithost(rest)
  525. realm = schema + ':' + hierpart + host
  526. if is_form_encoded:
  527. body = req.to_postdata()
  528. elif method == "GET":
  529. uri = req.to_url()
  530. else:
  531. headers.update(req.to_header(realm=realm))
  532. try:
  533. return httplib2.Http.request(self, uri, method=method, body=body,
  534. headers=headers, redirections=redirections,
  535. connection_type=connection_type)
  536. except Exception as e:
  537. if (type(e[0]) is unicode or type(e[0]) is str) and e[0][0:53] == "Server presented certificate that does not match host":
  538. httplib2.Http.disable_ssl_certificate_validation = True
  539. return httplib2.Http.request(self, uri, method=method, body=body,
  540. headers=headers, redirections=redirections,
  541. connection_type=connection_type)
  542. else:
  543. raise Error(e[0])
  544. class Server(object):
  545. """A skeletal implementation of a service provider, providing protected
  546. resources to requests from authorized consumers.
  547. This class implements the logic to check requests for authorization. You
  548. can use it with your web server or web framework to protect certain
  549. resources with OAuth.
  550. """
  551. timestamp_threshold = 300 # In seconds, five minutes.
  552. version = OAUTH_VERSION
  553. signature_methods = None
  554. def __init__(self, signature_methods=None):
  555. self.signature_methods = signature_methods or {}
  556. def add_signature_method(self, signature_method):
  557. self.signature_methods[signature_method.name] = signature_method
  558. return self.signature_methods
  559. def verify_request(self, request, consumer, token):
  560. """Verifies an api call and checks all the parameters."""
  561. self._check_version(request)
  562. self._check_signature(request, consumer, token)
  563. parameters = request.get_nonoauth_parameters()
  564. return parameters
  565. def build_authenticate_header(self, realm=''):
  566. """Optional support for the authenticate header."""
  567. return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
  568. def _check_version(self, request):
  569. """Verify the correct version of the request for this server."""
  570. version = self._get_version(request)
  571. if version and version != self.version:
  572. raise Error('OAuth version %s not supported.' % str(version))
  573. def _get_version(self, request):
  574. """Return the version of the request for this server."""
  575. try:
  576. version = request.get_parameter('oauth_version')
  577. except:
  578. version = OAUTH_VERSION
  579. return version
  580. def _get_signature_method(self, request):
  581. """Figure out the signature with some defaults."""
  582. try:
  583. signature_method = request.get_parameter('oauth_signature_method')
  584. except:
  585. signature_method = SIGNATURE_METHOD
  586. try:
  587. # Get the signature method object.
  588. signature_method = self.signature_methods[signature_method]
  589. except:
  590. signature_method_names = ', '.join(self.signature_methods.keys())
  591. raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
  592. return signature_method
  593. def _get_verifier(self, request):
  594. return request.get_parameter('oauth_verifier')
  595. def _check_signature(self, request, consumer, token):
  596. timestamp, nonce = request._get_timestamp_nonce()
  597. self._check_timestamp(timestamp)
  598. signature_method = self._get_signature_method(request)
  599. try:
  600. signature = request.get_parameter('oauth_signature')
  601. except:
  602. raise MissingSignature('Missing oauth_signature.')
  603. # Validate the signature.
  604. valid = signature_method.check(request, consumer, token, signature)
  605. if not valid:
  606. key, base = signature_method.signing_base(request, consumer, token)
  607. raise Error('Invalid signature. Expected signature base '
  608. 'string: %s' % base)
  609. def _check_timestamp(self, timestamp):
  610. """Verify that timestamp is recentish."""
  611. timestamp = int(timestamp)
  612. now = int(time.time())
  613. lapsed = now - timestamp
  614. if lapsed > self.timestamp_threshold:
  615. raise Error('Expired timestamp: given %d and now %s has a '
  616. 'greater difference than threshold %d' % (timestamp, now,
  617. self.timestamp_threshold))
  618. class SignatureMethod(object):
  619. """A way of signing requests.
  620. The OAuth protocol lets consumers and service providers pick a way to sign
  621. requests. This interface shows the methods expected by the other `oauth`
  622. modules for signing requests. Subclass it and implement its methods to
  623. provide a new way to sign requests.
  624. """
  625. def signing_base(self, request, consumer, token):
  626. """Calculates the string that needs to be signed.
  627. This method returns a 2-tuple containing the starting key for the
  628. signing and the message to be signed. The latter may be used in error
  629. messages to help clients debug their software.
  630. """
  631. raise NotImplementedError
  632. def sign(self, request, consumer, token):
  633. """Returns the signature for the given request, based on the consumer
  634. and token also provided.
  635. You should use your implementation of `signing_base()` to build the
  636. message to sign. Otherwise it may be less useful for debugging.
  637. """
  638. raise NotImplementedError
  639. def check(self, request, consumer, token, signature):
  640. """Returns whether the given signature is the correct signature for
  641. the given consumer and token signing the given request."""
  642. built = self.sign(request, consumer, token)
  643. return built == signature
  644. class SignatureMethod_HMAC_SHA1(SignatureMethod):
  645. name = 'HMAC-SHA1'
  646. def signing_base(self, request, consumer, token):
  647. if not hasattr(request, 'normalized_url') or request.normalized_url is None:
  648. raise ValueError("Base URL for request is not set.")
  649. sig = (
  650. escape(request.method),
  651. escape(request.normalized_url),
  652. escape(request.get_normalized_parameters()),
  653. )
  654. key = '%s&' % escape(consumer.secret)
  655. if token:
  656. key += escape(token.secret)
  657. raw = '&'.join(sig)
  658. return key, raw
  659. def sign(self, request, consumer, token):
  660. """Builds the base signature string."""
  661. key, raw = self.signing_base(request, consumer, token)
  662. hashed = hmac.new(key, raw, sha)
  663. # Calculate the digest base 64.
  664. return binascii.b2a_base64(hashed.digest())[:-1]
  665. class SignatureMethod_PLAINTEXT(SignatureMethod):
  666. name = 'PLAINTEXT'
  667. def signing_base(self, request, consumer, token):
  668. """Concatenates the consumer key and secret with the token's
  669. secret."""
  670. sig = '%s&' % escape(consumer.secret)
  671. if token:
  672. sig = sig + escape(token.secret)
  673. return sig, sig
  674. def sign(self, request, consumer, token):
  675. key, raw = self.signing_base(request, consumer, token)
  676. return raw