Private
Public Access
1
0

Enhance API key authentication to support 'ApiKey ' prefix for compatibility with CrewNerd standard; added corresponding test case.

This commit is contained in:
Sander Roosendaal
2026-04-17 10:23:54 +02:00
parent be3726fddb
commit 48a2c7cf4c
2 changed files with 43 additions and 3 deletions
+11 -3
View File
@@ -4,11 +4,19 @@ from rowers.models import APIKey
class APIKeyAuthentication(BaseAuthentication): class APIKeyAuthentication(BaseAuthentication):
def authenticate(self, request): def authenticate(self, request):
api_key = request.META.get('HTTP_AUTHORIZATION') auth_header = request.META.get('HTTP_AUTHORIZATION')
if not api_key: if not auth_header:
return None return None
# Handle "ApiKey <key>" format (CrewNerd standard)
if auth_header.startswith('ApiKey '):
api_key_value = auth_header[7:] # Strip "ApiKey " prefix
else:
# Support raw key for backward compatibility
api_key_value = auth_header
try: try:
api_key = APIKey.objects.get(key=api_key, is_active=True) api_key = APIKey.objects.get(key=api_key_value, is_active=True)
except APIKey.DoesNotExist: except APIKey.DoesNotExist:
raise AuthenticationFailed('Invalid API key') raise AuthenticationFailed('Invalid API key')
+32
View File
@@ -718,6 +718,38 @@ class OwnApi(TestCase):
self.assertEqual(response.status_code, 201) self.assertEqual(response.status_code, 201)
def test_strokedataform_rowingdata_apikey_with_prefix(self):
"""Test API key authentication with 'ApiKey ' prefix (CrewNerd format)"""
url = reverse('strokedata_rowingdata_apikey')
filename = 'rowers/tests/testdata/testdata.csv'
f = open(filename, 'rb')
# Use API Key header with "ApiKey " prefix (CrewNerd standard)
headers = {
"HTTP_AUTHORIZATION": f"ApiKey {self.apikey.key}",
}
form_data = {
"workouttype": "rower",
"boattype": "1x",
"notes": "A test file upload with ApiKey prefix",
}
# Send POST request
response = self.client.post(
url,
{"file": f, **form_data},
format="multipart",
**headers,
)
f.close()
# Assertions
self.assertEqual(response.status_code, 201)
def test_strokedataform_empty(self): def test_strokedataform_empty(self):
login = self.c.login(username=self.u.username, password=self.password) login = self.c.login(username=self.u.username, password=self.password)