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