1 import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2 import { apiRequest } from "@/lib/queryClient";
3 import { apiurl } from "@/lib/config";
4 import { useToast } from "@/hooks/use-toast";
5 import type { User, InsertUser } from "@shared/schema";
6
7 export function useAuth() {
8 const { toast } = useToast();
9 const queryClient = useQueryClient();
10
11 const {
12 data: user,
13 isLoading,
14 error,
15 refetch,
16 } = useQuery<User | null>({
17 queryKey: ["/api/user"],
18 queryFn: async () => {
19 try {
20 const url = apiurl("/api/user");
21 const res = await fetch(url, {
22 credentials: "include",
23 headers: {
24 Accept: "application/json",
25 },
26 });
27 if (res.status === 401 || !res.ok) {
28 return null;
29 }
30 return await res.json();
31 } catch (err) {
32 return null;
33 }
34 },
35 staleTime: 5 * 60 * 1000,
36 });
37
38 const loginMutation = useMutation({
39 mutationFn: async (credentials: any) => {
40 const res = await apiRequest("POST", "/api/login", credentials);
41 return res.json();
42 },
43 onSuccess: (user: User) => {
44 queryClient.setQueryData(["/api/user"], user);
45 toast({ title: "Welcome back!", description: `Signed in as ${user.firstName || "Technician"}` });
46 },
47 onError: (error: Error) => {
48 toast({
49 title: "Login failed",
50 description: error.message,
51 variant: "destructive",
52 });
53 },
54 });
55
56 const quickLoginMutation = useMutation({
57 mutationFn: async (payload?: { email?: string }) => {
58 const res = await apiRequest("POST", "/api/quick-login", payload || {});
59 return res.json();
60 },
61 onSuccess: (user: User) => {
62 queryClient.setQueryData(["/api/user"], user);
63 toast({ title: "Connected!", description: `Signed in as ${user.firstName || "Technician"} (${user.email})` });
64 },
65 onError: (error: Error) => {
66 toast({
67 title: "Sign in failed",
68 description: error.message,
69 variant: "destructive",
70 });
71 },
72 });
73
74 const registerMutation = useMutation({
75 mutationFn: async (userData: InsertUser) => {
76 const res = await apiRequest("POST", "/api/register", userData);
77 return res.json();
78 },
79 onSuccess: (user: User) => {
80 queryClient.setQueryData(["/api/user"], user);
81 toast({ title: "Account created", description: "You are now logged in." });
82 },
83 onError: (error: Error) => {
84 toast({
85 title: "Registration failed",
86 description: error.message,
87 variant: "destructive",
88 });
89 },
90 });
91
92 const logoutMutation = useMutation({
93 mutationFn: async () => {
94 await apiRequest("POST", "/api/logout");
95 },
96 onSuccess: () => {
97 queryClient.setQueryData(["/api/user"], null);
98 toast({ title: "Signed out", description: "Session closed successfully." });
99 },
100 });
101
102 return {
103 user,
104 isLoading,
105 isAuthenticated: !!user,
106 loginMutation,
107 quickLoginMutation,
108 registerMutation,
109 logoutMutation,
110 refetchUser: refetch,
111 };
112 }