Commits

Gregory Petukhov committed b49d0d4

Fix serious error in algo of unique key generation

Comments (0)

Files changed (3)

     call_command('syncdb', interactive=False)
     call_command('flush', interactive=False)
 
+    print 'Creating users'
     for x in xrange(100):
         username = 'test%d' % x
         User.objects.create_user(username, '%s@gmail.com' % username, username)
 
     users = User.objects.all()
 
+    print 'Creating auth keys'
     for user in users:
-        AuthKey.objects.wrap_url('/', uid=user.pk)
+        obj = AuthKey.objects.wrap_url('/', uid=user.pk)
 
     print 'Key count: %d' % AuthKey.objects.count()
 
 
 setup(
     name = 'django-urlauth',
-    version = '0.1.7',
+    version = '0.1.8',
     description = 'Django application for user authentication with key in hypertext link',
     url = 'http://bitbucket.org/lorien/django-urlauth/',
     author = 'Grigoriy Petukhov',

urlauth/models.py

-try:
-    from hashlib import sha1
-except ImportError:
-    from sha import new as sha1
+import os
+from binascii import hexlify
 import time
 from datetime import datetime, timedelta
 
 from django.conf import settings
 from django.utils import simplejson
 from django.contrib.auth.models import User
+from django.db.utils import IntegrityError
 
+class URLAuthError(Exception):
+    pass
 
 class AuthKeyManager(models.Manager):
 
 
         if 'onetime' in kwargs:
             key.onetime = kwargs.pop('onetime')
+        key.data = simplejson.dumps(kwargs)
 
-        source = '%s%d%d' % (settings.SECRET_KEY, time.time(), id({}))
-        key.id = sha1(source).hexdigest()
-        key.data = simplejson.dumps(kwargs)
-        key.save()
+        # Try 10 times to create AuthKey instance with unique PK
+        for x in xrange(10):
+            key.pk = hexlify(os.urandom(20))
+            try:
+                key.save(force_insert=True)
+            except IntegrityError:
+                key.pk = None
+            else:
+                break
+
+        if not key.pk:
+            raise URLAuthError('Could not create unique key')
+
         return key.id
 
     def wrap_url(self, url, **kwargs):