diff --git a/djangorestframework/tests/authentication.py b/djangorestframework/tests/authentication.py index 2806da36a..fb9996be4 100644 --- a/djangorestframework/tests/authentication.py +++ b/djangorestframework/tests/authentication.py @@ -146,3 +146,8 @@ class TokenAuthTests(TestCase): """Ensure POSTing json over token auth without correct credentials fails""" response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json') self.assertEqual(response.status_code, 403) + + def test_token_has_auto_assigned_key_if_none_provided(self): + """Ensure creating a token with no key will auto-assign a key""" + token = Token.objects.create(user=self.user) + self.assertEqual(len(token.key), 32) diff --git a/djangorestframework/tokenauth/models.py b/djangorestframework/tokenauth/models.py index 3b9a55bcf..b5a9f7b92 100644 --- a/djangorestframework/tokenauth/models.py +++ b/djangorestframework/tokenauth/models.py @@ -1,16 +1,22 @@ +import uuid from django.db import models class BaseToken(models.Model): """ The base abstract authorization token model class. """ - key = models.CharField(max_length=32, primary_key=True) + key = models.CharField(max_length=32, primary_key=True, blank=True) user = models.ForeignKey('auth.User') revoked = models.BooleanField(default=False) class Meta: abstract=True + def save(self, *args, **kwargs): + if not self.key: + self.key = uuid.uuid4().hex + return super(BaseToken, self).save(*args, **kwargs) + class Token(BaseToken): """ diff --git a/djangorestframework/tokenauth/views.py b/djangorestframework/tokenauth/views.py new file mode 100644 index 000000000..e69de29bb