Gregniuki commited on
Commit
493f2fc
·
1 Parent(s): ddcb46f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +13 -5
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
- token: str = Depends(verify_token), # Use Depends to inject the token after verification
147
- db: Session = Depends(get_db)
148
  ):
149
- user_email = token # As verify_token returns the 'sub' which is user email
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=401, detail="User not found or not verified in the database")
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})