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:
2026-01-25 13:03:17 +01:00
parent 43d40b46d7
commit a42e2a7c1c
7 changed files with 112 additions and 65 deletions

View File

@@ -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>
);
}

View File

@@ -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"

View File

@@ -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",

View File

@@ -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" />;
}

View 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}</>;
};

View File

@@ -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}`);