Update app.py
Browse files
app.py
CHANGED
@@ -405,28 +405,33 @@ def register_user(user_data: UserCreate, db: Session):
|
|
405 |
|
406 |
@app.get("/protected", response_class=HTMLResponse)
|
407 |
async def get_protected(
|
408 |
-
request: Request,
|
409 |
db: Session = Depends(get_db),
|
410 |
-
|
411 |
):
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
# Get the user from the database
|
424 |
-
db_user = get_user_by_email(db, user_email)
|
425 |
-
if db_user is None or not db_user.is_verified:
|
426 |
-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or not verified in the database")
|
427 |
|
428 |
-
#
|
429 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
430 |
|
431 |
def verify_email(verification_token: str, db: Session = Depends(get_db)):
|
432 |
# Verify the email using the token
|
|
|
405 |
|
406 |
@app.get("/protected", response_class=HTMLResponse)
|
407 |
async def get_protected(
|
408 |
+
request: Request,
|
409 |
db: Session = Depends(get_db),
|
410 |
+
authorization: Optional[str] = Header(None) # token from Authorization header
|
411 |
):
|
412 |
+
# Try to get the token from the Authorization header
|
413 |
+
if authorization:
|
414 |
+
scheme, _, token = authorization.partition(' ')
|
415 |
+
if scheme.lower() != 'bearer':
|
416 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication scheme")
|
417 |
+
else:
|
418 |
+
# Fall back to the cookie
|
419 |
+
token = request.cookies.get("access_token")
|
420 |
+
|
421 |
+
if not token:
|
422 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
|
|
|
|
|
|
|
|
423 |
|
424 |
+
# Verify the token and get user
|
425 |
+
try:
|
426 |
+
user_email = verify_token(token) # Implement your token verification logic
|
427 |
+
db_user = get_user_by_email(db, user_email)
|
428 |
+
if db_user is None or not db_user.is_verified:
|
429 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or not verified in the database")
|
430 |
+
|
431 |
+
# Render a template response
|
432 |
+
return templates.TemplateResponse("protected.html", {"request": request, "user": db_user.username})
|
433 |
+
except Exception as e: # Replace with specific exceptions as per your verification logic
|
434 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
|
435 |
|
436 |
def verify_email(verification_token: str, db: Session = Depends(get_db)):
|
437 |
# Verify the email using the token
|