models.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import binascii
  2. import os
  3. from django.conf import settings
  4. from django.db import models
  5. from django.utils.translation import gettext_lazy as _
  6. class Token(models.Model):
  7. """
  8. The default authorization token model.
  9. """
  10. key = models.CharField(_("Key"), max_length=40, primary_key=True)
  11. user = models.OneToOneField(
  12. settings.AUTH_USER_MODEL, related_name='auth_token',
  13. on_delete=models.CASCADE, verbose_name=_("User")
  14. )
  15. created = models.DateTimeField(_("Created"), auto_now_add=True)
  16. class Meta:
  17. # Work around for a bug in Django:
  18. # https://code.djangoproject.com/ticket/19422
  19. #
  20. # Also see corresponding ticket:
  21. # https://github.com/encode/django-rest-framework/issues/705
  22. abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
  23. verbose_name = _("Token")
  24. verbose_name_plural = _("Tokens")
  25. def save(self, *args, **kwargs):
  26. if not self.key:
  27. self.key = self.generate_key()
  28. return super().save(*args, **kwargs)
  29. @classmethod
  30. def generate_key(cls):
  31. return binascii.hexlify(os.urandom(20)).decode()
  32. def __str__(self):
  33. return self.key
  34. class TokenProxy(Token):
  35. """
  36. Proxy mapping pk to user pk for use in admin.
  37. """
  38. @property
  39. def pk(self):
  40. return self.user_id
  41. class Meta:
  42. proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS
  43. abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
  44. verbose_name = "token"