Skip to content

Commit

Permalink
Build API key: don't fetch and validate key twice (#10488)
Browse files Browse the repository at this point in the history
Instead of relying on the parent method,
we just now override the whole method to have
access to the key itself.
  • Loading branch information
stsewd authored Jun 28, 2023
1 parent 64196ad commit 8a7586b
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions readthedocs/api/v2/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ class HasBuildAPIKey(BaseHasAPIKey):
"""
Custom permission to inject the build API key into the request.
This avoids having to parse the key again on each view.
We completely override the ``has_permission`` method
to avoid having to parse and validate the key again on each view.
The key is injected in the ``request.build_api_key`` attribute
only if it's valid, otherwise it's set to ``None``.
"""
Expand All @@ -94,10 +95,18 @@ class HasBuildAPIKey(BaseHasAPIKey):
key_parser = TokenKeyParser()

def has_permission(self, request, view):
build_api_key = None
has_permission = super().has_permission(request, view)
if has_permission:
key = self.get_key(request)
request.build_api_key = None
key = self.get_key(request)
if not key:
return False

try:
build_api_key = self.model.objects.get_from_key(key)
except self.model.DoesNotExist:
return False

if build_api_key.has_expired:
return False

request.build_api_key = build_api_key
return has_permission
return True

0 comments on commit 8a7586b

Please sign in to comment.