Skip to content

Commit

Permalink
Explore swappable API key model functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
florimondmanca committed Dec 5, 2021
1 parent dd806cf commit 5f20bf9
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 7 deletions.
4 changes: 1 addition & 3 deletions src/rest_framework_api_key/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.db import models
from django.http.request import HttpRequest

from .models import AbstractAPIKey, APIKey
from .models import AbstractAPIKey


class APIKeyModelAdmin(admin.ModelAdmin):
Expand Down Expand Up @@ -55,6 +55,4 @@ def save_model(
obj.save()


admin.site.register(APIKey, APIKeyModelAdmin)

APIKeyAdmin = APIKeyModelAdmin # Compatibility with <1.3
32 changes: 30 additions & 2 deletions src/rest_framework_api_key/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import typing

from django.core.exceptions import ValidationError
from django.apps import apps as django_apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.utils import timezone

Expand Down Expand Up @@ -142,5 +144,31 @@ def __str__(self) -> str:
return str(self.name)


def get_swappable_setting() -> str:
if not hasattr(settings, "API_KEY_MODEL"):
# Ensure a default value is set.
settings.API_KEY_MODEL = "rest_framework_api_key.APIKey"

return "API_KEY_MODEL"


class APIKey(AbstractAPIKey):
pass
class Meta(AbstractAPIKey.Meta):
swappable = get_swappable_setting()


def get_api_key_model() -> typing.Type[AbstractAPIKey]:
"""
Return the API key model that is active in this project.
"""
try:
return django_apps.get_model(settings.API_KEY_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured(
"API_KEY_MODEL must be of the form 'app_label.model_name'"
)
except LookupError:
raise ImproperlyConfigured(
"API_KEY_MODEL refers to model '%s' that has not been installed"
% settings.API_KEY_MODEL
)
4 changes: 2 additions & 2 deletions src/rest_framework_api_key/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.http import HttpRequest
from rest_framework import permissions

from .models import AbstractAPIKey, APIKey
from .models import AbstractAPIKey, get_api_key_model


class KeyParser:
Expand Down Expand Up @@ -59,4 +59,4 @@ def has_object_permission(


class HasAPIKey(BaseHasAPIKey):
model = APIKey
model = get_api_key_model()
5 changes: 5 additions & 0 deletions test_project/project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,8 @@
# Static files (CSS, JavaScript, Images)

STATIC_URL = "/static/"


# API keys

API_KEY_MODEL = "heroes.HeroAPIKey"

0 comments on commit 5f20bf9

Please sign in to comment.