Gregniuki commited on
Commit
1e17d31
1 Parent(s): 03d6d1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -0
app.py CHANGED
@@ -310,7 +310,29 @@ def register_user(user_data: UserCreate, db: Session):
310
  db.commit()
311
  db.refresh(new_user)
312
  return new_user
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
 
 
 
 
 
 
 
314
  def verify_email(verification_token: str, db: Session = Depends(get_db)):
315
  # Verify the email using the token
316
  user = get_user_by_verification_token(db, verification_token)
 
310
  db.commit()
311
  db.refresh(new_user)
312
  return new_user
313
+
314
+ @app.get("/protected", response_class=HTMLResponse)
315
+ async def get_protected(
316
+ request: Request,
317
+ db: Session = Depends(get_db),
318
+ token: Optional[str] = None # token is Optional because it may come from the cookie
319
+ ):
320
+ # Try to get the token from the query parameter first, then fall back to the cookie
321
+ token = token or request.cookies.get("access_token")
322
+ if not token:
323
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
324
+
325
+ # Here verify_token is used directly in the endpoint
326
+ # If the token is invalid, verify_token will raise an HTTPException and the following lines will not be executed
327
+ user_email = verify_token(token) # Assuming that verify_token returns the user's email if the token is valid
328
 
329
+ # Get the user from the database
330
+ db_user = get_user_by_email(db, user_email)
331
+ if db_user is None or not db_user.is_verified:
332
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or not verified in the database")
333
+
334
+ # Render a template response
335
+ return templates.TemplateResponse("protected.html", {"request": request, "user": db_user.username})
336
  def verify_email(verification_token: str, db: Session = Depends(get_db)):
337
  # Verify the email using the token
338
  user = get_user_by_verification_token(db, verification_token)