'use client' import { useEffect, useState } from 'react' import { useRouter } from 'next/navigation' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8030' export default function LoginPage() { const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [error, setError] = useState('') const [isLoading, setIsLoading] = useState(false) const router = useRouter() useEffect(() => { const token = localStorage.getItem('admin_token') if (token) router.replace('/admin') // eslint-disable-next-line react-hooks/exhaustive-deps }, []) const handleLogin = async (e: React.FormEvent) => { e.preventDefault() setError('') setIsLoading(true) try { const res = await fetch(`${API_BASE}/api/v1/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (!res.ok) { const data = await res.json().catch(() => null) throw new Error(data?.detail || '登录失败') } const data = await res.json() localStorage.setItem('admin_token', data.token) router.replace('/admin') } catch (err: any) { setError(err?.message || '用户名或密码错误') } finally { setIsLoading(false) } } return (
管理员登录 登录后进入管理后台 {error && (
{error}
)}
setUsername(e.target.value)} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2" placeholder="admin" autoComplete="username" />
setPassword(e.target.value)} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2" placeholder="••••••••" autoComplete="current-password" />
) }