fix: Critical bug fixes for AI chat and children authorization
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

## 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>
This commit is contained in:
2025-10-06 10:55:25 +00:00
parent 5c255298d4
commit 34b8466004
18 changed files with 21557 additions and 51 deletions

View File

@@ -51,18 +51,18 @@ apiClient.interceptors.response.use(
throw new Error('No refresh token');
}
if (!deviceId) {
console.error('[API Client] No device ID found in storage');
throw new Error('No device ID');
// Use a plain axios instance without interceptors to avoid loops
const refreshPayload: { refreshToken: string; deviceId?: string } = {
refreshToken,
};
if (deviceId) {
refreshPayload.deviceId = deviceId;
}
// Use a plain axios instance without interceptors to avoid loops
const refreshResponse = await axios.create().post(
`${API_BASE_URL}/api/v1/auth/refresh`,
{
refreshToken,
deviceId
},
refreshPayload,
{
headers: { 'Content-Type': 'application/json' },
withCredentials: true

View File

@@ -293,6 +293,15 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
tokenStorage.clearTokens();
setUser(null);
setToken(null);
// Clear all localStorage and sessionStorage to remove cached data
// This ensures a fresh start on next login
if (typeof window !== 'undefined') {
localStorage.clear();
sessionStorage.clear();
console.log('[AuthContext] Cleared all browser storage on logout');
}
router.push('/login');
}
};