Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build API key: don't fetch and validate key twice #10488

Merged
merged 1 commit into from
Jun 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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