refactor: add AuthGuard component and fix API client empty response handling
- Add reusable AuthGuard component for protected routes - Move auth logic from index.tsx to (tabs)/_layout.tsx via AuthGuard - Fix ApiClient to handle empty responses (204 No Content) - Use useFocusEffect in chat.tsx to load messages after auth is ready - Extract getDateKey() helper function in calendar.tsx
This commit is contained in:
18
CLAUDE.md
18
CLAUDE.md
@@ -81,6 +81,7 @@ src/
|
||||
│ └── note/
|
||||
│ └── [id].tsx # Note editor for event (dynamic route)
|
||||
├── components/
|
||||
│ ├── AuthGuard.tsx # Auth wrapper: loads user, shows loading, redirects if unauthenticated
|
||||
│ ├── BaseBackground.tsx # Common screen wrapper (themed)
|
||||
│ ├── BaseButton.tsx # Reusable button component (themed, supports children)
|
||||
│ ├── Header.tsx # Header component (themed)
|
||||
@@ -97,7 +98,7 @@ src/
|
||||
│ └── logger.ts # react-native-logs config (apiLogger, storeLogger)
|
||||
├── services/
|
||||
│ ├── index.ts # Re-exports all services
|
||||
│ ├── ApiClient.ts # HTTP client with X-User-Id header injection, request logging
|
||||
│ ├── ApiClient.ts # HTTP client with X-User-Id header injection, request logging, handles empty responses (204)
|
||||
│ ├── AuthService.ts # login(), register(), logout() - calls API and updates AuthStore
|
||||
│ ├── EventService.ts # getAll(), getById(), getByDateRange(), create(), update(), delete()
|
||||
│ └── ChatService.ts # sendMessage(), confirmEvent(), rejectEvent(), getConversations(), getConversation()
|
||||
@@ -112,6 +113,13 @@ src/
|
||||
|
||||
**Routing:** Tab-based navigation with Chat, Calendar, and Settings as main screens. Auth screens (login, register) outside tabs. Dynamic routes for event detail and note editing.
|
||||
|
||||
**Authentication Flow:**
|
||||
- `AuthGuard` component wraps the tab layout in `(tabs)/_layout.tsx`
|
||||
- On app start, `AuthGuard` calls `loadStoredUser()` and shows loading indicator
|
||||
- If not authenticated, redirects to `/login`
|
||||
- `index.tsx` simply redirects to `/(tabs)/chat` - AuthGuard handles the rest
|
||||
- This pattern handles Expo Router's navigation state caching (avoids race conditions)
|
||||
|
||||
### Theme System
|
||||
|
||||
The app supports multiple themes (light/dark) via a reactive Zustand store.
|
||||
@@ -412,12 +420,14 @@ NODE_ENV=development # development = pretty logs, production = JSON
|
||||
- **Authentication fully implemented:**
|
||||
- `AuthStore`: Manages user state with expo-secure-store (native) / localStorage (web)
|
||||
- `AuthService`: login(), register(), logout() - calls backend API
|
||||
- `ApiClient`: Automatically injects X-User-Id header for authenticated requests
|
||||
- `ApiClient`: Automatically injects X-User-Id header for authenticated requests, handles empty responses (204)
|
||||
- `AuthGuard`: Reusable component that wraps protected routes - loads user, shows loading, redirects if unauthenticated
|
||||
- Login screen: Supports email OR userName login
|
||||
- Register screen: Email validation, checks for existing email/userName
|
||||
- `AuthButton`: Reusable button component with themed shadow
|
||||
- `Header`: Themed header component (logout moved to Settings)
|
||||
- `index.tsx`: Auth redirect - checks stored user on app start
|
||||
- `(tabs)/_layout.tsx`: Wraps tabs with AuthGuard for protected access
|
||||
- `index.tsx`: Simple redirect to chat (AuthGuard handles auth)
|
||||
- **Theme system fully implemented:**
|
||||
- `ThemeStore`: Zustand store with theme state and setTheme()
|
||||
- `Themes.tsx`: THEMES object with defaultLight/defaultDark variants
|
||||
@@ -438,7 +448,7 @@ NODE_ENV=development # development = pretty logs, production = JSON
|
||||
- Arrow navigation between proposals with "Event X von Y" counter
|
||||
- Each proposal individually confirmable/rejectable
|
||||
- **Typing indicator**: Animated dots (. .. ...) shown after 500ms delay while waiting for AI response
|
||||
- Messages persisted to database via ChatService and loaded on mount
|
||||
- Messages persisted to database via ChatService, loaded via `useFocusEffect` when screen gains focus
|
||||
- Tracks conversationId for message continuity across sessions
|
||||
- ChatStore with addMessages() for bulk loading, chatMessageToMessageData() helper
|
||||
- KeyboardAvoidingView for proper keyboard handling (iOS padding, Android height)
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { Tabs } from "expo-router";
|
||||
import { useThemeStore } from "../../stores/ThemeStore";
|
||||
import { AuthGuard } from "../../components/AuthGuard";
|
||||
|
||||
export default function TabLayout() {
|
||||
const { theme } = useThemeStore();
|
||||
return (
|
||||
<Tabs
|
||||
<AuthGuard>
|
||||
<Tabs
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
tabBarActiveTintColor: theme.chatBot,
|
||||
@@ -40,6 +42,7 @@ export default function TabLayout() {
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
</Tabs>
|
||||
</AuthGuard>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,14 @@ type MonthItem = {
|
||||
label: string; // e.g. "January 2024"
|
||||
};
|
||||
|
||||
/**
|
||||
* Formats a Date object to a string key in YYYY-MM-DD format.
|
||||
* Used for grouping and looking up events by date.
|
||||
*/
|
||||
const getDateKey = (date: Date): string => {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const generateMonths = (
|
||||
centerYear: number,
|
||||
centerMonth: number,
|
||||
@@ -108,7 +116,7 @@ const Calendar = () => {
|
||||
const map = new Map<string, ExpandedEvent[]>();
|
||||
events.forEach((e) => {
|
||||
const date = new Date(e.occurrenceStart);
|
||||
const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
const key = getDateKey(date);
|
||||
if (!map.has(key)) map.set(key, []);
|
||||
map.get(key)!.push(e);
|
||||
});
|
||||
@@ -157,7 +165,7 @@ const Calendar = () => {
|
||||
deleteEvent(event.id);
|
||||
// Close overlay if no more events for this date
|
||||
if (selectedDate) {
|
||||
const dateKey = `${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, "0")}-${String(selectedDate.getDate()).padStart(2, "0")}`;
|
||||
const dateKey = getDateKey(selectedDate);
|
||||
const remainingEvents = eventsByDate.get(dateKey) || [];
|
||||
if (remainingEvents.length <= 1) {
|
||||
setSelectedDate(null);
|
||||
@@ -175,7 +183,7 @@ const Calendar = () => {
|
||||
// Get events for selected date
|
||||
const selectedDateEvents = useMemo(() => {
|
||||
if (!selectedDate) return [];
|
||||
const key = `${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, "0")}-${String(selectedDate.getDate()).padStart(2, "0")}`;
|
||||
const key = getDateKey(selectedDate);
|
||||
return eventsByDate.get(key) || [];
|
||||
}, [selectedDate, eventsByDate]);
|
||||
|
||||
@@ -597,10 +605,6 @@ const CalendarGrid = (props: CalendarGridProps) => {
|
||||
return date;
|
||||
};
|
||||
|
||||
const getDateKey = (date: Date): string => {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<View
|
||||
className="h-full flex-1 flex-col flex-wrap gap-2 p-2"
|
||||
|
||||
@@ -8,13 +8,15 @@ import {
|
||||
Keyboard,
|
||||
} from "react-native";
|
||||
import { useThemeStore } from "../../stores/ThemeStore";
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import React, { useState, useRef, useEffect, useCallback } from "react";
|
||||
import { useFocusEffect } from "expo-router";
|
||||
import Header from "../../components/Header";
|
||||
import BaseBackground from "../../components/BaseBackground";
|
||||
import { FlashList } from "@shopify/flash-list";
|
||||
import { ChatService } from "../../services";
|
||||
import {
|
||||
useChatStore,
|
||||
useAuthStore,
|
||||
chatMessageToMessageData,
|
||||
MessageData,
|
||||
} from "../../stores";
|
||||
@@ -45,6 +47,7 @@ type ChatInputProps = {
|
||||
const TYPING_INDICATOR_DELAY_MS = 500;
|
||||
|
||||
const Chat = () => {
|
||||
const { isAuthenticated, isLoading: isAuthLoading } = useAuthStore();
|
||||
const {
|
||||
messages,
|
||||
addMessage,
|
||||
@@ -68,27 +71,31 @@ const Chat = () => {
|
||||
return () => keyboardDidShow.remove();
|
||||
}, []);
|
||||
|
||||
// Load existing messages from database on mount
|
||||
useEffect(() => {
|
||||
const fetchMessages = async () => {
|
||||
try {
|
||||
const conversationSummaries = await ChatService.getConversations();
|
||||
if (conversationSummaries.length > 0) {
|
||||
const conversationId = conversationSummaries[0].id;
|
||||
setCurrentConversationId(conversationId);
|
||||
// Load existing messages from database once authenticated and screen is focused
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (isAuthLoading || !isAuthenticated) return;
|
||||
|
||||
const serverMessages =
|
||||
await ChatService.getConversation(conversationId);
|
||||
const clientMessages = serverMessages.map(chatMessageToMessageData);
|
||||
addMessages(clientMessages);
|
||||
scrollToEnd();
|
||||
const fetchMessages = async () => {
|
||||
try {
|
||||
const conversationSummaries = await ChatService.getConversations();
|
||||
if (conversationSummaries.length > 0) {
|
||||
const conversationId = conversationSummaries[0].id;
|
||||
setCurrentConversationId(conversationId);
|
||||
|
||||
const serverMessages =
|
||||
await ChatService.getConversation(conversationId);
|
||||
const clientMessages = serverMessages.map(chatMessageToMessageData);
|
||||
addMessages(clientMessages);
|
||||
scrollToEnd();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load messages:", error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load messages:", error);
|
||||
}
|
||||
};
|
||||
fetchMessages();
|
||||
}, []);
|
||||
};
|
||||
fetchMessages();
|
||||
}, [isAuthLoading, isAuthenticated]),
|
||||
);
|
||||
|
||||
const scrollToEnd = () => {
|
||||
setTimeout(() => {
|
||||
@@ -283,6 +290,7 @@ const ChatInput = ({ onSend }: ChatInputProps) => {
|
||||
className="flex-1 border border-solid rounded-2xl px-3 py-2 mr-2"
|
||||
style={{
|
||||
backgroundColor: theme.messageBorderBg,
|
||||
color: theme.textPrimary,
|
||||
minHeight: MIN_INPUT_HEIGHT,
|
||||
maxHeight: MAX_INPUT_HEIGHT,
|
||||
textAlignVertical: "top",
|
||||
|
||||
@@ -1,35 +1,6 @@
|
||||
import { useEffect } from "react";
|
||||
import { View, ActivityIndicator } from "react-native";
|
||||
import { Redirect } from "expo-router";
|
||||
import { useAuthStore } from "../stores";
|
||||
import { useThemeStore } from "../stores/ThemeStore";
|
||||
|
||||
export default function Index() {
|
||||
const { isAuthenticated, isLoading, loadStoredUser } = useAuthStore();
|
||||
const { theme } = useThemeStore();
|
||||
|
||||
useEffect(() => {
|
||||
loadStoredUser();
|
||||
}, [loadStoredUser]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
backgroundColor: theme.primeBg,
|
||||
}}
|
||||
>
|
||||
<ActivityIndicator size="large" color={theme.chatBot} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (isAuthenticated) {
|
||||
return <Redirect href="/(tabs)/chat" />;
|
||||
}
|
||||
|
||||
return <Redirect href="/login" />;
|
||||
// AuthGuard in (tabs)/_layout.tsx handles authentication
|
||||
return <Redirect href="/(tabs)/chat" />;
|
||||
}
|
||||
|
||||
46
apps/client/src/components/AuthGuard.tsx
Normal file
46
apps/client/src/components/AuthGuard.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useEffect, ReactNode } from "react";
|
||||
import { View, ActivityIndicator } from "react-native";
|
||||
import { Redirect } from "expo-router";
|
||||
import { useAuthStore } from "../stores";
|
||||
import { useThemeStore } from "../stores/ThemeStore";
|
||||
|
||||
type AuthGuardProps = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps content that requires authentication.
|
||||
* - Loads stored user on mount
|
||||
* - Shows loading indicator while checking auth state
|
||||
* - Redirects to login if not authenticated
|
||||
* - Renders children if authenticated
|
||||
*/
|
||||
export const AuthGuard = ({ children }: AuthGuardProps) => {
|
||||
const { theme } = useThemeStore();
|
||||
const { isAuthenticated, isLoading, loadStoredUser } = useAuthStore();
|
||||
|
||||
useEffect(() => {
|
||||
loadStoredUser();
|
||||
}, [loadStoredUser]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
backgroundColor: theme.primeBg,
|
||||
}}
|
||||
>
|
||||
<ActivityIndicator size="large" color={theme.chatBot} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Redirect href="/login" />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
@@ -55,7 +55,12 @@ async function request<T>(
|
||||
}
|
||||
|
||||
apiLogger.debug(`${method} ${endpoint} - ${response.status} (${duration}ms)`);
|
||||
return response.json();
|
||||
|
||||
const text = await response.text();
|
||||
if (!text) {
|
||||
return undefined as T;
|
||||
}
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
const duration = Math.round(performance.now() - start);
|
||||
apiLogger.error(`${method} ${endpoint} failed (${duration}ms): ${error}`);
|
||||
|
||||
Reference in New Issue
Block a user