Skip to content

Commit

Permalink
fix: Invalid token exception in TokenAuthBackend
Browse files Browse the repository at this point in the history
  • Loading branch information
prabinoid committed Nov 19, 2024
1 parent e4c3b6c commit a5b30c3
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 34 deletions.
13 changes: 7 additions & 6 deletions backend/api/annotations/resources.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from databases import Database
from fastapi import APIRouter, Depends, Request
from loguru import logger
from starlette.authentication import requires

from backend.db import get_db
from backend.models.dtos.user_dto import AuthUserDTO
from backend.models.postgis.task import Task
from backend.models.postgis.task_annotation import TaskAnnotation
from backend.services.project_service import ProjectService
from backend.services.task_annotations_service import TaskAnnotationsService
from fastapi import APIRouter, Depends, Request
from starlette.authentication import requires
from loguru import logger
from backend.db import get_db
from databases import Database
from backend.services.users.authentication_service import login_required
from backend.models.dtos.user_dto import AuthUserDTO

router = APIRouter(
prefix="/projects",
Expand Down
34 changes: 17 additions & 17 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ async def lifespan(app):
# Set custom logger
# _app.logger = get_logger()

# Custom exception handler for 401 errors
@_app.exception_handler(HTTPException)
async def custom_http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 401 and "InvalidToken" in exc.detail.get("SubCode", ""):
return JSONResponse(
content={
"Error": exc.detail["Error"],
"SubCode": exc.detail["SubCode"],
},
status_code=exc.status_code,
headers={"WWW-Authenticate": "Bearer"},
)
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)

PROFILING = True # Set this from a settings model

if PROFILING:
Expand Down Expand Up @@ -71,23 +88,6 @@ async def pyinstrument_middleware(request, call_next):
AuthenticationMiddleware, backend=TokenAuthBackend(), on_error=None
)

# Custom exception handler for 401 errors
@_app.exception_handler(HTTPException)
async def custom_http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 401 and "InvalidToken" in exc.detail.get("SubCode", ""):
return JSONResponse(
content={
"Error": exc.detail["Error"],
"SubCode": exc.detail["SubCode"],
},
status_code=exc.status_code,
headers={"WWW-Authenticate": "Bearer"},
)
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)

add_api_end_points(_app)
return _app

Expand Down
22 changes: 11 additions & 11 deletions backend/services/users/authentication_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,17 @@ async def authenticate(self, conn):
decoded_token, 604800
)
if not valid_token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={
"Error": "Token is expired or invalid",
"SubCode": "InvalidToken",
},
headers={"WWW-Authenticate": "Bearer"},
)
tm.authenticated_user_id = (
user_id # Set the user ID on the decorator as a convenience
)
logger.debug("Token not valid...")
return
# raise HTTPException(
# status_code=401,
# detail={
# "Error": "Token is expired or invalid",
# "SubCode": "InvalidToken",
# },
# headers={"WWW-Authenticate": "Bearer"},
# )
tm.authenticated_user_id = user_id
return AuthCredentials(["authenticated"]), SimpleUser(user_id)


Expand Down

0 comments on commit a5b30c3

Please sign in to comment.