Skip to content

Commit bf63caf

Browse files
New authentication error handler in main.py
1 parent 3cc67dd commit bf63caf

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

main.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from fastapi.exceptions import RequestValidationError, HTTPException, StarletteHTTPException
99
from sqlmodel import Session
1010
from routers import authentication, organization, role, user
11-
from utils.auth import get_authenticated_user, get_optional_user, NeedsNewTokens, get_user_from_reset_token, PasswordValidationError
11+
from utils.auth import get_authenticated_user, get_optional_user, NeedsNewTokens, get_user_from_reset_token, PasswordValidationError, AuthenticationError
1212
from utils.models import User
1313
from utils.db import get_session, set_up_db
1414

@@ -37,6 +37,15 @@ async def lifespan(app: FastAPI):
3737
# -- Exception Handling Middlewares --
3838

3939

40+
# Handle AuthenticationError by redirecting to login page
41+
@app.exception_handler(AuthenticationError)
42+
async def authentication_error_handler(request: Request, exc: AuthenticationError):
43+
return RedirectResponse(
44+
url="/login",
45+
status_code=status.HTTP_303_SEE_OTHER
46+
)
47+
48+
4049
# Handle NeedsNewTokens by setting new tokens and redirecting to same page
4150
@app.exception_handler(NeedsNewTokens)
4251
async def needs_new_tokens_handler(request: Request, exc: NeedsNewTokens):
@@ -104,10 +113,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
104113
# Handle StarletteHTTPException (including 404, 405, etc.) by rendering the error page
105114
@app.exception_handler(StarletteHTTPException)
106115
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
107-
# Don't handle redirects
108-
if exc.status_code in [301, 302, 303, 307, 308]:
109-
raise exc
110-
111116
return templates.TemplateResponse(
112117
request,
113118
"errors/error.html",

0 commit comments

Comments
 (0)