consumer.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #!/usr/bin/env python
  2. """
  3. Simple example for an OpenID consumer.
  4. Once you understand this example you'll know the basics of OpenID
  5. and using the Python OpenID library. You can then move on to more
  6. robust examples, and integrating OpenID into your application.
  7. """
  8. __copyright__ = 'Copyright 2005-2008, Janrain, Inc.'
  9. from Cookie import SimpleCookie
  10. import cgi
  11. import urlparse
  12. import cgitb
  13. import sys
  14. def quoteattr(s):
  15. qs = cgi.escape(s, 1)
  16. return '"%s"' % (qs,)
  17. from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
  18. try:
  19. import openid
  20. except ImportError:
  21. sys.stderr.write("""
  22. Failed to import the OpenID library. In order to use this example, you
  23. must either install the library (see INSTALL in the root of the
  24. distribution) or else add the library to python's import path (the
  25. PYTHONPATH environment variable).
  26. For more information, see the README in the root of the library
  27. distribution.""")
  28. sys.exit(1)
  29. from openid.store import memstore
  30. from openid.store import filestore
  31. from openid.consumer import consumer
  32. from openid.oidutil import appendArgs
  33. from openid.cryptutil import randomString
  34. from openid.fetchers import setDefaultFetcher, Urllib2Fetcher
  35. from openid.extensions import pape, sreg
  36. # Used with an OpenID provider affiliate program.
  37. OPENID_PROVIDER_NAME = 'MyOpenID'
  38. OPENID_PROVIDER_URL ='https://www.myopenid.com/affiliate_signup?affiliate_id=39'
  39. class OpenIDHTTPServer(HTTPServer):
  40. """http server that contains a reference to an OpenID consumer and
  41. knows its base URL.
  42. """
  43. def __init__(self, store, *args, **kwargs):
  44. HTTPServer.__init__(self, *args, **kwargs)
  45. self.sessions = {}
  46. self.store = store
  47. if self.server_port != 80:
  48. self.base_url = ('http://%s:%s/' %
  49. (self.server_name, self.server_port))
  50. else:
  51. self.base_url = 'http://%s/' % (self.server_name,)
  52. class OpenIDRequestHandler(BaseHTTPRequestHandler):
  53. """Request handler that knows how to verify an OpenID identity."""
  54. SESSION_COOKIE_NAME = 'pyoidconsexsid'
  55. session = None
  56. def getConsumer(self, stateless=False):
  57. if stateless:
  58. store = None
  59. else:
  60. store = self.server.store
  61. return consumer.Consumer(self.getSession(), store)
  62. def getSession(self):
  63. """Return the existing session or a new session"""
  64. if self.session is not None:
  65. return self.session
  66. # Get value of cookie header that was sent
  67. cookie_str = self.headers.get('Cookie')
  68. if cookie_str:
  69. cookie_obj = SimpleCookie(cookie_str)
  70. sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None)
  71. if sid_morsel is not None:
  72. sid = sid_morsel.value
  73. else:
  74. sid = None
  75. else:
  76. sid = None
  77. # If a session id was not set, create a new one
  78. if sid is None:
  79. sid = randomString(16, '0123456789abcdef')
  80. session = None
  81. else:
  82. session = self.server.sessions.get(sid)
  83. # If no session exists for this session ID, create one
  84. if session is None:
  85. session = self.server.sessions[sid] = {}
  86. session['id'] = sid
  87. self.session = session
  88. return session
  89. def setSessionCookie(self):
  90. sid = self.getSession()['id']
  91. session_cookie = '%s=%s;' % (self.SESSION_COOKIE_NAME, sid)
  92. self.send_header('Set-Cookie', session_cookie)
  93. def do_GET(self):
  94. """Dispatching logic. There are three paths defined:
  95. / - Display an empty form asking for an identity URL to
  96. verify
  97. /verify - Handle form submission, initiating OpenID verification
  98. /process - Handle a redirect from an OpenID server
  99. Any other path gets a 404 response. This function also parses
  100. the query parameters.
  101. If an exception occurs in this function, a traceback is
  102. written to the requesting browser.
  103. """
  104. try:
  105. self.parsed_uri = urlparse.urlparse(self.path)
  106. self.query = {}
  107. for k, v in cgi.parse_qsl(self.parsed_uri[4]):
  108. self.query[k] = v.decode('utf-8')
  109. path = self.parsed_uri[2]
  110. if path == '/':
  111. self.render()
  112. elif path == '/verify':
  113. self.doVerify()
  114. elif path == '/process':
  115. self.doProcess()
  116. elif path == '/affiliate':
  117. self.doAffiliate()
  118. else:
  119. self.notFound()
  120. except (KeyboardInterrupt, SystemExit):
  121. raise
  122. except:
  123. self.send_response(500)
  124. self.send_header('Content-type', 'text/html')
  125. self.setSessionCookie()
  126. self.end_headers()
  127. self.wfile.write(cgitb.html(sys.exc_info(), context=10))
  128. def doVerify(self):
  129. """Process the form submission, initating OpenID verification.
  130. """
  131. # First, make sure that the user entered something
  132. openid_url = self.query.get('openid_identifier')
  133. if not openid_url:
  134. self.render('Enter an OpenID Identifier to verify.',
  135. css_class='error', form_contents=openid_url)
  136. return
  137. immediate = 'immediate' in self.query
  138. use_sreg = 'use_sreg' in self.query
  139. use_pape = 'use_pape' in self.query
  140. use_stateless = 'use_stateless' in self.query
  141. oidconsumer = self.getConsumer(stateless = use_stateless)
  142. try:
  143. request = oidconsumer.begin(openid_url)
  144. except consumer.DiscoveryFailure, exc:
  145. fetch_error_string = 'Error in discovery: %s' % (
  146. cgi.escape(str(exc[0])))
  147. self.render(fetch_error_string,
  148. css_class='error',
  149. form_contents=openid_url)
  150. else:
  151. if request is None:
  152. msg = 'No OpenID services found for <code>%s</code>' % (
  153. cgi.escape(openid_url),)
  154. self.render(msg, css_class='error', form_contents=openid_url)
  155. else:
  156. # Then, ask the library to begin the authorization.
  157. # Here we find out the identity server that will verify the
  158. # user's identity, and get a token that allows us to
  159. # communicate securely with the identity server.
  160. if use_sreg:
  161. self.requestRegistrationData(request)
  162. if use_pape:
  163. self.requestPAPEDetails(request)
  164. trust_root = self.server.base_url
  165. return_to = self.buildURL('process')
  166. if request.shouldSendRedirect():
  167. redirect_url = request.redirectURL(
  168. trust_root, return_to, immediate=immediate)
  169. self.send_response(302)
  170. self.send_header('Location', redirect_url)
  171. self.writeUserHeader()
  172. self.end_headers()
  173. else:
  174. form_html = request.htmlMarkup(
  175. trust_root, return_to,
  176. form_tag_attrs={'id':'openid_message'},
  177. immediate=immediate)
  178. self.wfile.write(form_html)
  179. def requestRegistrationData(self, request):
  180. sreg_request = sreg.SRegRequest(
  181. required=['nickname'], optional=['fullname', 'email'])
  182. request.addExtension(sreg_request)
  183. def requestPAPEDetails(self, request):
  184. pape_request = pape.Request([pape.AUTH_PHISHING_RESISTANT])
  185. request.addExtension(pape_request)
  186. def doProcess(self):
  187. """Handle the redirect from the OpenID server.
  188. """
  189. oidconsumer = self.getConsumer()
  190. # Ask the library to check the response that the server sent
  191. # us. Status is a code indicating the response type. info is
  192. # either None or a string containing more information about
  193. # the return type.
  194. url = 'http://'+self.headers.get('Host')+self.path
  195. info = oidconsumer.complete(self.query, url)
  196. sreg_resp = None
  197. pape_resp = None
  198. css_class = 'error'
  199. display_identifier = info.getDisplayIdentifier()
  200. if info.status == consumer.FAILURE and display_identifier:
  201. # In the case of failure, if info is non-None, it is the
  202. # URL that we were verifying. We include it in the error
  203. # message to help the user figure out what happened.
  204. fmt = "Verification of %s failed: %s"
  205. message = fmt % (cgi.escape(display_identifier),
  206. info.message)
  207. elif info.status == consumer.SUCCESS:
  208. # Success means that the transaction completed without
  209. # error. If info is None, it means that the user cancelled
  210. # the verification.
  211. css_class = 'alert'
  212. # This is a successful verification attempt. If this
  213. # was a real application, we would do our login,
  214. # comment posting, etc. here.
  215. fmt = "You have successfully verified %s as your identity."
  216. message = fmt % (cgi.escape(display_identifier),)
  217. sreg_resp = sreg.SRegResponse.fromSuccessResponse(info)
  218. pape_resp = pape.Response.fromSuccessResponse(info)
  219. if info.endpoint.canonicalID:
  220. # You should authorize i-name users by their canonicalID,
  221. # rather than their more human-friendly identifiers. That
  222. # way their account with you is not compromised if their
  223. # i-name registration expires and is bought by someone else.
  224. message += (" This is an i-name, and its persistent ID is %s"
  225. % (cgi.escape(info.endpoint.canonicalID),))
  226. elif info.status == consumer.CANCEL:
  227. # cancelled
  228. message = 'Verification cancelled'
  229. elif info.status == consumer.SETUP_NEEDED:
  230. if info.setup_url:
  231. message = '<a href=%s>Setup needed</a>' % (
  232. quoteattr(info.setup_url),)
  233. else:
  234. # This means auth didn't succeed, but you're welcome to try
  235. # non-immediate mode.
  236. message = 'Setup needed'
  237. else:
  238. # Either we don't understand the code or there is no
  239. # openid_url included with the error. Give a generic
  240. # failure message. The library should supply debug
  241. # information in a log.
  242. message = 'Verification failed.'
  243. self.render(message, css_class, display_identifier,
  244. sreg_data=sreg_resp, pape_data=pape_resp)
  245. def doAffiliate(self):
  246. """Direct the user sign up with an affiliate OpenID provider."""
  247. sreg_req = sreg.SRegRequest(['nickname'], ['fullname', 'email'])
  248. href = sreg_req.toMessage().toURL(OPENID_PROVIDER_URL)
  249. message = """Get an OpenID at <a href=%s>%s</a>""" % (
  250. quoteattr(href), OPENID_PROVIDER_NAME)
  251. self.render(message)
  252. def renderSREG(self, sreg_data):
  253. if not sreg_data:
  254. self.wfile.write(
  255. '<div class="alert">No registration data was returned</div>')
  256. else:
  257. sreg_list = sreg_data.items()
  258. sreg_list.sort()
  259. self.wfile.write(
  260. '<h2>Registration Data</h2>'
  261. '<table class="sreg">'
  262. '<thead><tr><th>Field</th><th>Value</th></tr></thead>'
  263. '<tbody>')
  264. odd = ' class="odd"'
  265. for k, v in sreg_list:
  266. field_name = sreg.data_fields.get(k, k)
  267. value = cgi.escape(v.encode('UTF-8'))
  268. self.wfile.write(
  269. '<tr%s><td>%s</td><td>%s</td></tr>' % (odd, field_name, value))
  270. if odd:
  271. odd = ''
  272. else:
  273. odd = ' class="odd"'
  274. self.wfile.write('</tbody></table>')
  275. def renderPAPE(self, pape_data):
  276. if not pape_data:
  277. self.wfile.write(
  278. '<div class="alert">No PAPE data was returned</div>')
  279. else:
  280. self.wfile.write('<div class="alert">Effective Auth Policies<ul>')
  281. for policy_uri in pape_data.auth_policies:
  282. self.wfile.write('<li><tt>%s</tt></li>' % (cgi.escape(policy_uri),))
  283. if not pape_data.auth_policies:
  284. self.wfile.write('<li>No policies were applied.</li>')
  285. self.wfile.write('</ul></div>')
  286. def buildURL(self, action, **query):
  287. """Build a URL relative to the server base_url, with the given
  288. query parameters added."""
  289. base = urlparse.urljoin(self.server.base_url, action)
  290. return appendArgs(base, query)
  291. def notFound(self):
  292. """Render a page with a 404 return code and a message."""
  293. fmt = 'The path <q>%s</q> was not understood by this server.'
  294. msg = fmt % (self.path,)
  295. openid_url = self.query.get('openid_identifier')
  296. self.render(msg, 'error', openid_url, status=404)
  297. def render(self, message=None, css_class='alert', form_contents=None,
  298. status=200, title="Python OpenID Consumer Example",
  299. sreg_data=None, pape_data=None):
  300. """Render a page."""
  301. self.send_response(status)
  302. self.pageHeader(title)
  303. if message:
  304. self.wfile.write("<div class='%s'>" % (css_class,))
  305. self.wfile.write(message)
  306. self.wfile.write("</div>")
  307. if sreg_data is not None:
  308. self.renderSREG(sreg_data)
  309. if pape_data is not None:
  310. self.renderPAPE(pape_data)
  311. self.pageFooter(form_contents)
  312. def pageHeader(self, title):
  313. """Render the page header"""
  314. self.setSessionCookie()
  315. self.wfile.write('''\
  316. Content-type: text/html; charset=UTF-8
  317. <html>
  318. <head><title>%s</title></head>
  319. <style type="text/css">
  320. * {
  321. font-family: verdana,sans-serif;
  322. }
  323. body {
  324. width: 50em;
  325. margin: 1em;
  326. }
  327. div {
  328. padding: .5em;
  329. }
  330. tr.odd td {
  331. background-color: #dddddd;
  332. }
  333. table.sreg {
  334. border: 1px solid black;
  335. border-collapse: collapse;
  336. }
  337. table.sreg th {
  338. border-bottom: 1px solid black;
  339. }
  340. table.sreg td, table.sreg th {
  341. padding: 0.5em;
  342. text-align: left;
  343. }
  344. table {
  345. margin: 0;
  346. padding: 0;
  347. }
  348. .alert {
  349. border: 1px solid #e7dc2b;
  350. background: #fff888;
  351. }
  352. .error {
  353. border: 1px solid #ff0000;
  354. background: #ffaaaa;
  355. }
  356. #verify-form {
  357. border: 1px solid #777777;
  358. background: #dddddd;
  359. margin-top: 1em;
  360. padding-bottom: 0em;
  361. }
  362. </style>
  363. <body>
  364. <h1>%s</h1>
  365. <p>
  366. This example consumer uses the <a href=
  367. "http://github.com/openid/python-openid" >Python
  368. OpenID</a> library. It just verifies that the identifier that you enter
  369. is your identifier.
  370. </p>
  371. ''' % (title, title))
  372. def pageFooter(self, form_contents):
  373. """Render the page footer"""
  374. if not form_contents:
  375. form_contents = ''
  376. self.wfile.write('''\
  377. <div id="verify-form">
  378. <form method="get" accept-charset="UTF-8" action=%s>
  379. Identifier:
  380. <input type="text" name="openid_identifier" value=%s />
  381. <input type="submit" value="Verify" /><br />
  382. <input type="checkbox" name="immediate" id="immediate" /><label for="immediate">Use immediate mode</label>
  383. <input type="checkbox" name="use_sreg" id="use_sreg" /><label for="use_sreg">Request registration data</label>
  384. <input type="checkbox" name="use_pape" id="use_pape" /><label for="use_pape">Request phishing-resistent auth policy (PAPE)</label>
  385. <input type="checkbox" name="use_stateless" id="use_stateless" /><label for="use_stateless">Use stateless mode</label>
  386. </form>
  387. </div>
  388. </body>
  389. </html>
  390. ''' % (quoteattr(self.buildURL('verify')), quoteattr(form_contents)))
  391. def main(host, port, data_path, weak_ssl=False):
  392. # Instantiate OpenID consumer store and OpenID consumer. If you
  393. # were connecting to a database, you would create the database
  394. # connection and instantiate an appropriate store here.
  395. if data_path:
  396. store = filestore.FileOpenIDStore(data_path)
  397. else:
  398. store = memstore.MemoryStore()
  399. if weak_ssl:
  400. setDefaultFetcher(Urllib2Fetcher())
  401. addr = (host, port)
  402. server = OpenIDHTTPServer(store, addr, OpenIDRequestHandler)
  403. print 'Server running at:'
  404. print server.base_url
  405. server.serve_forever()
  406. if __name__ == '__main__':
  407. host = 'localhost'
  408. port = 8001
  409. weak_ssl = False
  410. try:
  411. import optparse
  412. except ImportError:
  413. pass # Use defaults (for Python 2.2)
  414. else:
  415. parser = optparse.OptionParser('Usage:\n %prog [options]')
  416. parser.add_option(
  417. '-d', '--data-path', dest='data_path',
  418. help='Data directory for storing OpenID consumer state. '
  419. 'Setting this option implies using a "FileStore."')
  420. parser.add_option(
  421. '-p', '--port', dest='port', type='int', default=port,
  422. help='Port on which to listen for HTTP requests. '
  423. 'Defaults to port %default.')
  424. parser.add_option(
  425. '-s', '--host', dest='host', default=host,
  426. help='Host on which to listen for HTTP requests. '
  427. 'Also used for generating URLs. Defaults to %default.')
  428. parser.add_option(
  429. '-w', '--weakssl', dest='weakssl', default=False,
  430. action='store_true', help='Skip ssl cert verification')
  431. options, args = parser.parse_args()
  432. if args:
  433. parser.error('Expected no arguments. Got %r' % args)
  434. host = options.host
  435. port = options.port
  436. data_path = options.data_path
  437. weak_ssl = options.weakssl
  438. main(host, port, data_path, weak_ssl)