models.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. class APIKey(AbstractAPIKey):
  7. permission = models.ManyToManyField(Permission, related_name="api_keys")
  8. class Meta(AbstractAPIKey.Meta):
  9. verbose_name = "API key"
  10. verbose_name_plural = "API keys"
  11. def get_all_permissions(self):
  12. return self.permission.all()
  13. def has_permission(self, model):
  14. '''
  15. Checks if the APIKey has any type of permission for a specific model
  16. '''
  17. permissions = self.get_all_permissions()
  18. for i in permissions:
  19. if model == i.content_type.model:
  20. return True
  21. return False
  22. def has_permission_method(self, model, request_method):
  23. '''
  24. Checks if the APIKey has request method permission on certain model
  25. request_method can be POST, GET, PUT, DELETE
  26. '''
  27. permissions = self.get_all_permissions()
  28. for i in permissions:
  29. if model == i.content_type.model and request_method in i.codename:
  30. return True
  31. return False