Commits

Martin von Löwis committed 1de436d

Port to 3.x

Comments (0)

Files changed (1)

 # in the role of a relying party
 
 import urlparse, urllib, httplib, BeautifulSoup, time
-import cStringIO, base64, hmac, sha, datetime, re, random
-import itertools, cPickle
+import cStringIO, base64, hmac, hashlib, datetime, re, random
+import itertools, cPickle, sys
 
 try:
     from xml.etree import ElementTree
 # Don't use urllib, since it sometimes selects HTTP/1.1 (e.g. in PyPI)
 # and then fails to parse chunked responses.
 
+# 3.x portability
+
+if sys.version_info < (3,):
+    def b(s):
+        return s
+else:
+    def b(s):
+        return s.encode('ascii')
+
 def normalize_uri(uri):
     """Normalize an uri according to OpenID section 7.2. Return a pair
     type,value, where type can be either 'xri' or 'uri'."""
 def parse_response(s):
     '''Parse a key-value form (OpenID section 4.1.1) into a dictionary'''
     res = {}
-    for line in s.splitlines():
+    for line in s.decode('utf-8').splitlines():
         k,v = line.split(':', 1)
         res[k] = v
     return res
     if res.status in (301, 302, 303, 307):
         return discover(res.msg.get('location'))
 
-    content_type = res.msg.gettype()
+    if sys.version_info < (3,0):
+        content_type = res.msg.gettype()
+    else:
+        content_type = res.msg.get_content_type()
 
     # Yadis 6.2.5 option 2 and 3: header includes x-xrds-location
     xrds_loc = res.msg.get('x-xrds-location')
         dh_server_public = unbtwoc(base64.b64decode(data['dh_server_public']))
         # shared secret: sha1(2^(server_priv*priv) mod prime) xor enc_mac_key
         shared_secret = btwoc(pow(dh_server_public, priv, dh_prime))
-        shared_secret = sha.new(shared_secret).digest()
+        shared_secret = hashlib.sha1(shared_secret).digest()
         if len(shared_secret) != len(enc_mac_key):
             raise ValueError, "incorrect DH key size"
         # Fake mac_key result
     signed = response['openid.signed'][0].split(',')
     query = []
     for name in signed:
-        if isinstance(name, unicode):
-            name = name.encode('ascii')
         value = response['openid.'+name][0]
-        if isinstance(value, unicode):
+        value = '%s:%s\n' % (name, value)
+        if sys.version_info >= (3,):
             value = value.encode('utf-8')
-        query.append('%s:%s\n' % (name, value))
-    query = ''.join(query)
+        query.append(value)
+    query = b('').join(query)
 
-    mac_key = base64.decodestring(session['mac_key'])
-    transmitted_sig = base64.decodestring(response['openid.sig'][0])
-    computed_sig = hmac.new(mac_key, query, sha).digest()
+    mac_key = base64.decodestring(b(session['mac_key']))
+    transmitted_sig = base64.decodestring(b(response['openid.sig'][0]))
+    computed_sig = hmac.new(mac_key, query, hashlib.sha1).digest()
 
     if transmitted_sig != computed_sig:
         raise ValueError('Invalid signature')
                     payload += 'Your nickname is '+username+'\n'
                 else:
                     payload += 'No nickname is known\n'
+                if isinstance(payload, unicode):
+                    payload = payload.encode('utf-8')
                 return self.write(payload, "text/plain")
                 
         return self.not_found()
 
     def debug(self, value):
         payload = repr(value)
+        if isinstance(payload, unicode):
+            payload = payload.encode('utf-8')
         self.write(payload, "text/plain")
 
     def error(self, text):
+        if isinstance(text, unicode):
+            text = text.encode('utf-8')
         self.write(text, "text/plain")
 
     def root(self):
-        payload = "<html><head><title>OpenID login</title></head><body>\n"
+        payload = u"<html><head><title>OpenID login</title></head><body>\n"
         
         for name, icon, provider in providers:
-            payload += "<p><a href='%s?provider=%s'><img src='%s' alt='%s'></a></p>\n" % (
+            payload += u"<p><a href='%s?provider=%s'><img src='%s' alt='%s'></a></p>\n" % (
                 self.base_url, name, icon, name)
-        payload += "<form>Type your OpenID:<input name='claimed'/><input type='submit'/></form>\n"
-        payload += "</body></html>"
-        self.write(payload, "text/html")
+        payload += u"<form>Type your OpenID:<input name='claimed'/><input type='submit'/></form>\n"
+        payload += u"</body></html>"
+        self.write(payload.encode('utf-8'), "text/html")
 
     def rp_discovery(self):
         payload = '''<xrds:XRDS