Update main.py
Browse files
main.py
CHANGED
@@ -186,16 +186,32 @@ from jwt import ExpiredSignatureError, InvalidTokenError # Ensure you've import
|
|
186 |
|
187 |
@app.get("/login", response_class=HTMLResponse)
|
188 |
async def login(request: Request, db: Session = Depends(get_db)):
|
189 |
-
# Try to retrieve the access token from the cookie
|
190 |
access_token = request.cookies.get("access_token")
|
191 |
|
192 |
if access_token:
|
193 |
try:
|
194 |
-
# Remove the 'Bearer ' prefix and verify the token
|
195 |
user_email = verify_token(access_token.split("Bearer ")[1])
|
196 |
if user_email:
|
197 |
-
#
|
198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
except ExpiredSignatureError:
|
200 |
# Token has expired. You could redirect to the login page or inform the user
|
201 |
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Token expired")
|
@@ -210,6 +226,7 @@ async def login(request: Request, db: Session = Depends(get_db)):
|
|
210 |
# If not authenticated, show the login page
|
211 |
return templates.TemplateResponse("login.html", {"request": request})
|
212 |
|
|
|
213 |
|
214 |
@app.post("/login")
|
215 |
async def login_post(
|
|
|
186 |
|
187 |
@app.get("/login", response_class=HTMLResponse)
|
188 |
async def login(request: Request, db: Session = Depends(get_db)):
|
|
|
189 |
access_token = request.cookies.get("access_token")
|
190 |
|
191 |
if access_token:
|
192 |
try:
|
|
|
193 |
user_email = verify_token(access_token.split("Bearer ")[1])
|
194 |
if user_email:
|
195 |
+
# Retrieve the user from the database
|
196 |
+
db_user = db.query(User).filter(User.email == user_email).first()
|
197 |
+
if not db_user:
|
198 |
+
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="User not found")
|
199 |
+
|
200 |
+
# Check if user is verified
|
201 |
+
if not db_user.is_verified:
|
202 |
+
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="User is not verified")
|
203 |
+
|
204 |
+
# Create a new access token for the user
|
205 |
+
new_access_token = auth_views.create_access_token(
|
206 |
+
data={"sub": db_user.email},
|
207 |
+
expires_delta=timedelta(minutes=auth_views.ACCESS_TOKEN_EXPIRE_MINUTES)
|
208 |
+
)
|
209 |
+
|
210 |
+
# Redirect the user to the protected route
|
211 |
+
url = app.url_path_for("get_protected")
|
212 |
+
response = RedirectResponse(url)
|
213 |
+
response.set_cookie(key="access_token", value=f"Bearer {new_access_token}", httponly=True)
|
214 |
+
return response
|
215 |
except ExpiredSignatureError:
|
216 |
# Token has expired. You could redirect to the login page or inform the user
|
217 |
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Token expired")
|
|
|
226 |
# If not authenticated, show the login page
|
227 |
return templates.TemplateResponse("login.html", {"request": request})
|
228 |
|
229 |
+
|
230 |
|
231 |
@app.post("/login")
|
232 |
async def login_post(
|