Skip to content

Commit 07497e3

Browse files
committed
Token decode error exception handled
1 parent 61cb20c commit 07497e3

File tree

2 files changed

+27
-18
lines changed

2 files changed

+27
-18
lines changed

backend/main.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from pyinstrument import Profiler
1111
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
1212
from starlette.middleware.authentication import AuthenticationMiddleware
13-
1413
from backend.config import settings
1514
from backend.db import db_connection
1615
from backend.exceptions import BadRequest, Conflict, Forbidden, NotFound, Unauthorized
@@ -55,16 +54,21 @@ async def lifespan(app):
5554
# Custom exception handler for invalid token and logout.
5655
@_app.exception_handler(HTTPException)
5756
async def custom_http_exception_handler(request: Request, exc: HTTPException):
58-
if exc.status_code == 401 and "InvalidToken" in exc.detail.get("SubCode", ""):
59-
return JSONResponse(
60-
content={
61-
"Error": exc.detail["Error"],
62-
"SubCode": exc.detail["SubCode"],
63-
},
64-
status_code=exc.status_code,
65-
headers={"WWW-Authenticate": "Bearer"},
66-
)
67-
57+
try:
58+
if exc.status_code == 401 and "InvalidToken" in exc.detail.get(
59+
"SubCode", ""
60+
):
61+
return JSONResponse(
62+
content={
63+
"Error": exc.detail["Error"],
64+
"SubCode": exc.detail["SubCode"],
65+
},
66+
status_code=exc.status_code,
67+
headers={"WWW-Authenticate": "Bearer"},
68+
)
69+
except Exception as e:
70+
logging.debug(f"Exception while handling custom HTTPException: {e}")
71+
pass
6872
if isinstance(exc.detail, dict) and "error" in exc.detail:
6973
error_response = exc.detail
7074
else:

backend/services/users/authentication_service.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,18 +70,18 @@ def verify_token(token):
7070
class TokenAuthBackend(AuthenticationBackend):
7171
async def authenticate(self, conn):
7272
if "authorization" not in conn.headers:
73-
return
73+
return None
7474

7575
auth = conn.headers["authorization"]
7676
try:
7777
scheme, credentials = auth.split()
7878
if scheme.lower() != "token":
79-
return
79+
return None
8080
try:
8181
decoded_token = base64.b64decode(credentials).decode("ascii")
8282
except UnicodeDecodeError:
8383
logger.debug("Unable to decode token")
84-
return False
84+
return None
8585
except (ValueError, UnicodeDecodeError, binascii.Error):
8686
raise AuthenticationError("Invalid auth credentials")
8787

@@ -90,7 +90,7 @@ async def authenticate(self, conn):
9090
)
9191
if not valid_token:
9292
logger.debug("Token not valid.")
93-
return
93+
return None
9494
tm.authenticated_user_id = user_id
9595
return AuthCredentials(["authenticated"]), SimpleUser(user_id)
9696

@@ -251,7 +251,6 @@ async def login_required(
251251
raise AuthenticationError("Invalid auth credentials")
252252
valid_token, user_id = AuthenticationService.is_valid_token(decoded_token, 604800)
253253
if not valid_token:
254-
logger.debug("Token not valid")
255254
raise HTTPException(
256255
status_code=status.HTTP_401_UNAUTHORIZED,
257256
detail={"Error": "Token is expired or invalid", "SubCode": "InvalidToken"},
@@ -275,12 +274,18 @@ async def login_required_optional(
275274
decoded_token = base64.b64decode(credentials).decode("ascii")
276275
except UnicodeDecodeError:
277276
logger.debug("Unable to decode token")
278-
raise HTTPException(status_code=401, detail="Invalid token")
277+
raise HTTPException(
278+
status_code=status.HTTP_401_UNAUTHORIZED,
279+
detail={
280+
"Error": "Token is expired or invalid",
281+
"SubCode": "InvalidToken",
282+
},
283+
headers={"WWW-Authenticate": "Bearer"},
284+
)
279285
except (ValueError, UnicodeDecodeError, binascii.Error):
280286
raise AuthenticationError("Invalid auth credentials")
281287
valid_token, user_id = AuthenticationService.is_valid_token(decoded_token, 604800)
282288
if not valid_token:
283-
logger.debug("Token not valid")
284289
return None
285290
return AuthUserDTO(id=user_id)
286291

0 commit comments

Comments
 (0)