from rest_framework_api_key.permissions import BaseHasAPIKey
from .models import APIKey


class HasAPIKey(BaseHasAPIKey):
    model = APIKey

    def has_permission(self, request, view):
        # First check if we have a valid API key
        has_api_key = super().has_permission(request, view)

        if has_api_key:
            # Get the API key from the request
            key = self.get_key(request)
            if key:
                try:
                    api_key = APIKey.objects.get_from_key(key)
                    # Set the request.user to the user associated with the API key
                    request.user = api_key.user
                    return True
                except APIKey.DoesNotExist:
                    pass

        return False
