Files
maternal-app/maternal-web/lib/api/client.ts
Andrei 34b8466004
Some checks failed
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled
fix: Critical bug fixes for AI chat and children authorization
## AI Chat Fixes
- **CRITICAL**: Fixed AI chat responding only with sleep-related info
  - Root cause: Current user message was never added to context before sending to AI
  - Added user message to context in ai.service.ts before API call
  - Fixed conversation ID handling for new conversations (undefined check)
  - Fixed children query to properly use FamilyMember join instead of incorrect familyId lookup
  - Added FamilyMember entity to AI module imports

- **Context improvements**:
  - New conversations now use empty history array (not the current message)
  - Properly query user's children across all their families via family membership

## Children Authorization Fix
- **CRITICAL SECURITY**: Fixed authorization bug where all users could see all children
  - Root cause: Controllers used `user.sub` but JWT strategy returns `user.userId`
  - Changed all children controller methods to use `user.userId` instead of `user.sub`
  - Added comprehensive logging to track userId and returned children
  - Backend now correctly filters children by family membership

## WebSocket Authentication
- **Enhanced error handling** in families gateway
  - Better error messages for connection failures
  - Added debug logging for token validation
  - More descriptive error emissions to client
  - Added userId fallback (checks both payload.userId and payload.sub)

## User Experience
- **Auto-clear cache on logout**:
  - Logout now clears localStorage and sessionStorage
  - Prevents stale cached data from persisting across sessions
  - Users get fresh data on every login without manual cache clearing

## Testing
- Backend correctly returns only user's own children (verified in logs)
- AI chat now responds to all types of questions, not just sleep-related
- WebSocket authentication provides clearer error feedback

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-06 10:55:25 +00:00

133 lines
4.5 KiB
TypeScript

import axios from 'axios';
import { tokenStorage } from '@/lib/utils/tokenStorage';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
export const apiClient = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
// Request interceptor to add auth token
apiClient.interceptors.request.use(
(config) => {
const token = tokenStorage.getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor to handle token refresh
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
// Only handle token refresh on client side
if (typeof window === 'undefined') {
return Promise.reject(error);
}
// If error is 401 and we haven't tried to refresh yet
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const refreshToken = tokenStorage.getRefreshToken();
const deviceId = tokenStorage.getDeviceId();
console.log('[API Client] Attempting token refresh, refreshToken exists:', !!refreshToken, 'deviceId exists:', !!deviceId);
if (!refreshToken) {
console.error('[API Client] No refresh token found in storage');
throw new Error('No refresh token');
}
// Use a plain axios instance without interceptors to avoid loops
const refreshPayload: { refreshToken: string; deviceId?: string } = {
refreshToken,
};
if (deviceId) {
refreshPayload.deviceId = deviceId;
}
const refreshResponse = await axios.create().post(
`${API_BASE_URL}/api/v1/auth/refresh`,
refreshPayload,
{
headers: { 'Content-Type': 'application/json' },
withCredentials: true
}
);
const response = refreshResponse;
// Handle different response structures
let newAccessToken;
let newRefreshToken;
if (response.data?.data?.tokens?.accessToken) {
newAccessToken = response.data.data.tokens.accessToken;
newRefreshToken = response.data.data.tokens.refreshToken;
} else if (response.data?.tokens?.accessToken) {
newAccessToken = response.data.tokens.accessToken;
newRefreshToken = response.data.tokens.refreshToken;
} else if (response.data?.accessToken) {
newAccessToken = response.data.accessToken;
newRefreshToken = response.data.refreshToken;
} else {
throw new Error('Invalid token refresh response');
}
// Update tokens in storage
tokenStorage.setAccessToken(newAccessToken);
if (newRefreshToken) {
tokenStorage.setRefreshToken(newRefreshToken);
}
// Retry original request with new token
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return apiClient(originalRequest);
} catch (refreshError: any) {
console.error('[API Client] Token refresh failed:', refreshError);
// Only clear tokens if this is a real auth failure (not a network error)
// and not during the initial page load where React Strict Mode might cause issues
const isAuthFailure = refreshError?.response?.status === 401 ||
refreshError?.response?.status === 403;
// Check if this is likely a React Strict Mode double-invocation
// by seeing if we're in development mode and the error happened very quickly
const isDevelopment = process.env.NODE_ENV === 'development';
if (isAuthFailure && !isDevelopment) {
console.log('[API Client] Auth failure in production, clearing tokens');
tokenStorage.clearTokens();
} else if (isDevelopment) {
console.log('[API Client] Development mode - not clearing tokens to avoid React Strict Mode issues');
}
// Avoid redirect loop - only redirect if not already on login page
// and only in production or after a real auth failure
if (!window.location.pathname.includes('/login') && isAuthFailure && !isDevelopment) {
window.location.href = '/login';
}
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
export default apiClient;