models.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from django.db import models
  2. from rest_framework_api_key.models import AbstractAPIKey, BaseAPIKeyManager
  3. from django.contrib.auth.models import User, Permission
  4. from django.contrib import contenttypes
  5. from django.contrib.auth.backends import ModelBackend
  6. from .utils import parse_request_method_name
  7. class APIKey(AbstractAPIKey):
  8. permission = models.ManyToManyField(Permission, related_name="api_keys")
  9. class Meta(AbstractAPIKey.Meta):
  10. verbose_name = "API key"
  11. verbose_name_plural = "API keys"
  12. def get_all_permissions(self):
  13. return self.permission.all()
  14. def has_permission(self, model):
  15. '''
  16. Checks if the APIKey has any type of permission for a specific model
  17. '''
  18. permissions = self.get_all_permissions()
  19. for i in permissions:
  20. if model == i.content_type.model:
  21. return True
  22. return False
  23. def has_permission_method(self, model, request_method):
  24. '''
  25. Checks if the APIKey has request method permission on certain model.
  26. request_method can be POST, GET, PUT, DELETE
  27. '''
  28. permissions = self.get_all_permissions()
  29. for i in permissions:
  30. if model == i.content_type.model and parse_request_method_name(request_method) in i.codename:
  31. return True
  32. return False