from fastapi import FastAPI, Request from fastapi.responses import RedirectResponse, HTMLResponse from fastapi.staticfiles import StaticFiles from google_manager.constants import SCOPES from pages.load_page import load_page import google_auth_oauthlib.flow from starlette.middleware.sessions import SessionMiddleware import gradio as gr from gpt_summary import Ui # Create an instance of the FastAPI app app = FastAPI() # Add Session middleware to the app app.add_middleware(SessionMiddleware, secret_key="mysecret") # Mount the static files directory app.mount("/assets", StaticFiles(directory="assets"), name="assets") @app.get("/", response_class=HTMLResponse) async def home(request: Request): # Load the html content of the auth page html_content = load_page("./pages/auth_page.html") # print("request session") # print(request.session) creds = request.session.get("credentials", None) # print("state") # print(creds) if not creds or not creds.valid: return HTMLResponse(content=html_content, status_code=200) else: return RedirectResponse("/gradio/?__theme=dark") # Define the endpoint for Google authentication @app.get("/auth") async def integrate_google(request: Request): # print(SCOPES) flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( "credentials.json", scopes=SCOPES ) flow.redirect_uri = "http://127.0.0.1:8000/auth_callback" authorization_url, state = flow.authorization_url( access_type="offline", include_granted_scopes="true", ) request.session["state"] = state return RedirectResponse(url=authorization_url) # Define the callback endpoint after successful authentication @app.get("/auth_callback") async def auth_callback(request: Request): state = request.session["state"] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( "credentials.json", scopes=SCOPES, state=state ) flow.redirect_uri = "http://127.0.0.1:8000/auth_callback" # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = str(request.url) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials request.session["credentials"] = credentials_to_dict(credentials) return RedirectResponse("/gradio?__theme=dark") # Mount the Gradio UI app = gr.mount_gradio_app(app, Ui, path="/gradio") # Define a helper function to convert credentials to dictionary def credentials_to_dict(credentials): return { "token": credentials.token, "refresh_token": credentials.refresh_token, "token_uri": credentials.token_uri, "client_id": credentials.client_id, "client_secret": credentials.client_secret, "scopes": credentials.scopes, }