models.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import binascii
  2. import os
  3. from typing import List
  4. from django.conf import settings
  5. from django.db import models
  6. from bitfield import BitField
  7. from glitchtip.base_models import CreatedModel
  8. def generate_token():
  9. return binascii.hexlify(os.urandom(32)).decode()
  10. class APIToken(CreatedModel):
  11. """
  12. Ideas borrowed from rest_framework.authtoken and sentry.apitoken
  13. """
  14. token = models.CharField(
  15. max_length=64, unique=True, editable=False, default=generate_token
  16. )
  17. user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
  18. label = models.CharField(max_length=255, blank=True)
  19. scopes = BitField(
  20. flags=(
  21. "project:read",
  22. "project:write",
  23. "project:admin",
  24. "project:releases",
  25. "team:read",
  26. "team:write",
  27. "team:admin",
  28. "event:read",
  29. "event:write",
  30. "event:admin",
  31. "org:read",
  32. "org:write",
  33. "org:admin",
  34. "member:read",
  35. "member:write",
  36. "member:admin",
  37. )
  38. )
  39. def __str__(self):
  40. return self.token
  41. def get_scopes(self):
  42. """
  43. Return array of set scope flags.
  44. Example: ["project:read"]
  45. """
  46. return [i[0] for i in self.scopes.items() if i[1] is True]
  47. def add_permission(self, permission: str):
  48. """ Add permission flag to scopes and save """
  49. setattr(self.scopes, permission, True)
  50. self.save(update_fields=["scopes"])
  51. def add_permissions(self, permissions: List[str]):
  52. """ Add permission flags to scopes and save """
  53. for permission in permissions:
  54. setattr(self.scopes, permission, True)
  55. self.save(update_fields=["scopes"])