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/
|
│ └── note/
|
||||||
│ └── [id].tsx # Note editor for event (dynamic route)
|
│ └── [id].tsx # Note editor for event (dynamic route)
|
||||||
├── components/
|
├── components/
|
||||||
|
│ ├── AuthGuard.tsx # Auth wrapper: loads user, shows loading, redirects if unauthenticated
|
||||||
│ ├── BaseBackground.tsx # Common screen wrapper (themed)
|
│ ├── BaseBackground.tsx # Common screen wrapper (themed)
|
||||||
│ ├── BaseButton.tsx # Reusable button component (themed, supports children)
|
│ ├── BaseButton.tsx # Reusable button component (themed, supports children)
|
||||||
│ ├── Header.tsx # Header component (themed)
|
│ ├── Header.tsx # Header component (themed)
|
||||||
@@ -97,7 +98,7 @@ src/
|
|||||||
│ └── logger.ts # react-native-logs config (apiLogger, storeLogger)
|
│ └── logger.ts # react-native-logs config (apiLogger, storeLogger)
|
||||||
├── services/
|
├── services/
|
||||||
│ ├── index.ts # Re-exports all 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
|
│ ├── AuthService.ts # login(), register(), logout() - calls API and updates AuthStore
|
||||||
│ ├── EventService.ts # getAll(), getById(), getByDateRange(), create(), update(), delete()
|
│ ├── EventService.ts # getAll(), getById(), getByDateRange(), create(), update(), delete()
|
||||||
│ └── ChatService.ts # sendMessage(), confirmEvent(), rejectEvent(), getConversations(), getConversation()
|
│ └── 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.
|
**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
|
### Theme System
|
||||||
|
|
||||||
The app supports multiple themes (light/dark) via a reactive Zustand store.
|
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:**
|
- **Authentication fully implemented:**
|
||||||
- `AuthStore`: Manages user state with expo-secure-store (native) / localStorage (web)
|
- `AuthStore`: Manages user state with expo-secure-store (native) / localStorage (web)
|
||||||
- `AuthService`: login(), register(), logout() - calls backend API
|
- `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
|
- Login screen: Supports email OR userName login
|
||||||
- Register screen: Email validation, checks for existing email/userName
|
- Register screen: Email validation, checks for existing email/userName
|
||||||
- `AuthButton`: Reusable button component with themed shadow
|
- `AuthButton`: Reusable button component with themed shadow
|
||||||
- `Header`: Themed header component (logout moved to Settings)
|
- `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:**
|
- **Theme system fully implemented:**
|
||||||
- `ThemeStore`: Zustand store with theme state and setTheme()
|
- `ThemeStore`: Zustand store with theme state and setTheme()
|
||||||
- `Themes.tsx`: THEMES object with defaultLight/defaultDark variants
|
- `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
|
- Arrow navigation between proposals with "Event X von Y" counter
|
||||||
- Each proposal individually confirmable/rejectable
|
- Each proposal individually confirmable/rejectable
|
||||||
- **Typing indicator**: Animated dots (. .. ...) shown after 500ms delay while waiting for AI response
|
- **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
|
- Tracks conversationId for message continuity across sessions
|
||||||
- ChatStore with addMessages() for bulk loading, chatMessageToMessageData() helper
|
- ChatStore with addMessages() for bulk loading, chatMessageToMessageData() helper
|
||||||
- KeyboardAvoidingView for proper keyboard handling (iOS padding, Android height)
|
- KeyboardAvoidingView for proper keyboard handling (iOS padding, Android height)
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { Ionicons } from "@expo/vector-icons";
|
import { Ionicons } from "@expo/vector-icons";
|
||||||
import { Tabs } from "expo-router";
|
import { Tabs } from "expo-router";
|
||||||
import { useThemeStore } from "../../stores/ThemeStore";
|
import { useThemeStore } from "../../stores/ThemeStore";
|
||||||
|
import { AuthGuard } from "../../components/AuthGuard";
|
||||||
|
|
||||||
export default function TabLayout() {
|
export default function TabLayout() {
|
||||||
const { theme } = useThemeStore();
|
const { theme } = useThemeStore();
|
||||||
return (
|
return (
|
||||||
|
<AuthGuard>
|
||||||
<Tabs
|
<Tabs
|
||||||
screenOptions={{
|
screenOptions={{
|
||||||
headerShown: false,
|
headerShown: false,
|
||||||
@@ -41,5 +43,6 @@ export default function TabLayout() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
</AuthGuard>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,14 @@ type MonthItem = {
|
|||||||
label: string; // e.g. "January 2024"
|
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 = (
|
const generateMonths = (
|
||||||
centerYear: number,
|
centerYear: number,
|
||||||
centerMonth: number,
|
centerMonth: number,
|
||||||
@@ -108,7 +116,7 @@ const Calendar = () => {
|
|||||||
const map = new Map<string, ExpandedEvent[]>();
|
const map = new Map<string, ExpandedEvent[]>();
|
||||||
events.forEach((e) => {
|
events.forEach((e) => {
|
||||||
const date = new Date(e.occurrenceStart);
|
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, []);
|
if (!map.has(key)) map.set(key, []);
|
||||||
map.get(key)!.push(e);
|
map.get(key)!.push(e);
|
||||||
});
|
});
|
||||||
@@ -157,7 +165,7 @@ const Calendar = () => {
|
|||||||
deleteEvent(event.id);
|
deleteEvent(event.id);
|
||||||
// Close overlay if no more events for this date
|
// Close overlay if no more events for this date
|
||||||
if (selectedDate) {
|
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) || [];
|
const remainingEvents = eventsByDate.get(dateKey) || [];
|
||||||
if (remainingEvents.length <= 1) {
|
if (remainingEvents.length <= 1) {
|
||||||
setSelectedDate(null);
|
setSelectedDate(null);
|
||||||
@@ -175,7 +183,7 @@ const Calendar = () => {
|
|||||||
// Get events for selected date
|
// Get events for selected date
|
||||||
const selectedDateEvents = useMemo(() => {
|
const selectedDateEvents = useMemo(() => {
|
||||||
if (!selectedDate) return [];
|
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) || [];
|
return eventsByDate.get(key) || [];
|
||||||
}, [selectedDate, eventsByDate]);
|
}, [selectedDate, eventsByDate]);
|
||||||
|
|
||||||
@@ -597,10 +605,6 @@ const CalendarGrid = (props: CalendarGridProps) => {
|
|||||||
return date;
|
return date;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getDateKey = (date: Date): string => {
|
|
||||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
className="h-full flex-1 flex-col flex-wrap gap-2 p-2"
|
className="h-full flex-1 flex-col flex-wrap gap-2 p-2"
|
||||||
|
|||||||
@@ -8,13 +8,15 @@ import {
|
|||||||
Keyboard,
|
Keyboard,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { useThemeStore } from "../../stores/ThemeStore";
|
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 Header from "../../components/Header";
|
||||||
import BaseBackground from "../../components/BaseBackground";
|
import BaseBackground from "../../components/BaseBackground";
|
||||||
import { FlashList } from "@shopify/flash-list";
|
import { FlashList } from "@shopify/flash-list";
|
||||||
import { ChatService } from "../../services";
|
import { ChatService } from "../../services";
|
||||||
import {
|
import {
|
||||||
useChatStore,
|
useChatStore,
|
||||||
|
useAuthStore,
|
||||||
chatMessageToMessageData,
|
chatMessageToMessageData,
|
||||||
MessageData,
|
MessageData,
|
||||||
} from "../../stores";
|
} from "../../stores";
|
||||||
@@ -45,6 +47,7 @@ type ChatInputProps = {
|
|||||||
const TYPING_INDICATOR_DELAY_MS = 500;
|
const TYPING_INDICATOR_DELAY_MS = 500;
|
||||||
|
|
||||||
const Chat = () => {
|
const Chat = () => {
|
||||||
|
const { isAuthenticated, isLoading: isAuthLoading } = useAuthStore();
|
||||||
const {
|
const {
|
||||||
messages,
|
messages,
|
||||||
addMessage,
|
addMessage,
|
||||||
@@ -68,8 +71,11 @@ const Chat = () => {
|
|||||||
return () => keyboardDidShow.remove();
|
return () => keyboardDidShow.remove();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Load existing messages from database on mount
|
// Load existing messages from database once authenticated and screen is focused
|
||||||
useEffect(() => {
|
useFocusEffect(
|
||||||
|
useCallback(() => {
|
||||||
|
if (isAuthLoading || !isAuthenticated) return;
|
||||||
|
|
||||||
const fetchMessages = async () => {
|
const fetchMessages = async () => {
|
||||||
try {
|
try {
|
||||||
const conversationSummaries = await ChatService.getConversations();
|
const conversationSummaries = await ChatService.getConversations();
|
||||||
@@ -88,7 +94,8 @@ const Chat = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
fetchMessages();
|
fetchMessages();
|
||||||
}, []);
|
}, [isAuthLoading, isAuthenticated]),
|
||||||
|
);
|
||||||
|
|
||||||
const scrollToEnd = () => {
|
const scrollToEnd = () => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -283,6 +290,7 @@ const ChatInput = ({ onSend }: ChatInputProps) => {
|
|||||||
className="flex-1 border border-solid rounded-2xl px-3 py-2 mr-2"
|
className="flex-1 border border-solid rounded-2xl px-3 py-2 mr-2"
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: theme.messageBorderBg,
|
backgroundColor: theme.messageBorderBg,
|
||||||
|
color: theme.textPrimary,
|
||||||
minHeight: MIN_INPUT_HEIGHT,
|
minHeight: MIN_INPUT_HEIGHT,
|
||||||
maxHeight: MAX_INPUT_HEIGHT,
|
maxHeight: MAX_INPUT_HEIGHT,
|
||||||
textAlignVertical: "top",
|
textAlignVertical: "top",
|
||||||
|
|||||||
@@ -1,35 +1,6 @@
|
|||||||
import { useEffect } from "react";
|
|
||||||
import { View, ActivityIndicator } from "react-native";
|
|
||||||
import { Redirect } from "expo-router";
|
import { Redirect } from "expo-router";
|
||||||
import { useAuthStore } from "../stores";
|
|
||||||
import { useThemeStore } from "../stores/ThemeStore";
|
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
const { isAuthenticated, isLoading, loadStoredUser } = useAuthStore();
|
// AuthGuard in (tabs)/_layout.tsx handles authentication
|
||||||
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="/(tabs)/chat" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <Redirect href="/login" />;
|
|
||||||
}
|
|
||||||
|
|||||||
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)`);
|
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) {
|
} catch (error) {
|
||||||
const duration = Math.round(performance.now() - start);
|
const duration = Math.round(performance.now() - start);
|
||||||
apiLogger.error(`${method} ${endpoint} failed (${duration}ms): ${error}`);
|
apiLogger.error(`${method} ${endpoint} failed (${duration}ms): ${error}`);
|
||||||
|
|||||||
Reference in New Issue
Block a user