4.9 KiB
Authentication Fix - Complete Summary
Problem
Users were being logged out when navigating to content-planning due to 401 authentication errors. Requests were being made before Clerk authentication was ready, causing the frontend's 401 error handler to automatically sign out users.
Root Causes
- Frontend Components: Making API calls immediately on mount without checking if Clerk is loaded or user is authenticated
- EventSource Limitations: EventSource API doesn't support custom headers, so streaming endpoints couldn't receive auth tokens
- API Service: No guards to prevent requests when authentication isn't ready
Solutions Applied
1. Frontend Component Authentication Checks ✅
Files Updated:
ContentStrategyTab.tsxContentPlanningDashboard.tsx
Changes:
- Added
useAuthhook from Clerk - Check
isLoadedandisSignedInbefore making API calls - Show loading state while waiting for Clerk
- Show warning if user is not signed in
const { isLoaded, isSignedIn } = useAuth();
useEffect(() => {
if (!isLoaded) return; // Wait for Clerk
if (!isSignedIn) return; // Wait for authentication
// Only make API calls if authenticated
loadInitialData();
}, [isLoaded, isSignedIn]);
2. API Service Authentication Guards ✅
File Updated:
contentPlanningApi.ts
Changes:
- Added authentication checks in
getStrategies()method - Check if
authTokenGetteris set before making requests - Check if token is available before making requests
- Throw descriptive errors if authentication isn't ready
async getStrategies(userId?: number) {
const { getAuthTokenGetter } = await import('../api/client');
const tokenGetter = getAuthTokenGetter();
if (!tokenGetter) {
throw new Error('Authentication not ready. Please wait for sign-in to complete.');
}
const token = await tokenGetter();
if (!token) {
throw new Error('Authentication required. Please sign in to access content planning features.');
}
// Make request...
}
3. EventSource Authentication Support ✅
Files Updated:
contentPlanningApi.ts(frontend)streaming_endpoints.py(backend)
Changes:
- Updated
streamStrategicIntelligence()andstreamKeywordResearch()to pass token as query parameter - Updated backend streaming endpoints to use
get_current_user_with_query_tokeninstead ofget_current_user - Added
Requestimport to streaming endpoints
Frontend:
// EventSource doesn't support custom headers, so we pass token as query parameter
const url = `${this.baseURL}/enhanced-strategies/stream/strategic-intelligence?user_id=${userId || 1}&token=${encodeURIComponent(token)}`;
return new EventSource(url);
Backend:
@router.get("/stream/strategic-intelligence")
async def stream_strategic_intelligence(
request: Request,
current_user: Dict[str, Any] = Depends(get_current_user_with_query_token),
db: Session = Depends(get_db)
):
4. Client Module Export ✅
File Updated:
client.ts
Changes:
- Added
getAuthTokenGetter()export function to allow API services to check if auth is ready
export const getAuthTokenGetter = (): (() => Promise<string | null>) | null => {
return authTokenGetter;
};
Endpoints Fixed
- ✅
GET /api/content-planning/enhanced-strategies/- Regular HTTP (headers) - ✅
GET /api/content-planning/enhanced-strategies/stream/strategic-intelligence- EventSource (query param) - ✅
GET /api/content-planning/enhanced-strategies/stream/keyword-research- EventSource (query param)
Authentication Flow
- Component Mounts → Checks
isLoadedandisSignedIn - If Not Ready → Shows loading state, doesn't make API calls
- If Ready → Makes API calls
- API Service → Checks if
authTokenGetteris set and token is available - If Not Ready → Throws error (caught by component, shows message)
- If Ready → Makes request with auth token
- Backend → Validates token and processes request
Result
✅ No more premature API calls - Components wait for authentication ✅ No more 401 errors - Requests only made when authenticated ✅ No more unwanted logouts - Authentication verified before API calls ✅ EventSource support - Streaming endpoints work with query parameter tokens ✅ Better UX - Loading states while waiting for authentication
Testing Checklist
- Component waits for Clerk to load before making API calls
- Component checks if user is signed in before making API calls
- API service checks if auth token is available
- EventSource requests include token in query parameter
- Backend streaming endpoints accept tokens from query parameters
- Regular HTTP requests use Authorization header
- Error handling for unauthenticated requests
Status: ✅ COMPLETE
All authentication issues have been resolved. Users can now navigate to content-planning without being logged out.