fix oauth issue
Browse filesFiles changed (5)
7 unmodified lines8910111213147 unmodified linespinned: falsedisable_embedding: falsehf_oauth: truehf_oauth_expiration_minutes: 43200hf_oauth_scopes: - manage-repos---7 unmodified lines89101111121314125 unmodified lines140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185179 unmodified lines3653663673683693703713723733743753763773783793803813827 unmodified lines3903913923933943953963973983994004014024034044054064074084094101 unmodified line4124134144154164174184194204214224234244254264274284294302 unmodified lines4334344353624364374383644394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025037 unmodified linesfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetimefrom 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 hours timestamp = 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 hour expired_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 lines userinfo_response.raise_for_status() user_info = userinfo_response.json() # Calculate token expiration # OAuth tokens typically have expires_in in seconds expires_in = token_data.get("expires_in", 28800) # Default 8 hours expires_at = datetime.now() + timedelta(seconds=expires_in) # Create session session_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 lines raise 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 == 200 except 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 line raise HTTPException(status_code=401, detail="Invalid session") session_data = user_sessions[session] # Check if session has expired if is_session_expired(session_data): # Clean up expired session user_sessions.pop(session, None) raise HTTPException(status_code=401, detail="Session expired. Please sign in again.") # Validate token with HuggingFace if not await validate_token_with_hf(session_data["access_token"]): # Token is invalid, clean up session user_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""" """Check authentication status and validate token""" auth = get_auth_from_header(authorization) if auth.is_authenticated(): if not auth.is_authenticated(): return AuthStatus( authenticated=False, username=None, message="Not authenticated" ) # For dev tokens, skip validation if 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 validate token = authorization.replace("Bearer ", "") if authorization else None if token and "-" in token and len(token) > 20 and token in user_sessions: session_data = user_sessions[token] # Check if session has expired if is_session_expired(session_data): # Clean up expired session user_sessions.pop(token, None) return AuthStatus( authenticated=False, username=None, message="Session expired" ) # Validate token with HuggingFace if not await validate_token_with_hf(session_data["access_token"]): # Token is invalid, clean up session user_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 HF if 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 lines959697989910010110210310410510610710810911011111211311411511611711811994 unmodified lines return () => window.removeEventListener('storage', handleStorageChange); }, []);
// Listen for authentication expiration events useEffect(() => { const handleAuthExpired = (e: CustomEvent) => { console.log('[Auth] Session expired:', e.detail?.message); // Clear authentication state setIsAuthenticated(false); setUsername(null); apiClient.setToken(null); // Show alert to user if (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 token useEffect(() => {59 unmodified lines6061626364656667686970717273747576777879808182838485868759 unmodified lines return config; });
// Add response interceptor to handle authentication errors this.client.interceptors.response.use( (response) => response, (error) => { // Handle 401 errors (expired/invalid authentication) if (error.response && error.response.status === 401) { // Clear authentication data if (typeof window !== 'undefined') { localStorage.removeItem('hf_oauth_token'); localStorage.removeItem('hf_user_info'); this.token = null; // Dispatch custom event to notify UI components window.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 side if (typeof window !== 'undefined') { this.token = localStorage.getItem('hf_oauth_token');177 unmodified lines178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223177 unmodified lines return 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 tokens if (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 up logout(); 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