server.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. """
  2. The MIT License
  3. Copyright (c) 2007 Leah Culver
  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. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  21. import urllib
  22. import oauth.oauth as oauth
  23. # fake urls for the test server
  24. REQUEST_TOKEN_URL = 'https://photos.example.net/request_token'
  25. ACCESS_TOKEN_URL = 'https://photos.example.net/access_token'
  26. AUTHORIZATION_URL = 'https://photos.example.net/authorize'
  27. CALLBACK_URL = 'http://printer.example.com/request_token_ready'
  28. RESOURCE_URL = 'http://photos.example.net/photos'
  29. REALM = 'http://photos.example.net/'
  30. VERIFIER = 'verifier'
  31. # example store for one of each thing
  32. class MockOAuthDataStore(oauth.OAuthDataStore):
  33. def __init__(self):
  34. self.consumer = oauth.OAuthConsumer('key', 'secret')
  35. self.request_token = oauth.OAuthToken('requestkey', 'requestsecret')
  36. self.access_token = oauth.OAuthToken('accesskey', 'accesssecret')
  37. self.nonce = 'nonce'
  38. self.verifier = VERIFIER
  39. def lookup_consumer(self, key):
  40. if key == self.consumer.key:
  41. return self.consumer
  42. return None
  43. def lookup_token(self, token_type, token):
  44. token_attrib = getattr(self, '%s_token' % token_type)
  45. if token == token_attrib.key:
  46. ## HACK
  47. token_attrib.set_callback(CALLBACK_URL)
  48. return token_attrib
  49. return None
  50. def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
  51. if oauth_token and oauth_consumer.key == self.consumer.key and (oauth_token.key == self.request_token.key or oauth_token.key == self.access_token.key) and nonce == self.nonce:
  52. return self.nonce
  53. return None
  54. def fetch_request_token(self, oauth_consumer, oauth_callback):
  55. if oauth_consumer.key == self.consumer.key:
  56. if oauth_callback:
  57. # want to check here if callback is sensible
  58. # for mock store, we assume it is
  59. self.request_token.set_callback(oauth_callback)
  60. return self.request_token
  61. return None
  62. def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
  63. if oauth_consumer.key == self.consumer.key and oauth_token.key == self.request_token.key and oauth_verifier == self.verifier:
  64. # want to check here if token is authorized
  65. # for mock store, we assume it is
  66. return self.access_token
  67. return None
  68. def authorize_request_token(self, oauth_token, user):
  69. if oauth_token.key == self.request_token.key:
  70. # authorize the request token in the store
  71. # for mock store, do nothing
  72. return self.request_token
  73. return None
  74. class RequestHandler(BaseHTTPRequestHandler):
  75. def __init__(self, *args, **kwargs):
  76. self.oauth_server = oauth.OAuthServer(MockOAuthDataStore())
  77. self.oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
  78. self.oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
  79. BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
  80. # example way to send an oauth error
  81. def send_oauth_error(self, err=None):
  82. # send a 401 error
  83. self.send_error(401, str(err.message))
  84. # return the authenticate header
  85. header = oauth.build_authenticate_header(realm=REALM)
  86. for k, v in header.iteritems():
  87. self.send_header(k, v)
  88. def do_GET(self):
  89. # debug info
  90. #print self.command, self.path, self.headers
  91. # get the post data (if any)
  92. postdata = None
  93. if self.command == 'POST':
  94. try:
  95. length = int(self.headers.getheader('content-length'))
  96. postdata = self.rfile.read(length)
  97. except:
  98. pass
  99. # construct the oauth request from the request parameters
  100. oauth_request = oauth.OAuthRequest.from_request(self.command, self.path, headers=self.headers, query_string=postdata)
  101. # request token
  102. if self.path.startswith(REQUEST_TOKEN_URL):
  103. try:
  104. # create a request token
  105. token = self.oauth_server.fetch_request_token(oauth_request)
  106. # send okay response
  107. self.send_response(200, 'OK')
  108. self.end_headers()
  109. # return the token
  110. self.wfile.write(token.to_string())
  111. except oauth.OAuthError, err:
  112. self.send_oauth_error(err)
  113. return
  114. # user authorization
  115. if self.path.startswith(AUTHORIZATION_URL):
  116. try:
  117. # get the request token
  118. token = self.oauth_server.fetch_request_token(oauth_request)
  119. # authorize the token (kind of does nothing for now)
  120. token = self.oauth_server.authorize_token(token, None)
  121. token.set_verifier(VERIFIER)
  122. # send okay response
  123. self.send_response(200, 'OK')
  124. self.end_headers()
  125. # return the callback url (to show server has it)
  126. self.wfile.write(token.get_callback_url())
  127. except oauth.OAuthError, err:
  128. self.send_oauth_error(err)
  129. return
  130. # access token
  131. if self.path.startswith(ACCESS_TOKEN_URL):
  132. try:
  133. # create an access token
  134. token = self.oauth_server.fetch_access_token(oauth_request)
  135. # send okay response
  136. self.send_response(200, 'OK')
  137. self.end_headers()
  138. # return the token
  139. self.wfile.write(token.to_string())
  140. except oauth.OAuthError, err:
  141. self.send_oauth_error(err)
  142. return
  143. # protected resources
  144. if self.path.startswith(RESOURCE_URL):
  145. try:
  146. # verify the request has been oauth authorized
  147. consumer, token, params = self.oauth_server.verify_request(oauth_request)
  148. # send okay response
  149. self.send_response(200, 'OK')
  150. self.end_headers()
  151. # return the extra parameters - just for something to return
  152. self.wfile.write(str(params))
  153. except oauth.OAuthError, err:
  154. self.send_oauth_error(err)
  155. return
  156. def do_POST(self):
  157. return self.do_GET()
  158. def main():
  159. try:
  160. server = HTTPServer(('', 8080), RequestHandler)
  161. print 'Test server running...'
  162. server.serve_forever()
  163. except KeyboardInterrupt:
  164. server.socket.close()
  165. if __name__ == '__main__':
  166. main()