Implement server-side OAuth for Docker Space
Browse files- Add OAuth endpoints to FastAPI backend (/api/auth/login, /api/auth/callback, /api/auth/session)
- Replace client-side OAuth with server-side flow using OAUTH_CLIENT_ID and OAUTH_CLIENT_SECRET
- Handle HuggingFace OAuth callback and token exchange
- Create session management for authenticated users
- Update frontend to use backend OAuth endpoints instead of @huggingface/hub
- Remove @huggingface/hub dependency (not needed for Docker Spaces)
- Fix 'Failed to start login process' error by implementing proper Docker Space OAuth
Files changed (3)
1234567891011121314151617181919 unmodified lines39404142434487 unmodified lines132133134135136137"""FastAPI backend for AnyCoder - provides REST API endpoints"""from fastapi import FastAPI, HTTPException, Header, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetime# Import only what we need, avoiding Gradio UI importsimport sysimport osfrom huggingface_hub import InferenceClient# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [19 unmodified linesallow_headers=["*"],)# Pydantic models for request/responseclass CodeGenerationRequest(BaseModel):87 unmodified linesreturn {"languages": LANGUAGE_CHOICES}@app.get("/api/auth/status")async def auth_status(authorization: Optional[str] = Header(None)):"""Check authentication status"""123456789101112131415161718192021222319 unmodified lines4344454647484950515253545556575859606187 unmodified lines149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""FastAPI backend for AnyCoder - provides REST API endpoints"""from fastapi import FastAPI, HTTPException, Header, WebSocket, WebSocketDisconnect, Request, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponse, RedirectResponse, JSONResponsefrom pydantic import BaseModelfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetimeimport secretsimport base64import urllib.parse# Import only what we need, avoiding Gradio UI importsimport sysimport osfrom huggingface_hub import InferenceClientimport httpx# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [19 unmodified linesallow_headers=["*"],)# OAuth configurationOAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "")OAUTH_CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "")OAUTH_SCOPES = os.getenv("OAUTH_SCOPES", "openid profile manage-repos")OPENID_PROVIDER_URL = os.getenv("OPENID_PROVIDER_URL", "https://huggingface.co")SPACE_HOST = os.getenv("SPACE_HOST", "localhost:7860")# In-memory store for OAuth states (in production, use Redis or similar)oauth_states = {}# In-memory store for user sessionsuser_sessions = {}# Pydantic models for request/responseclass CodeGenerationRequest(BaseModel):87 unmodified linesreturn {"languages": LANGUAGE_CHOICES}@app.get("/api/auth/login")async def oauth_login(request: Request):"""Initiate OAuth login flow"""# Generate a random state to prevent CSRFstate = secrets.token_urlsafe(32)oauth_states[state] = {"timestamp": datetime.now()}# Build redirect URIprotocol = "https" if SPACE_HOST and not SPACE_HOST.startswith("localhost") else "http"redirect_uri = f"{protocol}://{SPACE_HOST}/api/auth/callback"# Build authorization URLauth_url = (f"{OPENID_PROVIDER_URL}/oauth/authorize"f"?client_id={OAUTH_CLIENT_ID}"f"&redirect_uri={urllib.parse.quote(redirect_uri)}"f"&scope={urllib.parse.quote(OAUTH_SCOPES)}"f"&state={state}"f"&response_type=code")return JSONResponse({"login_url": auth_url, "state": state})@app.get("/api/auth/callback")async def oauth_callback(code: str, state: str, request: Request):"""Handle OAuth callback"""# Verify state to prevent CSRFif state not in oauth_states:raise HTTPException(status_code=400, detail="Invalid state parameter")# Clean up old statesoauth_states.pop(state, None)# Exchange code for tokensprotocol = "https" if SPACE_HOST and not SPACE_HOST.startswith("localhost") else "http"redirect_uri = f"{protocol}://{SPACE_HOST}/api/auth/callback"# Prepare authorization headerauth_string = f"{OAUTH_CLIENT_ID}:{OAUTH_CLIENT_SECRET}"auth_bytes = auth_string.encode('utf-8')auth_b64 = base64.b64encode(auth_bytes).decode('utf-8')async with httpx.AsyncClient() as client:try:token_response = await client.post(f"{OPENID_PROVIDER_URL}/oauth/token",data={"client_id": OAUTH_CLIENT_ID,"code": code,"grant_type": "authorization_code","redirect_uri": redirect_uri,},headers={"Authorization": f"Basic {auth_b64}","Content-Type": "application/x-www-form-urlencoded",},)token_response.raise_for_status()token_data = token_response.json()# Get user infoaccess_token = token_data.get("access_token")userinfo_response = await client.get(f"{OPENID_PROVIDER_URL}/oauth/userinfo",headers={"Authorization": f"Bearer {access_token}"},)userinfo_response.raise_for_status()user_info = userinfo_response.json()# Create sessionsession_token = secrets.token_urlsafe(32)user_sessions[session_token] = {"access_token": access_token,"user_info": user_info,"timestamp": datetime.now(),}# Redirect to frontend with session tokenfrontend_url = f"{protocol}://{SPACE_HOST}/?session={session_token}"return RedirectResponse(url=frontend_url)except httpx.HTTPError as e:print(f"OAuth error: {e}")raise HTTPException(status_code=500, detail=f"OAuth failed: {str(e)}")@app.get("/api/auth/session")async def get_session(session: str):"""Get user info from session token"""if session not in user_sessions:raise HTTPException(status_code=401, detail="Invalid session")session_data = user_sessions[session]return {"access_token": session_data["access_token"],"user_info": session_data["user_info"],}@app.get("/api/auth/status")async def auth_status(authorization: Optional[str] = Header(None)):"""Check authentication status"""
13 unmodified lines1415161718192013 unmodified lines"react-dom": "^18.3.1","axios": "^1.7.2","@monaco-editor/react": "^4.6.0","@huggingface/hub": "^0.15.1","prismjs": "^1.29.0","react-markdown": "^9.0.1","remark-gfm": "^4.0.0"13 unmodified lines14151617181913 unmodified lines"react-dom": "^18.3.1","axios": "^1.7.2","@monaco-editor/react": "^4.6.0","prismjs": "^1.29.0","react-markdown": "^9.0.1","remark-gfm": "^4.0.0"
12345678910111213141516171824 unmodified lines434445464748495051525354553 unmodified lines596061626364656 unmodified lines727374757677787980818283848586878889// HuggingFace OAuth authentication utilitiesimport { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";const STORAGE_KEY = 'hf_oauth_token';const USER_INFO_KEY = 'hf_user_info';const DEV_MODE_KEY = 'hf_dev_mode';// Check if we're in development mode (localhost)const isDevelopment = typeof window !== 'undefined' &&(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');export interface OAuthUserInfo {id: string;name: string;preferredUsername?: string;avatarUrl?: string;}24 unmodified linesreturn null;}// Check if we're handling an OAuth redirectconst oauthResult = await oauthHandleRedirectIfPresent();if (oauthResult) {// Store the OAuth resultstoreOAuthData(oauthResult);return oauthResult;}// Check if we have stored credentials3 unmodified linesif (storedToken && storedUserInfo) {return {accessToken: storedToken,accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // Assume 24huserInfo: storedUserInfo,};}6 unmodified lines}/*** Redirect to HuggingFace OAuth login page*/export async function loginWithHuggingFace(): Promise<void> {try {const loginUrl = await oauthLoginUrl({// Redirect back to the current pageredirectUrl: window.location.href,// Request scopes - adjust as neededscopes: "openid profile inference-api",});window.location.href = loginUrl;} catch (error) {console.error('Failed to initiate OAuth login:', error);throw new Error('Failed to start login process');12345678910111213141516171819202124 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586873 unmodified lines919293949596976 unmodified lines104105106107108109110111112113114115116117118119120121122// HuggingFace OAuth authentication utilities (Server-side flow for Docker Spaces)const STORAGE_KEY = 'hf_oauth_token';const USER_INFO_KEY = 'hf_user_info';const DEV_MODE_KEY = 'hf_dev_mode';const API_BASE = '/api';// Check if we're in development mode (localhost)const isDevelopment = typeof window !== 'undefined' &&(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');export interface OAuthUserInfo {id?: string;sub?: string;name: string;preferred_username?: string;preferredUsername?: string;picture?: string;avatarUrl?: string;}24 unmodified linesreturn null;}// Check if we're handling an OAuth callback (session parameter in URL)const urlParams = new URLSearchParams(window.location.search);const sessionToken = urlParams.get('session');if (sessionToken) {// Fetch session data from backendtry {const response = await fetch(`${API_BASE}/auth/session?session=${sessionToken}`);if (response.ok) {const data = await response.json();// Normalize user infoconst userInfo: OAuthUserInfo = {id: data.user_info.sub || data.user_info.id,name: data.user_info.name,preferredUsername: data.user_info.preferred_username || data.user_info.preferredUsername,avatarUrl: data.user_info.picture || data.user_info.avatarUrl,};const oauthResult: OAuthResult = {accessToken: data.access_token,accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),userInfo,};// Store the OAuth resultstoreOAuthData(oauthResult);// Clean up URLwindow.history.replaceState({}, document.title, window.location.pathname);return oauthResult;}} catch (error) {console.error('Failed to fetch session:', error);}}// Check if we have stored credentials3 unmodified linesif (storedToken && storedUserInfo) {return {accessToken: storedToken,accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),userInfo: storedUserInfo,};}6 unmodified lines}/*** Redirect to HuggingFace OAuth login page (via backend)*/export async function loginWithHuggingFace(): Promise<void> {try {// Call backend to get OAuth URLconst response = await fetch(`${API_BASE}/auth/login`);if (!response.ok) {throw new Error('Failed to get login URL');}const data = await response.json();// Redirect to the OAuth authorization URLwindow.location.href = data.login_url;} catch (error) {console.error('Failed to initiate OAuth login:', error);throw new Error('Failed to start login process');
backend_api.py+119-2
frontend/package.json-1
frontend/src/lib/auth.ts+51-18