Gregniuki commited on
Commit
7c0b4d6
1 Parent(s): 5ed4a12

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +24 -36
main.py CHANGED
@@ -40,44 +40,29 @@ async def login(request: Request):
40
  return templates.TemplateResponse("login.html", {"request": request})
41
 
42
 
43
- @app.post("/login", response_class=HTMLResponse)
 
 
44
  async def login_post(
45
  request: Request,
46
  email: str = Form(...),
47
  password: str = Form(...),
48
- db: Session = Depends(get_db),
49
- # token: str = Depends(oauth2_scheme) # Check if the user has a valid token
50
  ):
51
- # if token:
52
- # If the user already has a valid token, redirect to protected.html
53
- # return templates.TemplateResponse("protected.html", {"request": request, "user": token})
54
-
55
- # Validate the email and password
56
  if not email or not password:
57
  raise HTTPException(status_code=400, detail="Invalid email or password")
58
 
59
- # Check user authentication using the provided email and password
60
  user = authenticate_user(db, email, password)
61
-
62
- if user is not None:
63
- # Authentication succeeded
64
- # Create an access token and handle login success
65
  access_token = auth_views.create_access_token(
66
  data={"sub": user.email},
67
- expires_delta=timedelta(minutes=auth_views.ACCESS_TOKEN_EXPIRE_MINUTES),
68
  )
69
 
70
- # Set the access_token (if desired)
71
- user.token = access_token
72
-
73
- # Commit the changes to the database
74
- db.commit()
75
-
76
- # Handle the login success as needed
77
- return templates.TemplateResponse("protected.html", {"request": request, "user": user.username})
78
  else:
79
- # Authentication failed
80
- # Handle login failure, e.g., display an error message
81
  return templates.TemplateResponse("login.html", {"request": request, "error_message": "Invalid email or password"})
82
 
83
  @app.get("/register", response_class=HTMLResponse)
@@ -141,19 +126,22 @@ async def verify_email(verification_token: str, db: Session = Depends(get_db)):
141
  # Redirect to the protected route with the token as a query parameter (or as required by your front-end/client)
142
  return RedirectResponse(url=f"/protected?token={access_token}")
143
 
144
- # User authentication (protected route)
145
- @app.post("/protected", response_class=HTMLResponse) # Specify response_class as HTMLResponse
146
- async def protected_route(request: Request, token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
147
- # Verify the access token
148
- user = verify_token(token, my_secret_key, "HS256")
149
- if user is None:
150
- raise HTTPException(status_code=401, detail="Invalid or expired token")
151
-
152
- # Check if the user exists in the database
153
- db_user = get_user_by_email(db, user) # Modify this to match your database query
154
 
 
 
 
 
 
 
 
 
 
155
  if db_user is None:
156
  raise HTTPException(status_code=401, detail="User not found in the database")
157
 
158
- # The user exists in the database, and you can render the protected route template
159
- return templates.TemplateResponse("protected.html", {"request": request, "user": user.email})
 
40
  return templates.TemplateResponse("login.html", {"request": request})
41
 
42
 
43
+ from fastapi.responses import RedirectResponse
44
+
45
+ @app.post("/login")
46
  async def login_post(
47
  request: Request,
48
  email: str = Form(...),
49
  password: str = Form(...),
50
+ db: Session = Depends(get_db)
 
51
  ):
 
 
 
 
 
52
  if not email or not password:
53
  raise HTTPException(status_code=400, detail="Invalid email or password")
54
 
 
55
  user = authenticate_user(db, email, password)
56
+ if user:
 
 
 
57
  access_token = auth_views.create_access_token(
58
  data={"sub": user.email},
59
+ expires_delta=timedelta(minutes=auth_views.ACCESS_TOKEN_EXPIRE_MINUTES)
60
  )
61
 
62
+ response = RedirectResponse(url="/protected", status_code=status.HTTP_303_SEE_OTHER)
63
+ response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
64
+ return response
 
 
 
 
 
65
  else:
 
 
66
  return templates.TemplateResponse("login.html", {"request": request, "error_message": "Invalid email or password"})
67
 
68
  @app.get("/register", response_class=HTMLResponse)
 
126
  # Redirect to the protected route with the token as a query parameter (or as required by your front-end/client)
127
  return RedirectResponse(url=f"/protected?token={access_token}")
128
 
129
+ @app.get("/protected", response_class=HTMLResponse)
130
+ async def protected_route(request: Request, db: Session = Depends(get_db)):
131
+ token = request.cookies.get("access_token")
132
+ if not token:
133
+ raise HTTPException(status_code=401, detail="Not authenticated")
 
 
 
 
 
134
 
135
+ try:
136
+ payload = jwt.decode(token.split(" ")[1], auth_views.SECRET_KEY, algorithms=[auth_views.ALGORITHM])
137
+ user_email = payload.get("sub")
138
+ if user_email is None:
139
+ raise HTTPException(status_code=401, detail="Not authenticated")
140
+ except jwt.PyJWTError:
141
+ raise HTTPException(status_code=401, detail="Not authenticated")
142
+
143
+ db_user = get_user_by_email(db, user_email)
144
  if db_user is None:
145
  raise HTTPException(status_code=401, detail="User not found in the database")
146
 
147
+ return templates.TemplateResponse("protected.html", {"request": request, "user": db_user})