florimondmanca/djangorestframework-api-key

get_usable_keys() is empty

Closed this issue · 0 comments

Describe the bug
When trying to validate my api key, get_usable_keys() returns empty. This results in not being able to validate my api key.

To Reproduce

  1. Having existing api keys in my database according to the following model:
class UserAPIKey(AbstractAPIKey):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="api_keys",
    )

    subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE)
  1. Send request with to api with permission_classes = (HasAPIKey, )
class ProductSales(generics.RetrieveAPIView):
    permission_classes = (HasAPIKey, )

    def get(self, request, *args, **kwargs):
       result = 'test'
       return Response(result)
  1. Adding print in get_from_key function prints empty query set:

def get_from_key(self, key: str) -> "AbstractAPIKey":

def get_from_key(self, key: str) -> "AbstractAPIKey":
       prefix, _, _ = key.partition(".")
       queryset = self.get_usable_keys()
       print('test', queryset)

       try:
           api_key = queryset.get(prefix=prefix)
       except self.model.DoesNotExist:
           raise  # For the sake of being explicit.

       if not api_key.is_valid(key):
           raise self.model.DoesNotExist("Key is not valid.")
       else:
           return api_key

Expected behavior
Expected to have usable keys to validate my api key

Looks like the usable api keys are requested from rest_framework_api_key_apikey table, instead of the UserApiKey table. How do I solve this?

Desktop (please complete the following information):

  • OS: Windows 10 Pro
  • Python Version: 3.9.2
  • Django Version: 3.2
  • DRF Version: 3.12.4