Update main.py
Browse files
main.py
CHANGED
@@ -37,40 +37,23 @@ oauth.register(
|
|
37 |
api_base_url='https://www.googleapis.com/oauth2/v1/',
|
38 |
client_kwargs={'scope': 'openid email profile'}
|
39 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
@app.get("/auth/callback")
|
41 |
async def auth_callback(request: Request, db: Session = Depends(get_db)):
|
42 |
# Exchange code for token
|
43 |
token = await oauth.google.authorize_access_token(request)
|
44 |
-
|
45 |
# Use token to get user info
|
46 |
user_info = await oauth.google.parse_id_token(request, token)
|
47 |
|
48 |
-
#
|
49 |
-
|
50 |
-
if not db_user:
|
51 |
-
# Create a new user if they don't exist
|
52 |
-
db_user = User(email=user_info['email'], username=user_info.get('name', ''))
|
53 |
-
db.add(db_user)
|
54 |
-
db.commit()
|
55 |
-
db.refresh(db_user)
|
56 |
|
57 |
-
# Create an access token for the user
|
58 |
-
access_token = auth_views.create_access_token(
|
59 |
-
data={"sub": db_user.email},
|
60 |
-
expires_delta=timedelta(minutes=auth_views.ACCESS_TOKEN_EXPIRE_MINUTES)
|
61 |
-
)
|
62 |
-
|
63 |
-
# Redirect the user to the protected route
|
64 |
-
response = RedirectResponse(url="/protected")
|
65 |
-
response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
|
66 |
-
return response
|
67 |
-
@app.get("/auth/callback")
|
68 |
-
async def auth_callback(request: Request, db: Session = Depends(get_db)):
|
69 |
-
# Exchange code for token
|
70 |
-
token = await oauth.google.authorize_access_token(request)
|
71 |
-
|
72 |
-
# Use token to get user info
|
73 |
-
user_info = await oauth.google.parse_id_token(request, token)
|
74 |
|
75 |
# Check if this user is already in your database, if not, create a new user record
|
76 |
db_user = db.query(User).filter(User.email == user_info['email']).first()
|
|
|
37 |
api_base_url='https://www.googleapis.com/oauth2/v1/',
|
38 |
client_kwargs={'scope': 'openid email profile'}
|
39 |
)
|
40 |
+
@app.get("/login/oauth")
|
41 |
+
async def login_oauth(request: Request):
|
42 |
+
# Redirect to OAuth provider (e.g., Google)
|
43 |
+
redirect_uri = request.url_for('auth_callback')
|
44 |
+
return await oauth.google.authorize_redirect(request, redirect_uri)
|
45 |
+
|
46 |
@app.get("/auth/callback")
|
47 |
async def auth_callback(request: Request, db: Session = Depends(get_db)):
|
48 |
# Exchange code for token
|
49 |
token = await oauth.google.authorize_access_token(request)
|
50 |
+
|
51 |
# Use token to get user info
|
52 |
user_info = await oauth.google.parse_id_token(request, token)
|
53 |
|
54 |
+
# Store user_info in session
|
55 |
+
request.session["user_info"] = user_info
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
# Check if this user is already in your database, if not, create a new user record
|
59 |
db_user = db.query(User).filter(User.email == user_info['email']).first()
|