1 import { createContext, use, useEffect, useState } from 'react'; 2 import type { ReactNode } from 'react'; 3 import { Navigate } from 'react-router'; 4 5 type User = { id: number; name: string; email: string }; 6 type Auth = { user: User | null; signIn: (email: string, password: string) => Promise<void>; signOut: () => void }; 7 8 const AuthContext = createContext<Auth | null>(null); 9 10 export function AuthProvider({ children }: { children: ReactNode }) { 11 const [user, setUser] = useState<User | null>(null); 12 const [lastActivity, setLastActivity] = useState(Date.now()); 13 14 async function signIn(email: string, password: string) { 15 const response = await fetch('/api/login', { 16 method: 'POST', 17 headers: { 'Content-Type': 'application/json' }, 18 body: JSON.stringify({ email, password }), 19 }); 20 if (!response.ok) throw new Error('Wrong email or password'); 21 const { token, user } = await response.json(); 22 localStorage.setItem('token', token); 23 setUser(user); 24 } 25 26 function signOut() { 27 localStorage.removeItem('token'); 28 setUser(null); 29 } 30 31 useEffect(() => { 32 fetch('/api/me', { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }) 33 .then((response) => (response.ok ? response.json() : null)) 34 .catch(() => null) 35 .then(setUser); 36 }, []); 37 38 useEffect(() => { 39 const touch = () => setLastActivity(Date.now()); 40 window.addEventListener('pointermove', touch); 41 window.addEventListener('keydown', touch); 42 return () => { 43 window.removeEventListener('pointermove', touch); 44 window.removeEventListener('keydown', touch); 45 }; 46 }, []); 47 48 useEffect(() => { 49 const timer = setTimeout(signOut, 15 * 60 * 1000); 50 return () => clearTimeout(timer); 51 }, [lastActivity]); 52 53 return <AuthContext value={{ user, signIn, signOut }}>{children}</AuthContext>; 54 } 55 56 export function useAuth() { 57 const auth = use(AuthContext); 58 if (!auth) throw new Error('useAuth must be used inside an AuthProvider'); 59 return auth; 60 } 61 62 export function RequireAuth({ children }: { children: ReactNode }) { 63 const { user } = useAuth(); 64 return user ? children : <Navigate to="/login" replace />; 65 }