florimondmanca / djangorestframework-api-key

🔐 API key permissions for Django REST Framework
https://florimondmanca.github.io/djangorestframework-api-key/
MIT License
678 stars 104 forks source link

get_usable_keys() is empty #220

Closed mathijsfr closed 2 years ago

mathijsfr commented 2 years ago

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:

https://github.com/florimondmanca/djangorestframework-api-key/blob/a9579e358ebfb5ede888f78d3f0af29ac1ee9d6f/src/rest_framework_api_key/models.py#L43

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):