fix(google): auth is now in state (#2647)

# Description

Please include a summary of the changes and the related issue. Please
also include relevant motivation and context.

## Checklist before requesting a review

Please delete options that are not relevant.

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented hard-to-understand areas
- [ ] I have ideally added tests that prove my fix is effective or that
my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged

## Screenshots (if appropriate):
This commit is contained in:
Stan Girard 2024-06-09 22:23:50 +02:00 committed by GitHub
parent 7467707da4
commit 11a2e888da
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -2,6 +2,7 @@ import json
import os import os
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import HTMLResponse
from google_auth_oauthlib.flow import Flow from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build from googleapiclient.discovery import build
from logger import get_logger from logger import get_logger
@ -9,9 +10,8 @@ from middlewares.auth import AuthBearer, get_current_user
from modules.sync.dto.inputs import SyncsUserInput, SyncUserUpdateInput from modules.sync.dto.inputs import SyncsUserInput, SyncUserUpdateInput
from modules.sync.service.sync_service import SyncService, SyncUserService from modules.sync.service.sync_service import SyncService, SyncUserService
from modules.user.entity.user_identity import UserIdentity from modules.user.entity.user_identity import UserIdentity
from .successfull_connection import successfullConnectionPage
from fastapi.responses import HTMLResponse
from .successfull_connection import successfullConnectionPage
# Set environment variable for OAuthlib # Set environment variable for OAuthlib
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
@ -45,7 +45,12 @@ CLIENT_SECRETS_FILE_CONTENT = {
"token_uri": os.getenv("GOOGLE_TOKEN_URI"), "token_uri": os.getenv("GOOGLE_TOKEN_URI"),
"auth_provider_x509_cert_url": os.getenv("GOOGLE_AUTH_PROVIDER_CERT_URL"), "auth_provider_x509_cert_url": os.getenv("GOOGLE_AUTH_PROVIDER_CERT_URL"),
"client_secret": os.getenv("GOOGLE_CLIENT_SECRET"), "client_secret": os.getenv("GOOGLE_CLIENT_SECRET"),
"redirect_uris": [os.getenv("GOOGLE_REDIRECT_URI")], "redirect_uris": os.getenv("GOOGLE_REDIRECT_URI", "http://localhost").split(
","
),
"javascript_origins": os.getenv(
"GOOGLE_JAVASCRIPT_ORIGINS", "http://localhost"
).split(","),
} }
} }
@ -69,12 +74,15 @@ def authorize_google(
dict: A dictionary containing the authorization URL. dict: A dictionary containing the authorization URL.
""" """
logger.debug(f"Authorizing Google Drive sync for user: {current_user.id}") logger.debug(f"Authorizing Google Drive sync for user: {current_user.id}")
redirect_uri = f"{BASE_REDIRECT_URI}?user_id={current_user.id}" redirect_uri = BASE_REDIRECT_URI
flow = Flow.from_client_config( flow = Flow.from_client_config(
CLIENT_SECRETS_FILE_CONTENT, scopes=SCOPES, redirect_uri=redirect_uri CLIENT_SECRETS_FILE_CONTENT,
scopes=SCOPES,
redirect_uri=redirect_uri,
) )
state = f"user_id={current_user.id}"
authorization_url, state = flow.authorization_url( authorization_url, state = flow.authorization_url(
access_type="offline", include_granted_scopes="true" access_type="offline", include_granted_scopes="true", state=state
) )
logger.info( logger.info(
f"Generated authorization URL: {authorization_url} for user: {current_user.id}" f"Generated authorization URL: {authorization_url} for user: {current_user.id}"
@ -103,7 +111,8 @@ def oauth2callback_google(request: Request):
""" """
state = request.query_params.get("state") state = request.query_params.get("state")
state_dict = {"state": state} state_dict = {"state": state}
current_user = request.query_params.get("user_id") logger.info(f"State: {state}")
current_user = state.split("=")[1] if state else None
logger.debug( logger.debug(
f"Handling OAuth2 callback for user: {current_user} with state: {state}" f"Handling OAuth2 callback for user: {current_user} with state: {state}"
) )
@ -115,9 +124,10 @@ def oauth2callback_google(request: Request):
raise HTTPException(status_code=400, detail="Invalid state parameter") raise HTTPException(status_code=400, detail="Invalid state parameter")
if sync_user_state.get("user_id") != current_user: if sync_user_state.get("user_id") != current_user:
logger.error("Invalid user") logger.error("Invalid user")
logger.info(f"Invalid user: {current_user}")
raise HTTPException(status_code=400, detail="Invalid user") raise HTTPException(status_code=400, detail="Invalid user")
redirect_uri = f"{BASE_REDIRECT_URI}?user_id={current_user}" redirect_uri = f"{BASE_REDIRECT_URI}"
flow = Flow.from_client_config( flow = Flow.from_client_config(
CLIENT_SECRETS_FILE_CONTENT, CLIENT_SECRETS_FILE_CONTENT,
scopes=SCOPES, scopes=SCOPES,