- App now prompts for backend URL on first launch - Stores in SecureStore for persistence - Default: http://localhost:3001 - Can be changed in app settings - Backend setup screen at /app/(auth)/backend-setup.tsx
71 lines
2 KiB
TypeScript
71 lines
2 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { Stack } from 'expo-router';
|
|
import { useAuthStore } from '@/store/auth';
|
|
import { useWebSocket } from '@/hooks/useWebSocket';
|
|
import { authClient } from '@/lib/auth-client';
|
|
import { getBackendUrl } from '@/lib/api';
|
|
|
|
/**
|
|
* Root layout with auth guard
|
|
* Routes to backend-setup if not configured, then to auth stack or app stack
|
|
*/
|
|
export default function RootLayout() {
|
|
const { user, setUser, setIsLoading } = useAuthStore();
|
|
const [backendConfigured, setBackendConfigured] = useState(false);
|
|
const [checked, setChecked] = useState(false);
|
|
|
|
// Initialize WebSocket connection when authenticated
|
|
useWebSocket();
|
|
|
|
useEffect(() => {
|
|
// Check if user is already authenticated
|
|
async function checkAuth() {
|
|
try {
|
|
setIsLoading(true);
|
|
const response = await authClient.getSession();
|
|
const sessionData = (response as any)?.data;
|
|
if (sessionData && (sessionData.user || sessionData.data?.user)) {
|
|
const user = sessionData.user || sessionData.data?.user;
|
|
setUser(user);
|
|
}
|
|
} catch (error) {
|
|
console.error('Auth check failed:', error);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
}
|
|
|
|
// Check if backend URL is configured
|
|
async function checkBackend() {
|
|
const url = await getBackendUrl();
|
|
setBackendConfigured(!!url);
|
|
setChecked(true);
|
|
}
|
|
|
|
checkBackend();
|
|
checkAuth();
|
|
}, [setUser, setIsLoading]);
|
|
|
|
if (!checked) {
|
|
return null; // Or a loading screen
|
|
}
|
|
|
|
return (
|
|
<Stack
|
|
screenOptions={{
|
|
headerShown: false,
|
|
}}
|
|
>
|
|
{!backendConfigured ? (
|
|
// Backend not configured - show setup first
|
|
<Stack.Screen name="(auth)/backend-setup" />
|
|
) : user ? (
|
|
// User is authenticated - show app stack
|
|
<Stack.Screen name="(app)" />
|
|
) : (
|
|
// User is not authenticated - show auth stack
|
|
<Stack.Screen name="(auth)" />
|
|
)}
|
|
</Stack>
|
|
);
|
|
}
|