-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseAuth.ts
More file actions
243 lines (205 loc) · 6.09 KB
/
Copy pathuseAuth.ts
File metadata and controls
243 lines (205 loc) · 6.09 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// ===================
// © AngelaMos | 2025
// useAuth.ts
// ===================
import {
type UseMutationResult,
type UseQueryResult,
useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query'
import { toast } from 'sonner'
import {
AUTH_ERROR_MESSAGES,
AUTH_SUCCESS_MESSAGES,
AuthResponseError,
isValidLogoutAllResponse,
isValidTokenResponse,
isValidTokenWithUserResponse,
isValidUserResponse,
type LoginRequest,
type LogoutAllResponse,
type PasswordChangeRequest,
type TokenWithUserResponse,
type UserResponse,
} from '@/api/types'
import { API_ENDPOINTS, QUERY_KEYS, ROUTES } from '@/config'
import { apiClient, QUERY_STRATEGIES } from '@/core/api'
import { useAuthStore } from '@/core/lib'
export const authQueries = {
all: () => QUERY_KEYS.AUTH.ALL,
me: () => QUERY_KEYS.AUTH.ME(),
} as const
const fetchCurrentUser = async (): Promise<UserResponse> => {
const response = await apiClient.get<unknown>(API_ENDPOINTS.AUTH.ME)
const data: unknown = response.data
if (!isValidUserResponse(data)) {
throw new AuthResponseError(
AUTH_ERROR_MESSAGES.INVALID_USER_RESPONSE,
API_ENDPOINTS.AUTH.ME
)
}
return data
}
export const useCurrentUser = (): UseQueryResult<UserResponse, Error> => {
const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
return useQuery({
queryKey: authQueries.me(),
queryFn: fetchCurrentUser,
enabled: isAuthenticated,
...QUERY_STRATEGIES.auth,
})
}
const performLogin = async (
credentials: LoginRequest
): Promise<TokenWithUserResponse> => {
const formData = new URLSearchParams()
formData.append('username', credentials.username)
formData.append('password', credentials.password)
const response = await apiClient.post<unknown>(
API_ENDPOINTS.AUTH.LOGIN,
formData,
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}
)
const data: unknown = response.data
if (!isValidTokenWithUserResponse(data)) {
throw new AuthResponseError(
AUTH_ERROR_MESSAGES.INVALID_LOGIN_RESPONSE,
API_ENDPOINTS.AUTH.LOGIN
)
}
return data
}
export const useLogin = (): UseMutationResult<
TokenWithUserResponse,
Error,
LoginRequest
> => {
const queryClient = useQueryClient()
const login = useAuthStore((s) => s.login)
return useMutation({
mutationFn: performLogin,
onSuccess: (data: TokenWithUserResponse): void => {
login(data.user, data.access_token)
queryClient.setQueryData(authQueries.me(), data.user)
const welcomeMessage = AUTH_SUCCESS_MESSAGES.WELCOME_BACK(
data.user.full_name
)
toast.success(welcomeMessage)
},
onError: (error: Error): void => {
const message =
error instanceof AuthResponseError ? error.message : 'Login failed'
toast.error(message)
},
})
}
const performLogout = async (): Promise<void> => {
await apiClient.post(API_ENDPOINTS.AUTH.LOGOUT)
}
export const useLogout = (): UseMutationResult<void, Error, void> => {
const queryClient = useQueryClient()
const logout = useAuthStore((s) => s.logout)
return useMutation({
mutationFn: performLogout,
onSuccess: (): void => {
logout()
queryClient.removeQueries({ queryKey: authQueries.all() })
toast.success(AUTH_SUCCESS_MESSAGES.LOGOUT_SUCCESS)
window.location.href = ROUTES.LOGIN
},
onError: (): void => {
logout()
queryClient.removeQueries({ queryKey: authQueries.all() })
window.location.href = ROUTES.LOGIN
},
})
}
const performLogoutAll = async (): Promise<LogoutAllResponse> => {
const response = await apiClient.post<unknown>(API_ENDPOINTS.AUTH.LOGOUT_ALL)
const data: unknown = response.data
if (!isValidLogoutAllResponse(data)) {
throw new AuthResponseError(
AUTH_ERROR_MESSAGES.INVALID_LOGOUT_RESPONSE,
API_ENDPOINTS.AUTH.LOGOUT_ALL
)
}
return data
}
export const useLogoutAll = (): UseMutationResult<
LogoutAllResponse,
Error,
void
> => {
const queryClient = useQueryClient()
const logout = useAuthStore((s) => s.logout)
return useMutation({
mutationFn: performLogoutAll,
onSuccess: (data: LogoutAllResponse): void => {
logout()
queryClient.removeQueries({ queryKey: authQueries.all() })
toast.success(`Logged out from ${data.revoked_sessions} session(s)`)
window.location.href = ROUTES.LOGIN
},
onError: (error: Error): void => {
const message =
error instanceof AuthResponseError
? error.message
: 'Failed to logout all sessions'
toast.error(message)
},
})
}
const performPasswordChange = async (
data: PasswordChangeRequest
): Promise<void> => {
await apiClient.post(API_ENDPOINTS.AUTH.CHANGE_PASSWORD, data)
}
export const useChangePassword = (): UseMutationResult<
void,
Error,
PasswordChangeRequest
> => {
return useMutation({
mutationFn: performPasswordChange,
onSuccess: (): void => {
toast.success(AUTH_SUCCESS_MESSAGES.PASSWORD_CHANGED)
},
onError: (error: Error): void => {
const message =
error instanceof AuthResponseError
? error.message
: 'Failed to change password'
toast.error(message)
},
})
}
export const useRefreshAuth = (): (() => Promise<void>) => {
const queryClient = useQueryClient()
const { setAccessToken, login, logout } = useAuthStore()
return async (): Promise<void> => {
try {
const response = await apiClient.post<unknown>(API_ENDPOINTS.AUTH.REFRESH)
const data: unknown = response.data
if (!isValidTokenResponse(data)) {
throw new AuthResponseError(
AUTH_ERROR_MESSAGES.INVALID_TOKEN_RESPONSE,
API_ENDPOINTS.AUTH.REFRESH
)
}
setAccessToken(data.access_token)
const userResponse = await apiClient.get<unknown>(API_ENDPOINTS.AUTH.ME)
const userData: unknown = userResponse.data
if (isValidUserResponse(userData)) {
login(userData, data.access_token)
queryClient.setQueryData(authQueries.me(), userData)
}
} catch {
logout()
queryClient.removeQueries({ queryKey: authQueries.all() })
}
}
}