Gregniuki commited on
Commit
ca1fdb8
1 Parent(s): cbc30e5

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +28 -6
main.py CHANGED
@@ -132,13 +132,35 @@ async def verify_email(verification_token: str, db: Session = Depends(get_db)):
132
  # Redirect to the protected route with the token as a query parameter (or as required by your front-end/client)
133
  return RedirectResponse(url=f"/protected?token={access_token}")
134
 
 
 
135
 
136
 
137
  @app.get("/protected", response_class=HTMLResponse)
138
- async def get_protected(
139
- request: Request,
140
- token: str = Query(None), # Accept token from query parameters
141
- db: Session = Depends(get_db)
142
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  # Now pass both the request and token to the protected_route function
144
- return await protected_route(request, token, db)
 
132
  # Redirect to the protected route with the token as a query parameter (or as required by your front-end/client)
133
  return RedirectResponse(url=f"/protected?token={access_token}")
134
 
135
+ from jwt import decode, PyJWTError # make sure jwt is imported
136
+
137
 
138
 
139
  @app.get("/protected", response_class=HTMLResponse)
140
+ async def get_protected(request: Request, token: Optional[str] = None, db: Session = Depends(get_db)):
141
+ # Try to get the token from the query parameter first, then fall back to the cookie
142
+ token = token or request.cookies.get("access_token")
143
+ if not token:
144
+ raise HTTPException(status_code=401, detail="Not authenticated")
145
+
146
+ try:
147
+ payload = decode(token, auth_views.SECRET_KEY, algorithms=[auth_views.ALGORITHM])
148
+ user_email = payload.get("sub")
149
+ if user_email is None:
150
+ raise HTTPException(status_code=401, detail="Not authenticated")
151
+ except PyJWTError:
152
+ raise HTTPException(status_code=401, detail="Could not validate credentials")
153
+
154
+ db_user = get_user_by_email(db, user_email)
155
+ if db_user is None or not db_user.is_verified:
156
+ raise HTTPException(status_code=401, detail="User not found or not verified in the database")
157
+
158
+ return templates.TemplateResponse("protected.html", {"request": request, "user": db_user})
159
+
160
+ #async def get_protected(
161
+ # request: Request,
162
+ # token: str = Query(None), # Accept token from query parameters
163
+ # db: Session = Depends(get_db)
164
+ #):
165
  # Now pass both the request and token to the protected_route function
166
+ # return await protected_route(request, token, db)