Skip to content

Commit 5de44fe

Browse files
authored
Merge pull request #775 from cisagov/AL-allow-authorization
Allow API Keys to be passed through the Authorization header
2 parents f19e484 + 2bc6d7e commit 5de44fe

File tree

1 file changed

+28
-23
lines changed
  • backend/src/xfd_django/xfd_api

1 file changed

+28
-23
lines changed

backend/src/xfd_django/xfd_api/auth.py

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import hashlib
66
from hashlib import sha256
77
import os
8+
import re
89
from typing import List, Optional
910
from urllib.parse import urlencode
1011
import uuid
@@ -272,34 +273,38 @@ def get_current_active_user(
272273
if api_key:
273274
user = get_user_by_api_key(api_key)
274275
elif token:
275-
try:
276-
# Decode token in Authorization header to get user
277-
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
278-
user_id = payload.get("id")
279-
280-
if user_id is None:
281-
print("No user ID found in token")
276+
# Check if token is an API key
277+
if re.match(r"^[A-Fa-f0-9]{32}$", token):
278+
user = get_user_by_api_key(token)
279+
else:
280+
try:
281+
# Decode token in Authorization header to get user
282+
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
283+
user_id = payload.get("id")
284+
285+
if user_id is None:
286+
print("No user ID found in token")
287+
raise HTTPException(
288+
status_code=status.HTTP_401_UNAUTHORIZED,
289+
detail="Invalid token",
290+
headers={"WWW-Authenticate": "Bearer"},
291+
)
292+
# Fetch the user by ID from the database
293+
user = User.objects.get(id=user_id)
294+
except jwt.ExpiredSignatureError:
295+
print("Token has expired")
296+
raise HTTPException(
297+
status_code=status.HTTP_401_UNAUTHORIZED,
298+
detail="Token has expired",
299+
headers={"WWW-Authenticate": "Bearer"},
300+
)
301+
except jwt.InvalidTokenError:
302+
print("Invalid token")
282303
raise HTTPException(
283304
status_code=status.HTTP_401_UNAUTHORIZED,
284305
detail="Invalid token",
285306
headers={"WWW-Authenticate": "Bearer"},
286307
)
287-
# Fetch the user by ID from the database
288-
user = User.objects.get(id=user_id)
289-
except jwt.ExpiredSignatureError:
290-
print("Token has expired")
291-
raise HTTPException(
292-
status_code=status.HTTP_401_UNAUTHORIZED,
293-
detail="Token has expired",
294-
headers={"WWW-Authenticate": "Bearer"},
295-
)
296-
except jwt.InvalidTokenError:
297-
print("Invalid token")
298-
raise HTTPException(
299-
status_code=status.HTTP_401_UNAUTHORIZED,
300-
detail="Invalid token",
301-
headers={"WWW-Authenticate": "Bearer"},
302-
)
303308
else:
304309
raise HTTPException(
305310
status_code=status.HTTP_401_UNAUTHORIZED,

0 commit comments

Comments
 (0)