Skip to content

Commit

Permalink
fix authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
gagantrivedi committed Jul 31, 2023
1 parent cd4bb46 commit 7372c71
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
7 changes: 2 additions & 5 deletions api/api_keys/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,11 @@
class MasterAPIKeyAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
key = key_parser.get(request)

if not key:
return None

with suppress(MasterAPIKey.DoesNotExist):
if key := MasterAPIKey.objects.get_from_key(
key
) and MasterAPIKey.objects.is_valid(key):
if MasterAPIKey.objects.is_valid(key):
key = MasterAPIKey.objects.get_from_key(key)
return APIKeyUser(key), None

raise exceptions.AuthenticationFailed("Valid Master API Key not found.")
18 changes: 16 additions & 2 deletions api/tests/unit/api_keys/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ def test_authenticate_returns_api_key_user_for_valid_key(master_api_key, rf):
)
# When
user, _ = MasterAPIKeyAuthentication().authenticate(request)

# Then
assert user.key == master_api_key[0]

Expand All @@ -25,7 +24,7 @@ def test_authenticate_returns_none_if_no_key_provider(rf):
assert MasterAPIKeyAuthentication().authenticate(request) is None


def test_authenticate_raises_error_for_invalid_key(rf, master_api_key):
def test_authenticate_raises_error_for_expired_key(rf, master_api_key):
# Given
request = rf.get(
"/some-endpoint", HTTP_AUTHORIZATION="Api-Key " + master_api_key[1]
Expand All @@ -38,3 +37,18 @@ def test_authenticate_raises_error_for_invalid_key(rf, master_api_key):
MasterAPIKeyAuthentication().authenticate(request)

# Then - exception was raised


def test_authenticate_raises_error_for_revoked_key(rf, master_api_key):
# Given
request = rf.get(
"/some-endpoint", HTTP_AUTHORIZATION="Api-Key " + master_api_key[1]
)
master_api_key[0].revoked = True
master_api_key[0].save()

# When
with pytest.raises(AuthenticationFailed):
MasterAPIKeyAuthentication().authenticate(request)

# Then - exception was raised

0 comments on commit 7372c71

Please sign in to comment.