123456789101112131415161718192021222324252627282930313233343536373839 |
- from django.db import models
- from rest_framework_api_key.models import AbstractAPIKey, BaseAPIKeyManager
- from django.contrib.auth.models import User, Permission
- from django.contrib import contenttypes
- from django.contrib.auth.backends import ModelBackend
- from .utils import parse_request_method_name
- class APIKey(AbstractAPIKey):
- permission = models.ManyToManyField(Permission, related_name="api_keys")
- class Meta(AbstractAPIKey.Meta):
- verbose_name = "API key"
- verbose_name_plural = "API keys"
- def get_all_permissions(self):
- return self.permission.all()
- def has_permission(self, model):
- '''
- Checks if the APIKey has any type of permission for a specific model
- '''
- permissions = self.get_all_permissions()
- for i in permissions:
- if model == i.content_type.model:
- return True
- return False
- def has_permission_method(self, model, request_method):
- '''
- Checks if the APIKey has request method permission on certain model.
- request_method can be POST, GET, PUT, DELETE
- '''
- permissions = self.get_all_permissions()
- for i in permissions:
- if model == i.content_type.model and parse_request_method_name(request_method) in i.codename:
- return True
- return False
|