Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cc27c00991 | |||
| 2ab097ec8a |
+34
-3
@@ -7,7 +7,7 @@ import { InviteGateScreen } from '@/components/game/InviteGateScreen';
|
||||
import { useGameLoop } from '@/hooks/useGameLoop';
|
||||
import { useAuthGate } from '@/hooks/useAuthGate';
|
||||
import { TICK_INTERVAL_MS } from '@ai-tycoon/shared';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import { Sparkles, RefreshCw, WifiOff } from 'lucide-react';
|
||||
|
||||
function LoadingScreen() {
|
||||
return (
|
||||
@@ -25,8 +25,35 @@ function LoadingScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function BackendErrorScreen({ error, onRetry }: { error: string; onRetry: () => void }) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-surface-950 to-surface-900">
|
||||
<div className="max-w-md w-full mx-4 text-center">
|
||||
<div className="inline-flex items-center gap-2 mb-6">
|
||||
<Sparkles className="text-accent-light" size={32} />
|
||||
<h1 className="text-4xl font-bold bg-gradient-to-r from-accent-light to-accent bg-clip-text text-transparent">
|
||||
AI Tycoon
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-900 border border-surface-700 rounded-xl p-6 space-y-4">
|
||||
<WifiOff className="mx-auto text-danger" size={40} />
|
||||
<h2 className="text-lg font-semibold text-surface-100">Cannot Connect to Server</h2>
|
||||
<p className="text-sm text-surface-400">{error}</p>
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-accent hover:bg-accent-dark text-white font-medium text-sm transition-colors"
|
||||
>
|
||||
<RefreshCw size={16} /> Retry
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const { loading: authLoading, needsInvite, needsPasswordReset, setRegistered, setNeedsPasswordReset } = useAuthGate();
|
||||
const { loading: authLoading, backendError, needsInvite, needsPasswordReset, setRegistered, setNeedsPasswordReset, retry } = useAuthGate();
|
||||
const companyName = useGameStore((s) => s.meta.companyName);
|
||||
const lastTickTimestamp = useGameStore((s) => s.meta.lastTickTimestamp);
|
||||
const [catchUpTicks, setCatchUpTicks] = useState<number | null>(null);
|
||||
@@ -43,12 +70,16 @@ export function App() {
|
||||
}
|
||||
}, [companyName, lastTickTimestamp, catchUpDone]);
|
||||
|
||||
useGameLoop(!catchUpDone || authLoading || needsInvite || needsPasswordReset);
|
||||
useGameLoop(!catchUpDone || authLoading || !!backendError || needsInvite || needsPasswordReset);
|
||||
|
||||
if (authLoading) {
|
||||
return <LoadingScreen />;
|
||||
}
|
||||
|
||||
if (backendError) {
|
||||
return <BackendErrorScreen error={backendError} onRetry={retry} />;
|
||||
}
|
||||
|
||||
if (needsInvite || needsPasswordReset) {
|
||||
return (
|
||||
<InviteGateScreen
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { api, getTokenPayload, isRegistered as checkRegistered, needsPasswordReset as checkNeedsReset, setAuthToken } from '@/lib/api';
|
||||
import { useState, useCallback } from 'react';
|
||||
import { api, getTokenPayload, isRegistered as checkRegistered, needsPasswordReset as checkNeedsReset, validateStoredToken } from '@/lib/api';
|
||||
import { ensureAuth } from './useCloudSave';
|
||||
|
||||
interface AuthGateState {
|
||||
loading: boolean;
|
||||
backendError: string | null;
|
||||
needsInvite: boolean;
|
||||
needsPasswordReset: boolean;
|
||||
registered: boolean;
|
||||
@@ -11,46 +12,60 @@ interface AuthGateState {
|
||||
config: { requireInvite: boolean; userInvitations: number } | null;
|
||||
setRegistered: (value: boolean) => void;
|
||||
setNeedsPasswordReset: (value: boolean) => void;
|
||||
retry: () => void;
|
||||
}
|
||||
|
||||
export function useAuthGate(): AuthGateState {
|
||||
const [config, setConfig] = useState<{ requireInvite: boolean; userInvitations: number } | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [backendError, setBackendError] = useState<string | null>(null);
|
||||
const [registered, setRegistered] = useState(false);
|
||||
const [passwordReset, setPasswordReset] = useState(false);
|
||||
const [admin, setAdmin] = useState(false);
|
||||
const [initCount, setInitCount] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const init = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setBackendError(null);
|
||||
|
||||
validateStoredToken();
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
const [cfg] = await Promise.all([
|
||||
api.config.get(),
|
||||
ensureAuth(),
|
||||
]);
|
||||
|
||||
if (cancelled) return;
|
||||
await api.health();
|
||||
} catch (e) {
|
||||
setBackendError(e instanceof Error ? e.message : 'Cannot connect to server');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const cfg = await api.config.get();
|
||||
setConfig(cfg);
|
||||
} catch {
|
||||
setConfig({ requireInvite: false, userInvitations: 0 });
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureAuth();
|
||||
} catch {
|
||||
// auth failed — will show as unregistered
|
||||
}
|
||||
|
||||
const payload = getTokenPayload();
|
||||
const reg = checkRegistered();
|
||||
setRegistered(reg);
|
||||
setRegistered(checkRegistered());
|
||||
setPasswordReset(checkNeedsReset());
|
||||
setAdmin(payload?.role === 'admin');
|
||||
} catch {
|
||||
// Config fetch failed — allow game to load (fail open)
|
||||
setConfig({ requireInvite: false, userInvitations: 0 });
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
return () => { cancelled = true; };
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
// Run init on mount and on retry
|
||||
useState(() => { init(); });
|
||||
|
||||
const retry = useCallback(() => {
|
||||
setInitCount(c => c + 1);
|
||||
init();
|
||||
}, [init]);
|
||||
|
||||
const handleSetRegistered = useCallback((value: boolean) => {
|
||||
setRegistered(value);
|
||||
const payload = getTokenPayload();
|
||||
@@ -68,6 +83,7 @@ export function useAuthGate(): AuthGateState {
|
||||
|
||||
return {
|
||||
loading,
|
||||
backendError,
|
||||
needsInvite,
|
||||
needsPasswordReset: passwordReset,
|
||||
registered,
|
||||
@@ -75,5 +91,6 @@ export function useAuthGate(): AuthGateState {
|
||||
config,
|
||||
setRegistered: handleSetRegistered,
|
||||
setNeedsPasswordReset: handleSetPasswordReset,
|
||||
retry,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useGameStore } from '@/store';
|
||||
import { api, getAuthToken, setAuthToken } from '@/lib/api';
|
||||
import { api, getAuthToken, setAuthToken, clearAuthToken, decodeTokenPayload } from '@/lib/api';
|
||||
import { AUTO_SAVE_INTERVAL_TICKS } from '@ai-tycoon/shared';
|
||||
|
||||
export function useCloudSave() {
|
||||
@@ -31,8 +31,11 @@ export function useCloudSave() {
|
||||
}
|
||||
|
||||
export async function ensureAuth(): Promise<string | null> {
|
||||
let token = getAuthToken();
|
||||
if (token) return token;
|
||||
const token = getAuthToken();
|
||||
if (token) {
|
||||
if (decodeTokenPayload(token)) return token;
|
||||
clearAuthToken();
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await api.auth.anonymous();
|
||||
|
||||
+26
-3
@@ -63,19 +63,26 @@ export function needsPasswordReset(): boolean {
|
||||
return payload?.mustResetPassword === true;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
async function request<T>(path: string, options: RequestInit & { timeoutMs?: number } = {}): Promise<T> {
|
||||
const { timeoutMs = 10_000, ...fetchOptions } = options;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers as Record<string, string>),
|
||||
...(fetchOptions.headers as Record<string, string>),
|
||||
};
|
||||
|
||||
if (authToken) {
|
||||
headers['Authorization'] = `Bearer ${authToken}`;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
...fetchOptions,
|
||||
headers,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -84,9 +91,25 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
}
|
||||
|
||||
return res.json();
|
||||
} catch (e) {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') {
|
||||
throw new Error('Request timed out — server may be unreachable');
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
export function validateStoredToken(): void {
|
||||
const token = getAuthToken();
|
||||
if (token && !decodeTokenPayload(token)) {
|
||||
clearAuthToken();
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
health: () => request<{ status: string }>('/health', { timeoutMs: 5_000 }),
|
||||
auth: {
|
||||
anonymous: () => request<{ userId: string; token: string }>('/api/auth/anonymous', { method: 'POST' }),
|
||||
login: (login: string, password: string) =>
|
||||
|
||||
Reference in New Issue
Block a user