Spaces:
Sleeping
Sleeping
File size: 4,838 Bytes
ae87f3d b50348a ae87f3d 30ca3a9 ae87f3d b50348a ae87f3d b50348a ae87f3d b50348a ae87f3d b50348a 30ca3a9 ae87f3d 30ca3a9 ae87f3d 30ca3a9 ae87f3d b50348a ae87f3d b50348a ae87f3d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | import os
from typing import Optional
import gradio as gr
import plotly.graph_objects as go
from authlib.integrations.base_client import OAuthError
from authlib.integrations.starlette_client import OAuth
from dotenv import load_dotenv
from fastapi import FastAPI
from starlette.config import Config
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
load_dotenv()
app = FastAPI(title="Orchestrator Evals OAuth", version="1.0.0")
SECRET_KEY = os.getenv("SECRET_KEY", "change-me")
SPACE_HOST = os.getenv("SPACE_HOST", "").strip()
LOCAL_HTTPS_REDIRECT = os.getenv("LOCAL_HTTPS_REDIRECT", "").strip().lower() in {"1", "true", "yes"}
config = Config(".env")
oauth = OAuth(config)
oauth.register(
name="google",
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": "openid email profile"},
)
def _external_base_url(request: Request) -> str:
# In HF Spaces, SPACE_HOST is the canonical public host.
if SPACE_HOST:
return f"https://{SPACE_HOST}"
base_url = str(request.base_url).rstrip("/")
return base_url
def _build_redirect_uri(request: Request) -> str:
external_base = _external_base_url(request)
redirect_uri = f"{external_base}/auth"
# For local dev with plain uvicorn, keep http unless explicitly opted-in.
if LOCAL_HTTPS_REDIRECT and ("://localhost" in redirect_uri or "://127.0.0.1" in redirect_uri):
redirect_uri = redirect_uri.replace("http://", "https://", 1)
return redirect_uri
def _user_from_session(request: Request) -> Optional[dict]:
if "session" not in request.scope:
return None
user = request.session.get("user")
if isinstance(user, dict):
return user
return None
class GradioAuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if request.url.path.startswith("/gradio"):
if _user_from_session(request) is None:
return RedirectResponse(url="/", status_code=307)
return await call_next(request)
app.add_middleware(GradioAuthMiddleware)
app.add_middleware(
SessionMiddleware,
secret_key=SECRET_KEY,
max_age=3600,
same_site="lax",
https_only=True,
)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def homepage(request: Request):
user = _user_from_session(request)
if user is None:
return templates.TemplateResponse(
request=request,
name="home_public.html",
context={"title": "Orchestrator Evals"},
)
name = user.get("name") or user.get("email") or "User"
return templates.TemplateResponse(
request=request,
name="home_authenticated.html",
context={"title": "Orchestrator Evals", "name": name},
)
@app.get("/login")
async def login(request: Request):
redirect_uri = _build_redirect_uri(request)
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.get("/auth")
async def auth(request: Request):
try:
token = await oauth.google.authorize_access_token(request)
user = await oauth.google.userinfo(token=token)
request.session["user"] = dict(user)
return RedirectResponse(url="/gradio", status_code=302)
except OAuthError as exc:
return HTMLResponse(f"OAuth error: {exc}", status_code=400)
except Exception as exc: # pragma: no cover
return HTMLResponse(f"Authentication failed: {exc}", status_code=500)
@app.get("/logout")
async def logout(request: Request):
request.session.pop("user", None)
return RedirectResponse(url="/", status_code=302)
@app.get("/health")
async def health():
return {"status": "ok"}
def _build_dummy_plot() -> go.Figure:
fig = go.Figure(
data=[
go.Scatter(
x=["Mon", "Tue", "Wed", "Thu", "Fri"],
y=[2, 4, 3, 5, 6],
mode="lines+markers",
name="Demo Series",
)
]
)
fig.update_layout(
title="Dummy Plotly Graph",
xaxis_title="Day",
yaxis_title="Value",
template="plotly_white",
)
return fig
with gr.Blocks(title="Orchestrator Evals") as gradio_ui:
gr.Markdown("## Protected Gradio UI")
gr.Markdown("This is a dummy Plotly graph behind Google OAuth.")
plot = gr.Plot(label="Plotly Demo")
gradio_ui.load(fn=_build_dummy_plot, outputs=plot)
app = gr.mount_gradio_app(app, gradio_ui, path="/gradio")
|