fix oauth issue
Browse filesFiles changed (5)
7 unmodified lines89101112137 unmodified linespinned: falsedisable_embedding: falsehf_oauth: truehf_oauth_scopes:- manage-repos---7 unmodified lines8910111213147 unmodified linespinned: falsedisable_embedding: falsehf_oauth: truehf_oauth_expiration_minutes: 43200hf_oauth_scopes:- manage-repos---
7 unmodified lines891011121314125 unmodified lines140141142143144145179 unmodified lines3253263273283293303313323333343353367 unmodified lines3443453463473483491 unmodified line3513523533543553562 unmodified lines3593603613623633643653663673683693703713727 unmodified linesfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetimeimport secretsimport base64import urllib.parse125 unmodified linesuser_sessions = {}# Pydantic models for request/responseclass CodeGenerationRequest(BaseModel):query: str179 unmodified linesuserinfo_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(),"username": user_info.get("name") or user_info.get("preferred_username") or "user","deployed_spaces": [] # Track deployed spaces for follow-up updates}7 unmodified linesraise 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"""1 unmodified lineraise 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"],2 unmodified lines@app.get("/api/auth/status")async def auth_status(authorization: Optional[str] = Header(None)):"""Check authentication status"""auth = get_auth_from_header(authorization)if auth.is_authenticated():return AuthStatus(authenticated=True,username=auth.username,message=f"Authenticated as {auth.username}")return AuthStatus(authenticated=False,username=None,7 unmodified lines891011121314125 unmodified lines140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185179 unmodified lines3653663673683693703713723733743753763773783793803813827 unmodified lines3903913923933943953963973983994004014024034044054064074084094101 unmodified line4124134144154164174184194204214224234244254264274284294302 unmodified lines4334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025037 unmodified linesfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetime, timedeltaimport secretsimport base64import urllib.parse125 unmodified linesuser_sessions = {}def is_session_expired(session_data: dict) -> bool:"""Check if session has expired"""expires_at = session_data.get("expires_at")if not expires_at:# If no expiration info, check if session is older than 8 hourstimestamp = session_data.get("timestamp", datetime.now())return (datetime.now() - timestamp) > timedelta(hours=8)return datetime.now() >= expires_at# Background task for cleaning up expired sessionsasync def cleanup_expired_sessions():"""Periodically clean up expired sessions"""while True:try:await asyncio.sleep(3600) # Run every hourexpired_sessions = []for session_token, session_data in user_sessions.items():if is_session_expired(session_data):expired_sessions.append(session_token)for session_token in expired_sessions:user_sessions.pop(session_token, None)print(f"[Auth] Cleaned up expired session: {session_token[:10]}...")if expired_sessions:print(f"[Auth] Cleaned up {len(expired_sessions)} expired session(s)")except Exception as e:print(f"[Auth] Cleanup error: {e}")# Start cleanup task on app startup@app.on_event("startup")async def startup_event():"""Run startup tasks"""asyncio.create_task(cleanup_expired_sessions())print("[Startup] ✅ Session cleanup task started")# Pydantic models for request/responseclass CodeGenerationRequest(BaseModel):query: str179 unmodified linesuserinfo_response.raise_for_status()user_info = userinfo_response.json()# Calculate token expiration# OAuth tokens typically have expires_in in secondsexpires_in = token_data.get("expires_in", 28800) # Default 8 hoursexpires_at = datetime.now() + timedelta(seconds=expires_in)# Create sessionsession_token = secrets.token_urlsafe(32)user_sessions[session_token] = {"access_token": access_token,"user_info": user_info,"timestamp": datetime.now(),"expires_at": expires_at,"username": user_info.get("name") or user_info.get("preferred_username") or "user","deployed_spaces": [] # Track deployed spaces for follow-up updates}7 unmodified linesraise HTTPException(status_code=500, detail=f"OAuth failed: {str(e)}")async def validate_token_with_hf(access_token: str) -> bool:"""Validate token with HuggingFace API"""try:async with httpx.AsyncClient() as client:response = await client.get(f"{OPENID_PROVIDER_URL}/oauth/userinfo",headers={"Authorization": f"Bearer {access_token}"},timeout=5.0)return response.status_code == 200except Exception as e:print(f"[Auth] Token validation error: {e}")return False@app.get("/api/auth/session")async def get_session(session: str):"""Get user info from session token"""1 unmodified lineraise HTTPException(status_code=401, detail="Invalid session")session_data = user_sessions[session]# Check if session has expiredif is_session_expired(session_data):# Clean up expired sessionuser_sessions.pop(session, None)raise HTTPException(status_code=401, detail="Session expired. Please sign in again.")# Validate token with HuggingFaceif not await validate_token_with_hf(session_data["access_token"]):# Token is invalid, clean up sessionuser_sessions.pop(session, None)raise HTTPException(status_code=401, detail="Authentication expired. Please sign in again.")return {"access_token": session_data["access_token"],"user_info": session_data["user_info"],2 unmodified lines@app.get("/api/auth/status")async def auth_status(authorization: Optional[str] = Header(None)):"""Check authentication status and validate token"""auth = get_auth_from_header(authorization)if not auth.is_authenticated():return AuthStatus(authenticated=False,username=None,message="Not authenticated")# For dev tokens, skip validationif auth.token and auth.token.startswith("dev_token_"):return AuthStatus(authenticated=True,username=auth.username,message=f"Authenticated as {auth.username} (dev mode)")# For session tokens, check expiration and validatetoken = authorization.replace("Bearer ", "") if authorization else Noneif token and "-" in token and len(token) > 20 and token in user_sessions:session_data = user_sessions[token]# Check if session has expiredif is_session_expired(session_data):# Clean up expired sessionuser_sessions.pop(token, None)return AuthStatus(authenticated=False,username=None,message="Session expired")# Validate token with HuggingFaceif not await validate_token_with_hf(session_data["access_token"]):# Token is invalid, clean up sessionuser_sessions.pop(token, None)return AuthStatus(authenticated=False,username=None,message="Authentication expired")return AuthStatus(authenticated=True,username=auth.username,message=f"Authenticated as {auth.username}")# For direct OAuth tokens, validate with HFif auth.token:is_valid = await validate_token_with_hf(auth.token)if is_valid:return AuthStatus(authenticated=True,username=auth.username,message=f"Authenticated as {auth.username}")else:return AuthStatus(authenticated=False,username=None,message="Token expired or invalid")return AuthStatus(authenticated=False,username=None,
94 unmodified lines959697989910094 unmodified linesreturn () => window.removeEventListener('storage', handleStorageChange);}, []);// Listen for window focus (user returns to tab after OAuth redirect)// Only check if backend was available before or if we're authenticated with tokenuseEffect(() => {94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811994 unmodified linesreturn () => window.removeEventListener('storage', handleStorageChange);}, []);// Listen for authentication expiration eventsuseEffect(() => {const handleAuthExpired = (e: CustomEvent) => {console.log('[Auth] Session expired:', e.detail?.message);// Clear authentication statesetIsAuthenticated(false);setUsername(null);apiClient.setToken(null);// Show alert to userif (typeof window !== 'undefined') {alert(e.detail?.message || 'Your session has expired. Please sign in again.');}};window.addEventListener('auth-expired', handleAuthExpired as EventListener);return () => window.removeEventListener('auth-expired', handleAuthExpired as EventListener);}, []);// Listen for window focus (user returns to tab after OAuth redirect)// Only check if backend was available before or if we're authenticated with tokenuseEffect(() => {
59 unmodified lines60616263646559 unmodified linesreturn config;});// Load token from localStorage on client sideif (typeof window !== 'undefined') {this.token = localStorage.getItem('hf_oauth_token');59 unmodified lines6061626364656667686970717273747576777879808182838485868759 unmodified linesreturn config;});// Add response interceptor to handle authentication errorsthis.client.interceptors.response.use((response) => response,(error) => {// Handle 401 errors (expired/invalid authentication)if (error.response && error.response.status === 401) {// Clear authentication dataif (typeof window !== 'undefined') {localStorage.removeItem('hf_oauth_token');localStorage.removeItem('hf_user_info');this.token = null;// Dispatch custom event to notify UI componentswindow.dispatchEvent(new CustomEvent('auth-expired', {detail: { message: 'Your session has expired. Please sign in again.' }}));}}return Promise.reject(error);});// Load token from localStorage on client sideif (typeof window !== 'undefined') {this.token = localStorage.getItem('hf_oauth_token');
177 unmodified lines178179180181182183177 unmodified linesreturn getStoredToken() !== null;}/*** Development mode login (mock authentication)*/177 unmodified lines178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223177 unmodified linesreturn getStoredToken() !== null;}/*** Validate authentication with backend* Returns true if authenticated, false if session expired*/export async function validateAuthentication(): Promise<boolean> {const token = getStoredToken();if (!token) {return false;}// Skip validation for dev mode tokensif (isDevelopment && token.startsWith('dev_token_')) {return true;}try {const response = await fetch(`${API_BASE}/auth/status`, {headers: {'Authorization': `Bearer ${token}`,},});if (response.status === 401) {// Session expired, clean uplogout();return false;}if (!response.ok) {return false;}const data = await response.json();return data.authenticated === true;} catch (error) {console.error('Failed to validate authentication:', error);return false;}}/*** Development mode login (mock authentication)*/
README.md+1
backend_api.py+134-3
frontend/src/app/page.tsx+19
frontend/src/lib/api.ts+22
frontend/src/lib/auth.ts+40