import { createContext, ReactNode, useContext, useEffect, useRef } from "react"; import { useQuery, useMutation, UseMutationResult, } from "@tanstack/react-query"; import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas"; import { z } from "zod"; import { getQueryFn, apiRequest, queryClient } from "../lib/queryClient"; import { useToast } from "@/hooks/use-toast"; type SelectUser = z.infer; const insertUserSchema = ( UserUncheckedCreateInputObjectSchema as unknown as z.ZodObject<{ username: z.ZodString; password: z.ZodString; }> ).pick({ username: true, password: true, }); type InsertUser = z.infer; type AuthContextType = { user: SelectUser | null; isLoading: boolean; error: Error | null; loginMutation: UseMutationResult; logoutMutation: UseMutationResult; registerMutation: UseMutationResult; }; // type LoginData = Pick; type LoginData = { username: InsertUser["username"]; password: InsertUser["password"]; }; export const AuthContext = createContext(null); export function AuthProvider({ children }: { children: ReactNode }) { const { toast } = useToast(); const { data: user, error, isLoading, } = useQuery({ queryKey: ["/api/users/"], queryFn: getQueryFn({ on401: "returnNull" }), }); const loginMutation = useMutation({ mutationFn: async (credentials: LoginData) => { const res = await apiRequest("POST", "/api/auth/login", credentials); const contentType = res.headers.get("content-type") || ""; const isJson = contentType.includes("application/json"); const data = isJson ? await res.json() : {}; if (!res.ok) { throw new Error(data?.error || "Login failed. Please try again."); } if (!data?.token || !data?.user) { throw new Error("Invalid response from server"); } localStorage.setItem("token", data.token); return data.user; }, onSuccess: (user: SelectUser) => { queryClient.setQueryData(["/api/users/"], user); }, onError: (error: Error) => { console.error("Login error:", error); toast({ title: "Login failed", description: error.message, variant: "destructive", }); }, }); const registerMutation = useMutation({ mutationFn: async (credentials: InsertUser) => { const res = await apiRequest("POST", "/api/auth/register", credentials); const contentType = res.headers.get("content-type") || ""; const isJson = contentType.includes("application/json"); const data = isJson ? await res.json() : {}; if (!res.ok) { throw new Error(data?.error || "Registration failed."); } if (!data?.token || !data?.user) { throw new Error("Invalid response from server"); } localStorage.setItem("token", data.token); return data.user; }, onSuccess: (user: SelectUser) => { queryClient.setQueryData(["/api/users/"], user); }, onError: (error: Error) => { console.error("Registration error:", error); toast({ title: "Registration failed", description: error.message, variant: "destructive", }); }, }); const logoutMutation = useMutation({ mutationFn: async () => { localStorage.removeItem("token"); await apiRequest("POST", "/api/auth/logout"); }, onSuccess: () => { queryClient.setQueryData(["/api/users/"], null); }, onError: (error: Error) => { toast({ title: "Logout failed", description: error.message, variant: "destructive", }); }, }); const IDLE_TIMEOUT = 60 * 60 * 1000; const WARN_BEFORE = 5 * 60 * 1000; const logoutTimer = useRef | null>(null); const warnTimer = useRef | null>(null); const warnedRef = useRef(false); useEffect(() => { if (!user) return; const clearTimers = () => { if (logoutTimer.current) clearTimeout(logoutTimer.current); if (warnTimer.current) clearTimeout(warnTimer.current); }; const resetTimers = () => { clearTimers(); warnedRef.current = false; warnTimer.current = setTimeout(() => { if (!warnedRef.current) { warnedRef.current = true; toast({ title: "Session expiring soon", description: "You will be logged out in 5 minutes due to inactivity.", duration: 10000, }); } }, IDLE_TIMEOUT - WARN_BEFORE); logoutTimer.current = setTimeout(() => { logoutMutation.mutate(); }, IDLE_TIMEOUT); }; const events = ["mousemove", "mousedown", "keydown", "scroll", "touchstart", "click"]; events.forEach((e) => window.addEventListener(e, resetTimers, { passive: true })); resetTimers(); return () => { clearTimers(); events.forEach((e) => window.removeEventListener(e, resetTimers)); }; }, [user]); return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (!context) { throw new Error("useAuth must be used within an AuthProvider"); } return context; }