ClientTest / app.py
zinoubm's picture
app is in beta and ready for testing
b0abe84
raw
history blame
2.38 kB
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from google_manager.constants import SCOPES
from pages.auth_page import html_content
import google_auth_oauthlib.flow
from starlette.middleware.sessions import SessionMiddleware
import gradio as gr
from gpt_summary import Ui
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="mysecret")
app.mount("/assets", StaticFiles(directory="assets"), name="assets")
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
print("request session")
print(request.session)
state = request.session.get("state", None)
print("state")
print(state)
if state:
return RedirectResponse("/gradio")
else:
return HTMLResponse(content=html_content, status_code=200)
@app.get("/auth")
async def integreate_google(request: Request):
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)
@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")
app = gr.mount_gradio_app(app, Ui, path="/gradio")
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,
}