Update main.py
Browse files
main.py
CHANGED
@@ -181,19 +181,31 @@ async def landing(request: Request):
|
|
181 |
|
182 |
# Your other routes and app configuration go here
|
183 |
|
|
|
|
|
|
|
184 |
@app.get("/login", response_class=HTMLResponse)
|
185 |
-
async def login(request: Request,
|
186 |
-
#
|
187 |
-
|
|
|
|
|
188 |
try:
|
189 |
-
#
|
190 |
-
user_email = verify_token(
|
191 |
if user_email:
|
192 |
# If token is valid, redirect to /protected
|
193 |
return RedirectResponse(url="/protected")
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
except Exception as e:
|
195 |
-
#
|
196 |
-
|
|
|
197 |
|
198 |
# If not authenticated, show the login page
|
199 |
return templates.TemplateResponse("login.html", {"request": request})
|
|
|
181 |
|
182 |
# Your other routes and app configuration go here
|
183 |
|
184 |
+
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST
|
185 |
+
from jwt import ExpiredSignatureError, InvalidTokenError # Ensure you've imported these
|
186 |
+
|
187 |
@app.get("/login", response_class=HTMLResponse)
|
188 |
+
async def login(request: Request, db: Session = Depends(get_db)):
|
189 |
+
# Try to retrieve the access token from the cookie
|
190 |
+
access_token = request.cookies.get("access_token")
|
191 |
+
|
192 |
+
if access_token:
|
193 |
try:
|
194 |
+
# Remove the 'Bearer ' prefix and verify the token
|
195 |
+
user_email = verify_token(access_token.split("Bearer ")[1])
|
196 |
if user_email:
|
197 |
# If token is valid, redirect to /protected
|
198 |
return RedirectResponse(url="/protected")
|
199 |
+
except ExpiredSignatureError:
|
200 |
+
# Token has expired. You could redirect to the login page or inform the user
|
201 |
+
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Token expired")
|
202 |
+
except InvalidTokenError:
|
203 |
+
# Token is invalid, inform the user or redirect
|
204 |
+
raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Invalid token")
|
205 |
except Exception as e:
|
206 |
+
# General exception, log this exception for debugging
|
207 |
+
# Respond with a generic error message
|
208 |
+
raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="An error occurred")
|
209 |
|
210 |
# If not authenticated, show the login page
|
211 |
return templates.TemplateResponse("login.html", {"request": request})
|