backend fixes

This commit is contained in:
Abubakar Abid 2024-10-10 15:25:55 -07:00
parent 9004b11064
commit 1b28536ea3
2 changed files with 7 additions and 12 deletions

View File

@ -11,6 +11,7 @@ from dataclasses import dataclass, field
import fastapi
from fastapi.responses import RedirectResponse
from huggingface_hub import HfFolder, whoami
from starlette.datastructures import URL
from gradio.utils import get_space
@ -23,8 +24,6 @@ MAX_REDIRECTS = 2
def attach_oauth(app: fastapi.FastAPI):
from gradio.route_utils import API_PREFIX
try:
from starlette.middleware.sessions import SessionMiddleware
except ImportError as e:
@ -36,13 +35,12 @@ def attach_oauth(app: fastapi.FastAPI):
# Add `/login/huggingface`, `/login/callback` and `/logout` routes to enable OAuth in the Gradio app.
# If the app is running in a Space, OAuth is enabled normally. Otherwise, we mock the "real" routes to make the
# user log in with a fake user profile - without any calls to hf.co.
router = fastapi.APIRouter(prefix=API_PREFIX)
app.include_router(router)
print(">", get_space(), get_space() is not None)
if get_space() is not None:
_add_oauth_routes(router)
_add_oauth_routes(app)
else:
_add_mocked_oauth_routes(router)
_add_mocked_oauth_routes(app)
# Session Middleware requires a secret key to sign the cookies. Let's use a hash
# of the OAuth secret key to make it unique to the Space + updated in case OAuth
@ -189,13 +187,9 @@ def _add_mocked_oauth_routes(app: fastapi.APIRouter) -> None:
@app.get("/logout")
async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
"""Endpoint that logs out the user (e.g. delete cookie session)."""
from gradio.route_utils import API_PREFIX
request.session.pop("oauth_info", None)
logout_url = str(request.url).replace(
f"{API_PREFIX}/logout", "/"
) # preserve query params
return RedirectResponse(url=logout_url)
logout_url = URL("/").include_query_params(**request.query_params)
return RedirectResponse(url=logout_url, status_code=302)
def _generate_redirect_uri(request: fastapi.Request) -> str:

View File

@ -491,6 +491,7 @@ class App(FastAPI):
# It allows users to "Sign in with HuggingFace". Otherwise, add the default
# logout route.
if app.blocks is not None and app.blocks.expects_oauth:
print(">>>> OAuth routes enabled.")
attach_oauth(app)
else: