-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAuth.ts
More file actions
172 lines (154 loc) · 4.48 KB
/
useAuth.ts
File metadata and controls
172 lines (154 loc) · 4.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { useCallback, useEffect } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useAuthStore } from '@/stores/authStore';
import { authService } from '../services/authService';
import type { LoginDto, RegisterDto, AuthResponseDto } from '@/types/common';
/**
* useAuth Hook
*
* Manages authentication state and mutations
* Syncs with authStore and API
*/
export function useAuth() {
const authStore = useAuthStore();
// Set auth header when token changes
useEffect(() => {
if (authStore.accessToken) {
authService.setAuthHeader(authStore.accessToken);
} else {
authService.removeAuthHeader();
}
}, [authStore.accessToken]);
// Login mutation
const loginMutation = useMutation({
mutationFn: (credentials: LoginDto) => authService.login(credentials),
onSuccess: (response) => {
authStore.login(response);
},
onError: (error: Error) => {
authStore.setError(error.message);
},
});
// Register mutation
const registerMutation = useMutation({
mutationFn: (data: RegisterDto) => authService.register(data),
onSuccess: (response) => {
authStore.login(response);
},
onError: (error: Error) => {
authStore.setError(error.message);
},
});
// Get current user
const { data: profile, isLoading: isLoadingProfile } = useQuery({
queryKey: ['auth', 'profile'],
queryFn: () =>
authStore.accessToken ? authService.getCurrentUser(authStore.accessToken) : null,
enabled: !!authStore.accessToken && !authStore.user,
staleTime: 5 * 60 * 1000, // 5 minutes
});
// Sync profile to store
useEffect(() => {
if (profile) {
authStore.setUser(profile);
}
}, [profile, authStore]);
// Logout
const logoutMutation = useMutation({
mutationFn: async () => {
if (authStore.accessToken) {
await authService.logout(authStore.accessToken);
}
},
onSuccess: () => {
authStore.logout();
},
onError: () => {
// Still logout locally even if API fails
authStore.logout();
},
});
// Refresh token
const refreshTokenMutation = useMutation({
mutationFn: async () => {
if (!authStore.refreshToken) throw new Error('No refresh token');
return authService.refreshToken(authStore.refreshToken);
},
onSuccess: (response) => {
authStore.setAccessToken(response.accessToken);
},
onError: () => {
authStore.logout();
},
});
// Verify email
const verifyEmailMutation = useMutation({
mutationFn: (token: string) => authService.verifyEmail(token),
});
const handleLogin = useCallback(
async (email: string, password: string) => {
authStore.setLoading(true);
authStore.clearError();
try {
await loginMutation.mutateAsync({ email, password });
} finally {
authStore.setLoading(false);
}
},
[loginMutation, authStore],
);
const handleRegister = useCallback(
async (email: string, password: string, firstName: string, lastName: string) => {
authStore.setLoading(true);
authStore.clearError();
try {
await registerMutation.mutateAsync({
email,
password,
firstName,
lastName,
});
} finally {
authStore.setLoading(false);
}
},
[registerMutation, authStore],
);
const handleLogout = useCallback(async () => {
authStore.setLoading(true);
try {
await logoutMutation.mutateAsync();
} finally {
authStore.setLoading(false);
}
}, [logoutMutation, authStore]);
const handleRefreshToken = useCallback(async () => {
await refreshTokenMutation.mutateAsync();
}, [refreshTokenMutation]);
const handleVerifyEmail = useCallback(
async (token: string) => {
await verifyEmailMutation.mutateAsync(token);
},
[verifyEmailMutation],
);
return {
// State
user: authStore.user,
isAuthenticated: authStore.isAuthenticated,
isLoading: authStore.isLoading || isLoadingProfile,
error: authStore.error,
accessToken: authStore.accessToken,
refreshToken: authStore.refreshToken,
// Actions
login: handleLogin,
register: handleRegister,
logout: handleLogout,
refreshToken: handleRefreshToken,
verifyEmail: handleVerifyEmail,
clearError: () => authStore.clearError(),
// Mutation states
isLoginLoading: loginMutation.isPending,
isRegisterLoading: registerMutation.isPending,
isLogoutLoading: logoutMutation.isPending,
};
}