/** * 认证相关 Hooks */ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useNavigate } from 'react-router-dom'; import * as authApi from '@/api/auth'; import { useAuthStore } from '@/store/authStore'; // 登录 Hook export const useLogin = () => { const navigate = useNavigate(); const setAuth = useAuthStore((state) => state.setAuth); return useMutation({ mutationFn: authApi.login, onSuccess: (data) => { // 先保存 token localStorage.setItem('access_token', data.access_token); localStorage.setItem('refresh_token', data.refresh_token); // 获取用户信息 authApi.getCurrentUser().then((user) => { setAuth(user, data.access_token, data.refresh_token); navigate('/workspaces'); }); }, }); }; // 注册 Hook export const useRegister = () => { const navigate = useNavigate(); return useMutation({ mutationFn: authApi.register, onSuccess: () => { navigate('/login', { state: { message: '注册成功!请查收验证邮件。' }, }); }, }); }; // 登出 Hook export const useLogout = () => { const navigate = useNavigate(); const clearAuth = useAuthStore((state) => state.clearAuth); const queryClient = useQueryClient(); return useMutation({ mutationFn: authApi.logout, onSuccess: () => { clearAuth(); queryClient.clear(); navigate('/login'); }, onError: () => { // 即使登出失败也清除本地状态 clearAuth(); queryClient.clear(); navigate('/login'); }, }); }; // 获取当前用户 Hook export const useCurrentUser = () => { const isAuthenticated = useAuthStore((state) => state.isAuthenticated); const setUser = useAuthStore((state) => state.setUser); return useQuery({ queryKey: ['currentUser'], queryFn: authApi.getCurrentUser, enabled: isAuthenticated, onSuccess: (user) => { setUser(user); }, }); };