Update main.py
Browse files
main.py
CHANGED
@@ -143,14 +143,22 @@ async def verify_email(verification_token: str, db: Session = Depends(get_db)):
|
|
143 |
@app.get("/protected", response_class=HTMLResponse)
|
144 |
async def get_protected(
|
145 |
request: Request,
|
146 |
-
|
147 |
-
|
148 |
):
|
149 |
-
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
db_user = get_user_by_email(db, user_email)
|
152 |
if db_user is None or not db_user.is_verified:
|
153 |
-
raise HTTPException(status_code=
|
154 |
|
155 |
# Render a template response
|
156 |
return templates.TemplateResponse("protected.html", {"request": request, "user": db_user.username})
|
|
|
143 |
@app.get("/protected", response_class=HTMLResponse)
|
144 |
async def get_protected(
|
145 |
request: Request,
|
146 |
+
db: Session = Depends(get_db),
|
147 |
+
token: Optional[str] = None # token is Optional because it may come from the cookie
|
148 |
):
|
149 |
+
# Try to get the token from the query parameter first, then fall back to the cookie
|
150 |
+
token = token or request.cookies.get("access_token")
|
151 |
+
if not token:
|
152 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
153 |
+
|
154 |
+
# Here verify_token is used directly in the endpoint
|
155 |
+
# If the token is invalid, verify_token will raise an HTTPException and the following lines will not be executed
|
156 |
+
user_email = verify_token(token) # Assuming that verify_token returns the user's email if the token is valid
|
157 |
+
|
158 |
+
# Get the user from the database
|
159 |
db_user = get_user_by_email(db, user_email)
|
160 |
if db_user is None or not db_user.is_verified:
|
161 |
+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or not verified in the database")
|
162 |
|
163 |
# Render a template response
|
164 |
return templates.TemplateResponse("protected.html", {"request": request, "user": db_user.username})
|