import { useState, FormEvent, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { useAuth } from '@/shared/context/AuthContext'; import { apiClient } from '@/shared/api/serverClient'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { toast } from 'sonner'; import { Terminal, Lock, Cpu } from 'lucide-react'; export default function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); const navigate = useNavigate(); const location = useLocation(); const { login, isAuthenticated } = useAuth(); const from = location.state?.from?.pathname || '/'; // 监听认证状态,登录成功后自动跳转 useEffect(() => { if (isAuthenticated && !loading) { navigate(from, { replace: true }); } }, [isAuthenticated, navigate, from, loading]); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setLoading(true); try { const formData = new URLSearchParams(); formData.append('username', email); formData.append('password', password); const response = await apiClient.post('/auth/login', formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); await login(response.data.access_token); toast.success('访问已授予'); // 跳转由 useEffect 监听 isAuthenticated 状态变化自动处理 } catch (error: any) { toast.error(error.response?.data?.detail || '访问被拒绝'); } finally { setLoading(false); } }; return (
输入凭据以继续